2 * mini.c: The new Mono code generator.
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * (C) 2002 Ximian, Inc.
17 #ifdef sun // Solaris x86
18 #include <sys/types.h>
19 #include <sys/ucontext.h>
22 #ifdef HAVE_VALGRIND_MEMCHECK_H
23 #include <valgrind/memcheck.h>
26 #include <mono/metadata/assembly.h>
27 #include <mono/metadata/loader.h>
28 #include <mono/metadata/cil-coff.h>
29 #include <mono/metadata/tabledefs.h>
30 #include <mono/metadata/class.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/exception.h>
33 #include <mono/metadata/opcodes.h>
34 #include <mono/metadata/mono-endian.h>
35 #include <mono/metadata/tokentype.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/marshal.h>
39 #include <mono/metadata/socket-io.h>
40 #include <mono/metadata/appdomain.h>
41 #include <mono/metadata/debug-helpers.h>
42 #include <mono/io-layer/io-layer.h>
43 #include "mono/metadata/profiler.h"
44 #include <mono/metadata/profiler-private.h>
45 #include <mono/metadata/mono-config.h>
46 #include <mono/metadata/environment.h>
47 #include <mono/metadata/mono-debug.h>
48 #include <mono/metadata/monitor.h>
49 #include <mono/metadata/security-manager.h>
50 #include <mono/metadata/threads-types.h>
51 #include <mono/metadata/rawbuffer.h>
52 #include <mono/utils/mono-math.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-counters.h>
55 #include <mono/utils/mono-logger.h>
56 #include <mono/os/gc_wrapper.h>
64 #include "jit-icalls.h"
68 #define BRANCH_COST 100
69 #define INLINE_LENGTH_LIMIT 20
70 #define INLINE_FAILURE do {\
71 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
76 * this is used to determine when some branch optimizations are possible: we exclude FP compares
77 * because they have weird semantics with NaNs.
79 #define MONO_IS_COND_BRANCH_OP(ins) (((ins)->opcode >= CEE_BEQ && (ins)->opcode <= CEE_BLT_UN) || ((ins)->opcode >= OP_LBEQ && (ins)->opcode <= OP_LBLT_UN) || ((ins)->opcode >= OP_FBEQ && (ins)->opcode <= OP_FBLT_UN) || ((ins)->opcode >= OP_IBEQ && (ins)->opcode <= OP_IBLT_UN))
80 #define MONO_IS_COND_BRANCH_NOFP(ins) (MONO_IS_COND_BRANCH_OP(ins) && (ins)->inst_left->inst_left->type != STACK_R8)
82 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
84 static void setup_stat_profiler (void);
85 gboolean mono_arch_print_tree(MonoInst *tree, int arity);
86 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
87 static gpointer mono_jit_compile_method (MonoMethod *method);
88 static gpointer mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method);
89 static gpointer mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method);
91 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src,
92 const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
94 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
96 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
97 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
98 guint inline_offset, gboolean is_virtual_call);
100 /* helper methods signature */
101 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
102 static MonoMethodSignature *helper_sig_domain_get = NULL;
104 static guint32 default_opt = 0;
105 static gboolean default_opt_set = FALSE;
107 guint32 mono_jit_tls_id = -1;
108 MonoTraceSpec *mono_jit_trace_calls = NULL;
109 gboolean mono_break_on_exc = FALSE;
111 gboolean mono_compile_aot = FALSE;
113 gboolean mono_use_security_manager = FALSE;
115 static int mini_verbose = 0;
117 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
118 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
119 static CRITICAL_SECTION jit_mutex;
121 static GHashTable *class_init_hash_addr = NULL;
123 static MonoCodeManager *global_codeman = NULL;
125 static GHashTable *jit_icall_name_hash = NULL;
127 static MonoDebugOptions debug_options;
130 * Address of the trampoline code. This is used by the debugger to check
131 * whether a method is a trampoline.
133 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
136 mono_running_on_valgrind (void)
138 #ifdef HAVE_VALGRIND_MEMCHECK_H
139 if (RUNNING_ON_VALGRIND)
149 * mono_create_ftnptr:
151 * Given a function address, create a function descriptor for it.
152 * This is only needed on IA64.
155 mono_create_ftnptr (MonoDomain *domain, gpointer addr)
160 mono_domain_lock (domain);
161 desc = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
162 mono_domain_unlock (domain);
179 find_tramp (gpointer key, gpointer value, gpointer user_data)
181 FindTrampUserData *ud = (FindTrampUserData*)user_data;
184 ud->method = (MonoMethod*)key;
188 G_GNUC_UNUSED static char*
189 get_method_from_ip (void *ip)
194 MonoDomain *domain = mono_domain_get ();
195 MonoDebugSourceLocation *location;
196 FindTrampUserData user_data;
198 ji = mono_jit_info_table_find (domain, ip);
201 user_data.method = NULL;
202 mono_domain_lock (domain);
203 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
204 mono_domain_unlock (domain);
205 if (user_data.method) {
206 char *mname = mono_method_full_name (user_data.method, TRUE);
207 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
214 method = mono_method_full_name (ji->method, TRUE);
215 /* FIXME: unused ? */
216 location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
218 res = g_strdup_printf (" %s + 0x%x (%p %p) [%p - %s]", method, (int)((char*)ip - (char*)ji->code_start), ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
220 mono_debug_free_source_location (location);
229 return get_method_from_ip (ip);
234 mono_print_method_from_ip (void *ip)
238 MonoDebugSourceLocation *source;
239 MonoDomain *domain = mono_domain_get ();
240 FindTrampUserData user_data;
242 ji = mono_jit_info_table_find (domain, ip);
245 user_data.method = NULL;
246 mono_domain_lock (domain);
247 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
248 mono_domain_unlock (domain);
249 if (user_data.method) {
250 char *mname = mono_method_full_name (user_data.method, TRUE);
251 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
255 g_print ("No method at %p\n", ip);
258 method = mono_method_full_name (ji->method, TRUE);
259 source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
261 g_print ("IP %p at offset 0x%x of method %s (%p %p)[domain %p - %s]\n", ip, (int)((char*)ip - (char*)ji->code_start), method, ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
264 g_print ("%s:%d\n", source->source_file, source->row);
266 mono_debug_free_source_location (source);
271 * mono_method_same_domain:
273 * Determine whenever two compiled methods are in the same domain, thus
274 * the address of the callee can be embedded in the caller.
276 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
278 if (!caller || !callee)
282 * If the call was made from domain-neutral to domain-specific
283 * code, we can't patch the call site.
285 if (caller->domain_neutral && !callee->domain_neutral)
288 if ((caller->method->klass == mono_defaults.appdomain_class) &&
289 (strstr (caller->method->name, "InvokeInDomain"))) {
290 /* The InvokeInDomain methods change the current appdomain */
298 * mono_global_codeman_reserve:
300 * Allocate code memory from the global code manager.
302 void *mono_global_codeman_reserve (int size)
306 if (!global_codeman) {
307 /* This can happen during startup */
308 global_codeman = mono_code_manager_new ();
309 return mono_code_manager_reserve (global_codeman, size);
313 ptr = mono_code_manager_reserve (global_codeman, size);
320 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
322 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
329 #define MONO_INIT_VARINFO(vi,id) do { \
330 (vi)->range.first_use.pos.bid = 0xffff; \
335 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
336 #define UNVERIFIED do { goto unverified; } while (0)
339 * Basic blocks have two numeric identifiers:
340 * dfn: Depth First Number
341 * block_num: unique ID assigned at bblock creation
343 #define NEW_BBLOCK(cfg) (mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)))
344 #define ADD_BBLOCK(cfg,bbhash,b) do { \
345 g_hash_table_insert (bbhash, (b)->cil_code, (b)); \
346 (b)->block_num = cfg->num_bblocks++; \
347 (b)->real_offset = real_offset; \
350 #define GET_BBLOCK(cfg,bbhash,tblock,ip) do { \
351 (tblock) = g_hash_table_lookup (bbhash, (ip)); \
353 if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
354 (tblock) = NEW_BBLOCK (cfg); \
355 (tblock)->cil_code = (ip); \
356 ADD_BBLOCK (cfg, (bbhash), (tblock)); \
360 #define CHECK_BBLOCK(target,ip,tblock) do { \
361 if ((target) < (ip) && !(tblock)->code) { \
362 bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
363 if (cfg->verbose_level > 2) g_print ("queued block %d for check at IL%04x from IL%04x\n", (tblock)->block_num, (int)((target) - header->code), (int)((ip) - header->code)); \
367 #define NEW_ICONST(cfg,dest,val) do { \
368 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
369 (dest)->opcode = OP_ICONST; \
370 (dest)->inst_c0 = (val); \
371 (dest)->type = STACK_I4; \
374 #define NEW_PCONST(cfg,dest,val) do { \
375 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
376 (dest)->opcode = OP_PCONST; \
377 (dest)->inst_p0 = (val); \
378 (dest)->type = STACK_PTR; \
382 #ifdef MONO_ARCH_NEED_GOT_VAR
384 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do { \
385 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
386 (dest)->opcode = OP_PATCH_INFO; \
387 (dest)->inst_left = (gpointer)(el1); \
388 (dest)->inst_right = (gpointer)(el2); \
391 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
392 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
393 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
394 if (cfg->compile_aot) { \
395 MonoInst *group, *got_var, *got_loc; \
396 got_loc = mono_get_got_var (cfg); \
397 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
398 NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
399 (dest)->inst_p0 = got_var; \
400 (dest)->inst_p1 = group; \
402 (dest)->inst_p0 = (cons); \
403 (dest)->inst_i1 = (gpointer)(patch_type); \
405 (dest)->type = STACK_PTR; \
408 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type) do { \
409 MonoInst *group, *got_var, *got_loc; \
410 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
411 (dest)->opcode = OP_GOT_ENTRY; \
412 got_loc = mono_get_got_var (cfg); \
413 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
414 NEW_PATCH_INFO ((cfg), group, NULL, patch_type); \
415 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
416 (dest)->inst_p0 = got_var; \
417 (dest)->inst_p1 = group; \
418 (dest)->type = (stack_type); \
423 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
424 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
425 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST; \
426 (dest)->inst_p0 = (cons); \
427 (dest)->inst_i1 = (gpointer)(patch_type); \
428 (dest)->type = STACK_PTR; \
431 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type) do { \
432 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
433 (dest)->opcode = OP_AOTCONST; \
434 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
435 (dest)->inst_p1 = (gpointer)(patch_type); \
436 (dest)->type = (stack_type); \
441 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
443 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
445 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
447 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
449 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
451 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
453 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ)
455 #define NEW_TYPE_FROM_HANDLE_CONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_TYPE_FROM_HANDLE, (image), (token), STACK_OBJ)
457 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR)
459 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
460 if (cfg->compile_aot) { \
461 NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ); \
463 NEW_PCONST (cfg, args [0], (entry).blob); \
467 #define NEW_DOMAINCONST(cfg,dest) do { \
468 if (cfg->opt & MONO_OPT_SHARED) { \
469 /* avoid depending on undefined C behavior in sequence points */ \
470 MonoInst* __domain_var = mono_get_domainvar (cfg); \
471 NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
473 NEW_PCONST (cfg, dest, (cfg)->domain); \
477 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
479 #define NEW_ARGLOAD(cfg,dest,num) do { \
480 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
481 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
482 (dest)->ssa_op = MONO_SSA_LOAD; \
483 (dest)->inst_i0 = arg_array [(num)]; \
484 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype); \
485 type_to_eval_stack_type (param_types [(num)], (dest)); \
486 (dest)->klass = (dest)->inst_i0->klass; \
489 #define NEW_LOCLOAD(cfg,dest,num) do { \
490 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
491 (dest)->ssa_op = MONO_SSA_LOAD; \
492 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
493 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype); \
494 type_to_eval_stack_type (header->locals [(num)], (dest)); \
495 (dest)->klass = (dest)->inst_i0->klass; \
498 #define NEW_LOCLOADA(cfg,dest,num) do { \
499 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
500 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
501 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
502 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
503 (dest)->opcode = OP_LDADDR; \
504 (dest)->type = STACK_MP; \
505 (dest)->klass = (dest)->inst_i0->klass; \
506 if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
507 (cfg)->disable_ssa = TRUE; \
510 #define NEW_RETLOADA(cfg,dest) do { \
511 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
512 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
513 (dest)->inst_i0 = (cfg)->ret; \
514 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
515 (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I; \
516 (dest)->type = STACK_MP; \
517 (dest)->klass = (dest)->inst_i0->klass; \
518 (cfg)->disable_ssa = TRUE; \
521 #define NEW_ARGLOADA(cfg,dest,num) do { \
522 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
523 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
524 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
525 (dest)->inst_i0 = arg_array [(num)]; \
526 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
527 (dest)->opcode = OP_LDADDR; \
528 (dest)->type = STACK_MP; \
529 (dest)->klass = (dest)->inst_i0->klass; \
530 (cfg)->disable_ssa = TRUE; \
533 #define NEW_TEMPLOAD(cfg,dest,num) do { \
534 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
535 (dest)->ssa_op = MONO_SSA_LOAD; \
536 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
537 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype); \
538 type_to_eval_stack_type ((dest)->inst_i0->inst_vtype, (dest)); \
539 (dest)->klass = (dest)->inst_i0->klass; \
542 #define NEW_TEMPLOADA(cfg,dest,num) do { \
543 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
544 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
545 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
546 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
547 (dest)->opcode = OP_LDADDR; \
548 (dest)->type = STACK_MP; \
549 (dest)->klass = (dest)->inst_i0->klass; \
550 if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
551 (cfg)->disable_ssa = TRUE; \
555 #define NEW_INDLOAD(cfg,dest,addr,vtype) do { \
556 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
557 (dest)->inst_left = addr; \
558 (dest)->opcode = mono_type_to_ldind (vtype); \
559 type_to_eval_stack_type (vtype, (dest)); \
560 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
563 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do { \
564 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
565 (dest)->inst_i0 = addr; \
566 (dest)->opcode = mono_type_to_stind (vtype); \
567 (dest)->inst_i1 = (value); \
568 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
571 #define NEW_TEMPSTORE(cfg,dest,num,inst) do { \
572 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
573 (dest)->ssa_op = MONO_SSA_STORE; \
574 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
575 (dest)->opcode = mono_type_to_stind ((dest)->inst_i0->inst_vtype); \
576 (dest)->inst_i1 = (inst); \
577 (dest)->klass = (dest)->inst_i0->klass; \
580 #define NEW_LOCSTORE(cfg,dest,num,inst) do { \
581 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
582 (dest)->opcode = mono_type_to_stind (header->locals [(num)]); \
583 (dest)->ssa_op = MONO_SSA_STORE; \
584 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
585 (dest)->inst_i1 = (inst); \
586 (dest)->klass = (dest)->inst_i0->klass; \
589 #define NEW_ARGSTORE(cfg,dest,num,inst) do { \
590 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
591 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
592 (dest)->opcode = mono_type_to_stind (param_types [(num)]); \
593 (dest)->ssa_op = MONO_SSA_STORE; \
594 (dest)->inst_i0 = arg_array [(num)]; \
595 (dest)->inst_i1 = (inst); \
596 (dest)->klass = (dest)->inst_i0->klass; \
599 #define NEW_DUMMY_USE(cfg,dest,load) do { \
600 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
601 (dest)->opcode = OP_DUMMY_USE; \
602 (dest)->inst_left = (load); \
605 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
606 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
607 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
608 (dest)->opcode = OP_DUMMY_STORE; \
609 (dest)->klass = (dest)->inst_i0->klass; \
612 #define ADD_BINOP(op) do { \
613 MONO_INST_NEW (cfg, ins, (op)); \
614 ins->cil_code = ip; \
616 ins->inst_i0 = sp [0]; \
617 ins->inst_i1 = sp [1]; \
619 type_from_op (ins); \
623 #define ADD_UNOP(op) do { \
624 MONO_INST_NEW (cfg, ins, (op)); \
625 ins->cil_code = ip; \
627 ins->inst_i0 = sp [0]; \
629 type_from_op (ins); \
633 #define ADD_BINCOND(next_block) do { \
636 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
637 cmp->inst_i0 = sp [0]; \
638 cmp->inst_i1 = sp [1]; \
639 cmp->cil_code = ins->cil_code; \
640 type_from_op (cmp); \
642 ins->inst_i0 = cmp; \
643 MONO_ADD_INS (bblock, ins); \
644 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
645 GET_BBLOCK (cfg, bbhash, tblock, target); \
646 link_bblock (cfg, bblock, tblock); \
647 ins->inst_true_bb = tblock; \
648 CHECK_BBLOCK (target, ip, tblock); \
649 if ((next_block)) { \
650 link_bblock (cfg, bblock, (next_block)); \
651 ins->inst_false_bb = (next_block); \
652 start_new_bblock = 1; \
654 GET_BBLOCK (cfg, bbhash, tblock, ip); \
655 link_bblock (cfg, bblock, tblock); \
656 ins->inst_false_bb = tblock; \
657 start_new_bblock = 2; \
661 /* FIXME: handle float, long ... */
662 #define ADD_UNCOND(istrue) do { \
665 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
666 cmp->inst_i0 = sp [0]; \
667 switch (cmp->inst_i0->type) { \
669 cmp->inst_i1 = zero_int64; break; \
671 cmp->inst_i1 = zero_r8; break; \
674 cmp->inst_i1 = zero_ptr; break; \
676 cmp->inst_i1 = zero_obj; break; \
678 cmp->inst_i1 = zero_int32; \
680 cmp->cil_code = ins->cil_code; \
681 type_from_op (cmp); \
683 ins->inst_i0 = cmp; \
684 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ; \
685 MONO_ADD_INS (bblock, ins); \
686 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
687 GET_BBLOCK (cfg, bbhash, tblock, target); \
688 link_bblock (cfg, bblock, tblock); \
689 ins->inst_true_bb = tblock; \
690 CHECK_BBLOCK (target, ip, tblock); \
691 GET_BBLOCK (cfg, bbhash, tblock, ip); \
692 link_bblock (cfg, bblock, tblock); \
693 ins->inst_false_bb = tblock; \
694 start_new_bblock = 2; \
697 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
698 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
699 (dest)->opcode = CEE_LDELEMA; \
700 (dest)->inst_left = (sp) [0]; \
701 (dest)->inst_right = (sp) [1]; \
702 (dest)->type = STACK_MP; \
703 (dest)->klass = (k); \
704 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
707 #define NEW_GROUP(cfg,dest,el1,el2) do { \
708 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
709 (dest)->opcode = OP_GROUP; \
710 (dest)->inst_left = (el1); \
711 (dest)->inst_right = (el2); \
716 compare_bblock (gconstpointer a, gconstpointer b)
718 const MonoBasicBlock *b1 = a;
719 const MonoBasicBlock *b2 = b;
721 return b2->cil_code - b1->cil_code;
726 * link_bblock: Links two basic blocks
728 * links two basic blocks in the control flow graph, the 'from'
729 * argument is the starting block and the 'to' argument is the block
730 * the control flow ends to after 'from'.
733 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
735 MonoBasicBlock **newa;
739 if (from->cil_code) {
741 g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
743 g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
746 g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
748 g_print ("edge from entry to exit\n");
752 for (i = 0; i < from->out_count; ++i) {
753 if (to == from->out_bb [i]) {
759 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
760 for (i = 0; i < from->out_count; ++i) {
761 newa [i] = from->out_bb [i];
769 for (i = 0; i < to->in_count; ++i) {
770 if (from == to->in_bb [i]) {
776 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
777 for (i = 0; i < to->in_count; ++i) {
778 newa [i] = to->in_bb [i];
787 * mono_unlink_bblock:
789 * Unlink two basic blocks.
792 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
798 for (i = 0; i < from->out_count; ++i) {
799 if (to == from->out_bb [i]) {
806 for (i = 0; i < from->out_count; ++i) {
807 if (from->out_bb [i] != to)
808 from->out_bb [pos ++] = from->out_bb [i];
810 g_assert (pos == from->out_count - 1);
815 for (i = 0; i < to->in_count; ++i) {
816 if (from == to->in_bb [i]) {
823 for (i = 0; i < to->in_count; ++i) {
824 if (to->in_bb [i] != from)
825 to->in_bb [pos ++] = to->in_bb [i];
827 g_assert (pos == to->in_count - 1);
833 * mono_find_block_region:
835 * We mark each basic block with a region ID. We use that to avoid BB
836 * optimizations when blocks are in different regions.
839 * A region token that encodes where this region is, and information
840 * about the clause owner for this block.
842 * The region encodes the try/catch/filter clause that owns this block
843 * as well as the type. -1 is a special value that represents a block
844 * that is in none of try/catch/filter.
847 mono_find_block_region (MonoCompile *cfg, int offset)
849 MonoMethod *method = cfg->method;
850 MonoMethodHeader *header = mono_method_get_header (method);
851 MonoExceptionClause *clause;
854 /* first search for handlers and filters */
855 for (i = 0; i < header->num_clauses; ++i) {
856 clause = &header->clauses [i];
857 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
858 (offset < (clause->handler_offset)))
859 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
861 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
862 if (clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)
863 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
865 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
869 /* search the try blocks */
870 for (i = 0; i < header->num_clauses; ++i) {
871 clause = &header->clauses [i];
872 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
873 return ((i + 1) << 8) | clause->flags;
880 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
882 MonoMethod *method = cfg->method;
883 MonoMethodHeader *header = mono_method_get_header (method);
884 MonoExceptionClause *clause;
885 MonoBasicBlock *handler;
889 for (i = 0; i < header->num_clauses; ++i) {
890 clause = &header->clauses [i];
891 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) &&
892 (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
893 if (clause->flags == type) {
894 handler = g_hash_table_lookup (cfg->bb_hash, header->code + clause->handler_offset);
896 res = g_list_append (res, handler);
904 mono_find_spvar_for_region (MonoCompile *cfg, int region)
906 return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
910 mono_create_spvar_for_region (MonoCompile *cfg, int region)
914 var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
918 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
919 /* prevent it from being register allocated */
920 var->flags |= MONO_INST_INDIRECT;
922 g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
926 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
928 return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
932 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
936 var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
940 var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
941 /* prevent it from being register allocated */
942 var->flags |= MONO_INST_INDIRECT;
944 g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
950 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
954 array [*dfn] = start;
955 /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
956 for (i = 0; i < start->out_count; ++i) {
957 if (start->out_bb [i]->dfn)
960 start->out_bb [i]->dfn = *dfn;
961 start->out_bb [i]->df_parent = start;
962 array [*dfn] = start->out_bb [i];
963 df_visit (start->out_bb [i], dfn, array);
969 MonoBasicBlock *best;
973 previous_foreach (gconstpointer key, gpointer val, gpointer data)
975 PrevStruct *p = data;
976 MonoBasicBlock *bb = val;
977 //printf ("FIDPREV %d %p %p %p %p %p %d %d %d\n", bb->block_num, p->code, bb, p->best, bb->cil_code, p->best->cil_code,
978 //bb->method == p->best->method, bb->cil_code < p->code, bb->cil_code > p->best->cil_code);
980 if (bb->cil_code && bb->cil_code < p->code && bb->cil_code > p->best->cil_code)
984 static MonoBasicBlock*
985 find_previous (GHashTable *bb_hash, MonoBasicBlock *start, const guchar *code) {
991 g_hash_table_foreach (bb_hash, (GHFunc)previous_foreach, &p);
996 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1005 * FIXME: take into account all the details:
1006 * second may have been the target of more than one bblock
1008 second->out_count = first->out_count;
1009 second->out_bb = first->out_bb;
1011 for (i = 0; i < first->out_count; ++i) {
1012 bb = first->out_bb [i];
1013 for (j = 0; j < bb->in_count; ++j) {
1014 if (bb->in_bb [j] == first)
1015 bb->in_bb [j] = second;
1019 first->out_count = 0;
1020 first->out_bb = NULL;
1021 link_bblock (cfg, first, second);
1023 second->last_ins = first->last_ins;
1025 /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1026 for (inst = first->code; inst && inst->next; inst = inst->next) {
1027 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1028 g_print ("found %p: %s", inst->next->cil_code, code);
1030 if (inst->cil_code < second->cil_code && inst->next->cil_code >= second->cil_code) {
1031 second->code = inst->next;
1033 first->last_ins = inst;
1034 second->next_bb = first->next_bb;
1035 first->next_bb = second;
1039 if (!second->code) {
1040 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1046 reverse_branch_op (guint32 opcode)
1048 static const int reverse_map [] = {
1049 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1050 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1052 static const int reverse_fmap [] = {
1053 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1054 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1056 static const int reverse_lmap [] = {
1057 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1058 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1060 static const int reverse_imap [] = {
1061 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1062 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1065 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1066 opcode = reverse_map [opcode - CEE_BEQ];
1067 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1068 opcode = reverse_fmap [opcode - OP_FBEQ];
1069 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1070 opcode = reverse_lmap [opcode - OP_LBEQ];
1071 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1072 opcode = reverse_imap [opcode - OP_IBEQ];
1074 g_assert_not_reached ();
1080 * Returns the type used in the eval stack when @type is loaded.
1081 * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1084 type_to_eval_stack_type (MonoType *type, MonoInst *inst)
1088 inst->klass = klass = mono_class_from_mono_type (type);
1090 inst->type = STACK_MP;
1095 switch (type->type) {
1096 case MONO_TYPE_VOID:
1097 inst->type = STACK_INV;
1101 case MONO_TYPE_BOOLEAN:
1104 case MONO_TYPE_CHAR:
1107 inst->type = STACK_I4;
1112 case MONO_TYPE_FNPTR:
1113 inst->type = STACK_PTR;
1115 case MONO_TYPE_CLASS:
1116 case MONO_TYPE_STRING:
1117 case MONO_TYPE_OBJECT:
1118 case MONO_TYPE_SZARRAY:
1119 case MONO_TYPE_ARRAY:
1120 inst->type = STACK_OBJ;
1124 inst->type = STACK_I8;
1128 inst->type = STACK_R8;
1130 case MONO_TYPE_VALUETYPE:
1131 if (type->data.klass->enumtype) {
1132 type = type->data.klass->enum_basetype;
1135 inst->klass = klass;
1136 inst->type = STACK_VTYPE;
1139 case MONO_TYPE_TYPEDBYREF:
1140 inst->klass = mono_defaults.typed_reference_class;
1141 inst->type = STACK_VTYPE;
1143 case MONO_TYPE_GENERICINST:
1144 type = &type->data.generic_class->container_class->byval_arg;
1147 g_error ("unknown type 0x%02x in eval stack type", type->type);
1152 * The following tables are used to quickly validate the IL code in type_from_op ().
1155 bin_num_table [STACK_MAX] [STACK_MAX] = {
1156 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1157 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1158 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1159 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1160 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV},
1161 {STACK_INV, STACK_MP, STACK_INV, STACK_MP, STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1162 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1163 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1168 STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1171 /* reduce the size of this table */
1173 bin_int_table [STACK_MAX] [STACK_MAX] = {
1174 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1175 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1176 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1177 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1178 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1179 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1180 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1181 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1185 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1186 /* Inv i L p F & O vt */
1188 {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1189 {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1190 {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1191 {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1192 {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1193 {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1194 {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1197 /* reduce the size of this table */
1199 shift_table [STACK_MAX] [STACK_MAX] = {
1200 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1201 {STACK_INV, STACK_I4, STACK_INV, STACK_I4, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1202 {STACK_INV, STACK_I8, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1203 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1204 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1205 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1206 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1207 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1211 * Tables to map from the non-specific opcode to the matching
1212 * type-specific opcode.
1214 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1215 static const guint16
1216 binops_op_map [STACK_MAX] = {
1217 0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1220 /* handles from CEE_NEG to CEE_CONV_U8 */
1221 static const guint16
1222 unops_op_map [STACK_MAX] = {
1223 0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1226 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1227 static const guint16
1228 ovfops_op_map [STACK_MAX] = {
1229 0, 0, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2
1232 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1233 static const guint16
1234 ovf2ops_op_map [STACK_MAX] = {
1235 0, 0, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN
1238 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1239 static const guint16
1240 ovf3ops_op_map [STACK_MAX] = {
1241 0, 0, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1
1244 /* handles from CEE_CEQ to CEE_CLT_UN */
1245 static const guint16
1246 ceqops_op_map [STACK_MAX] = {
1247 0, 0, OP_LCEQ-CEE_CEQ, OP_PCEQ-CEE_CEQ, OP_FCEQ-CEE_CEQ, OP_LCEQ-CEE_CEQ
1251 * Sets ins->type (the type on the eval stack) according to the
1252 * type of the opcode and the arguments to it.
1253 * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1255 * FIXME: this function sets ins->type unconditionally in some cases, but
1256 * it should set it to invalid for some types (a conv.x on an object)
1259 type_from_op (MonoInst *ins) {
1260 switch (ins->opcode) {
1267 /* FIXME: check unverifiable args for STACK_MP */
1268 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1269 ins->opcode += binops_op_map [ins->type];
1276 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1277 ins->opcode += binops_op_map [ins->type];
1282 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1283 ins->opcode += binops_op_map [ins->type];
1287 /* FIXME: handle some specifics with ins->next->type */
1288 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1289 if ((ins->inst_i0->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((ins->inst_i0->type == STACK_PTR) || (ins->inst_i0->type == STACK_OBJ) || (ins->inst_i0->type == STACK_MP))))
1290 ins->opcode = OP_LCOMPARE;
1297 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1298 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1302 ins->type = neg_table [ins->inst_i0->type];
1303 ins->opcode += unops_op_map [ins->type];
1306 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1307 ins->type = ins->inst_i0->type;
1309 ins->type = STACK_INV;
1310 ins->opcode += unops_op_map [ins->type];
1316 ins->type = STACK_I4;
1317 ins->opcode += unops_op_map [ins->inst_i0->type];
1320 ins->type = STACK_R8;
1321 switch (ins->inst_i0->type) {
1326 ins->opcode = OP_LCONV_TO_R_UN;
1330 case CEE_CONV_OVF_I1:
1331 case CEE_CONV_OVF_U1:
1332 case CEE_CONV_OVF_I2:
1333 case CEE_CONV_OVF_U2:
1334 case CEE_CONV_OVF_I4:
1335 case CEE_CONV_OVF_U4:
1336 ins->type = STACK_I4;
1337 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1339 case CEE_CONV_OVF_I_UN:
1340 case CEE_CONV_OVF_U_UN:
1341 ins->type = STACK_PTR;
1342 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1344 case CEE_CONV_OVF_I1_UN:
1345 case CEE_CONV_OVF_I2_UN:
1346 case CEE_CONV_OVF_I4_UN:
1347 case CEE_CONV_OVF_U1_UN:
1348 case CEE_CONV_OVF_U2_UN:
1349 case CEE_CONV_OVF_U4_UN:
1350 ins->type = STACK_I4;
1351 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1354 ins->type = STACK_PTR;
1355 switch (ins->inst_i0->type) {
1361 ins->opcode = OP_LCONV_TO_U;
1364 ins->opcode = OP_FCONV_TO_U;
1370 ins->type = STACK_I8;
1371 ins->opcode += unops_op_map [ins->inst_i0->type];
1373 case CEE_CONV_OVF_I8:
1374 case CEE_CONV_OVF_U8:
1375 ins->type = STACK_I8;
1376 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1378 case CEE_CONV_OVF_U8_UN:
1379 case CEE_CONV_OVF_I8_UN:
1380 ins->type = STACK_I8;
1381 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1385 ins->type = STACK_R8;
1386 ins->opcode += unops_op_map [ins->inst_i0->type];
1389 ins->type = STACK_R8;
1393 ins->type = STACK_I4;
1394 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1397 case CEE_CONV_OVF_I:
1398 case CEE_CONV_OVF_U:
1399 ins->type = STACK_PTR;
1400 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1403 case CEE_ADD_OVF_UN:
1405 case CEE_MUL_OVF_UN:
1407 case CEE_SUB_OVF_UN:
1408 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1409 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1412 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1419 STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1422 /* map ldelem.x to the matching ldind.x opcode */
1424 ldelem_to_ldind [] = {
1438 /* map stelem.x to the matching stind.x opcode */
1440 stelem_to_stind [] = {
1454 param_table [STACK_MAX] [STACK_MAX] = {
1459 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1463 switch (args->type) {
1473 for (i = 0; i < sig->param_count; ++i) {
1474 switch (args [i].type) {
1478 if (!sig->params [i]->byref)
1482 if (sig->params [i]->byref)
1484 switch (sig->params [i]->type) {
1485 case MONO_TYPE_CLASS:
1486 case MONO_TYPE_STRING:
1487 case MONO_TYPE_OBJECT:
1488 case MONO_TYPE_SZARRAY:
1489 case MONO_TYPE_ARRAY:
1496 if (sig->params [i]->byref)
1498 if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1507 /*if (!param_table [args [i].type] [sig->params [i]->type])
1515 * When we need a pointer to the current domain many times in a method, we
1516 * call mono_domain_get() once and we store the result in a local variable.
1517 * This function returns the variable that represents the MonoDomain*.
1519 inline static MonoInst *
1520 mono_get_domainvar (MonoCompile *cfg)
1522 if (!cfg->domainvar)
1523 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1524 return cfg->domainvar;
1528 * The got_var contains the address of the Global Offset Table when AOT
1531 inline static MonoInst *
1532 mono_get_got_var (MonoCompile *cfg)
1534 #ifdef MONO_ARCH_NEED_GOT_VAR
1535 if (!cfg->compile_aot)
1537 if (!cfg->got_var) {
1538 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1540 return cfg->got_var;
1547 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1550 int num = cfg->num_varinfo;
1552 if ((num + 1) >= cfg->varinfo_count) {
1553 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1554 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1555 cfg->vars = (MonoMethodVar **)g_realloc (cfg->vars, sizeof (MonoMethodVar*) * cfg->varinfo_count);
1558 /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1559 mono_jit_stats.allocate_var++;
1561 MONO_INST_NEW (cfg, inst, opcode);
1562 inst->inst_c0 = num;
1563 inst->inst_vtype = type;
1564 inst->klass = mono_class_from_mono_type (type);
1565 /* if set to 1 the variable is native */
1568 cfg->varinfo [num] = inst;
1570 cfg->vars [num] = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoMethodVar));
1571 MONO_INIT_VARINFO (cfg->vars [num], num);
1574 //g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1579 * Transform a MonoInst into a load from the variable of index var_index.
1582 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1583 memset (dest, 0, sizeof (MonoInst));
1584 dest->ssa_op = MONO_SSA_LOAD;
1585 dest->inst_i0 = cfg->varinfo [var_index];
1586 dest->opcode = mono_type_to_ldind (dest->inst_i0->inst_vtype);
1587 type_to_eval_stack_type (dest->inst_i0->inst_vtype, dest);
1588 dest->klass = dest->inst_i0->klass;
1592 * Create a MonoInst that is a load from the variable of index var_index.
1595 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1597 NEW_TEMPLOAD (cfg,dest,var_index);
1602 * Create a MonoInst that is a store of the given value into the variable of index var_index.
1605 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1607 NEW_TEMPSTORE (cfg, dest, var_index, value);
1612 type_from_stack_type (MonoInst *ins) {
1613 switch (ins->type) {
1614 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1615 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1616 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1617 case STACK_R8: return &mono_defaults.double_class->byval_arg;
1618 case STACK_MP: return &mono_defaults.int_class->byval_arg;
1619 case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1620 case STACK_VTYPE: return &ins->klass->byval_arg;
1622 g_error ("stack type %d to montype not handled\n", ins->type);
1628 mono_type_from_stack_type (MonoInst *ins) {
1629 return type_from_stack_type (ins);
1633 array_access_to_klass (int opcode)
1637 return mono_defaults.byte_class;
1639 return mono_defaults.uint16_class;
1642 return mono_defaults.int_class;
1645 return mono_defaults.sbyte_class;
1648 return mono_defaults.int16_class;
1651 return mono_defaults.int32_class;
1653 return mono_defaults.uint32_class;
1656 return mono_defaults.int64_class;
1659 return mono_defaults.single_class;
1662 return mono_defaults.double_class;
1663 case CEE_LDELEM_REF:
1664 case CEE_STELEM_REF:
1665 return mono_defaults.object_class;
1667 g_assert_not_reached ();
1673 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1677 MONO_ADD_INS (bb, inst);
1680 switch (bb->last_ins->opcode) {
1694 while (prev->next && prev->next != bb->last_ins)
1696 if (prev == bb->code) {
1697 if (bb->last_ins == bb->code) {
1698 inst->next = bb->code;
1701 inst->next = prev->next;
1705 inst->next = bb->last_ins;
1709 // g_warning ("handle conditional jump in add_ins_to_end ()\n");
1711 MONO_ADD_INS (bb, inst);
1717 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1719 MonoInst *inst, *load;
1721 NEW_TEMPLOAD (cfg, load, src);
1723 NEW_TEMPSTORE (cfg, inst, dest, load);
1724 if (inst->opcode == CEE_STOBJ) {
1725 NEW_TEMPLOADA (cfg, inst, dest);
1726 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
1728 inst->cil_code = NULL;
1729 mono_add_ins_to_end (bb, inst);
1734 * We try to share variables when possible
1737 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1742 /* inlining can result in deeper stacks */
1743 if (slot >= mono_method_get_header (cfg->method)->max_stack)
1744 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1746 pos = ins->type - 1 + slot * STACK_MAX;
1748 switch (ins->type) {
1755 if ((vnum = cfg->intvars [pos]))
1756 return cfg->varinfo [vnum];
1757 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1758 cfg->intvars [pos] = res->inst_c0;
1761 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1767 * This function is called to handle items that are left on the evaluation stack
1768 * at basic block boundaries. What happens is that we save the values to local variables
1769 * and we reload them later when first entering the target basic block (with the
1770 * handle_loaded_temps () function).
1771 * It is also used to handle items on the stack in store opcodes, since it is
1772 * possible that the variable to be stored into is already on the stack, in
1773 * which case its old value should be used.
1774 * A single joint point will use the same variables (stored in the array bb->out_stack or
1775 * bb->in_stack, if the basic block is before or after the joint point).
1778 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
1780 MonoBasicBlock *outb;
1781 MonoInst *inst, **locals;
1786 if (cfg->verbose_level > 3)
1787 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
1788 if (!bb->out_scount) {
1789 bb->out_scount = count;
1790 //g_print ("bblock %d has out:", bb->block_num);
1792 for (i = 0; i < bb->out_count; ++i) {
1793 outb = bb->out_bb [i];
1794 /* exception handlers are linked, but they should not be considered for stack args */
1795 if (outb->flags & BB_EXCEPTION_HANDLER)
1797 //g_print (" %d", outb->block_num);
1798 if (outb->in_stack) {
1800 bb->out_stack = outb->in_stack;
1806 bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1807 for (i = 0; i < count; ++i) {
1809 * try to reuse temps already allocated for this purpouse, if they occupy the same
1810 * stack slot and if they are of the same type.
1811 * This won't cause conflicts since if 'local' is used to
1812 * store one of the values in the in_stack of a bblock, then
1813 * the same variable will be used for the same outgoing stack
1815 * This doesn't work when inlining methods, since the bblocks
1816 * in the inlined methods do not inherit their in_stack from
1817 * the bblock they are inlined to. See bug #58863 for an
1820 if (cfg->inlined_method)
1821 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1823 bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1828 for (i = 0; i < bb->out_count; ++i) {
1829 outb = bb->out_bb [i];
1830 /* exception handlers are linked, but they should not be considered for stack args */
1831 if (outb->flags & BB_EXCEPTION_HANDLER)
1833 if (outb->in_scount) {
1834 if (outb->in_scount != bb->out_scount)
1836 continue; /* check they are the same locals */
1838 outb->in_scount = count;
1839 outb->in_stack = bb->out_stack;
1842 locals = bb->out_stack;
1843 for (i = 0; i < count; ++i) {
1844 /* add store ops at the end of the bb, before the branch */
1845 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1846 if (inst->opcode == CEE_STOBJ) {
1847 NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
1848 handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
1850 inst->cil_code = sp [i]->cil_code;
1851 mono_add_ins_to_end (bb, inst);
1853 if (cfg->verbose_level > 3)
1854 g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1858 * It is possible that the out bblocks already have in_stack assigned, and
1859 * the in_stacks differ. In this case, we will store to all the different
1866 /* Find a bblock which has a different in_stack */
1868 while (bindex < bb->out_count) {
1869 outb = bb->out_bb [bindex];
1870 /* exception handlers are linked, but they should not be considered for stack args */
1871 if (outb->flags & BB_EXCEPTION_HANDLER) {
1875 if (outb->in_stack != locals) {
1877 * Instead of storing sp [i] to locals [i], we need to store
1878 * locals [i] to <new locals>[i], since the sp [i] tree can't
1879 * be shared between trees.
1881 for (i = 0; i < count; ++i)
1882 mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
1883 locals = outb->in_stack;
1895 ret_type_to_call_opcode (MonoType *type, int calli, int virt)
1898 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1901 switch (type->type) {
1902 case MONO_TYPE_VOID:
1903 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
1906 case MONO_TYPE_BOOLEAN:
1909 case MONO_TYPE_CHAR:
1912 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1916 case MONO_TYPE_FNPTR:
1917 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1918 case MONO_TYPE_CLASS:
1919 case MONO_TYPE_STRING:
1920 case MONO_TYPE_OBJECT:
1921 case MONO_TYPE_SZARRAY:
1922 case MONO_TYPE_ARRAY:
1923 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1926 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
1929 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
1930 case MONO_TYPE_VALUETYPE:
1931 if (type->data.klass->enumtype) {
1932 type = type->data.klass->enum_basetype;
1935 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
1936 case MONO_TYPE_TYPEDBYREF:
1937 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
1938 case MONO_TYPE_GENERICINST:
1939 type = &type->data.generic_class->container_class->byval_arg;
1942 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1948 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1950 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1951 MonoJumpInfoBBTable *table;
1953 table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
1955 table->table_size = num_blocks;
1957 ji->ip.label = label;
1958 ji->type = MONO_PATCH_INFO_SWITCH;
1959 ji->data.table = table;
1960 ji->next = cfg->patch_info;
1961 cfg->patch_info = ji;
1965 * When we add a tree of instructions, we need to ensure the instructions currently
1966 * on the stack are executed before (like, if we load a value from a local).
1967 * We ensure this by saving the currently loaded values to temps and rewriting the
1968 * instructions to load the values.
1969 * This is not done for opcodes that terminate a basic block (because it's handled already
1970 * by handle_stack_args ()) and for opcodes that can't change values, like POP.
1973 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
1975 MonoInst *load, *store, *temp, *ins;
1977 while (stack < sp) {
1979 /* handle also other constants */
1980 if ((ins->opcode != OP_ICONST) &&
1981 /* temps never get written to again, so we can safely avoid duplicating them */
1982 !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
1983 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1984 temp->flags |= MONO_INST_IS_TEMP;
1985 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1986 store->cil_code = ins->cil_code;
1987 if (store->opcode == CEE_STOBJ) {
1988 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
1989 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
1991 MONO_ADD_INS (bblock, store);
1992 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1993 load->cil_code = ins->cil_code;
2001 * target_type_is_incompatible:
2002 * @cfg: MonoCompile context
2004 * Check that the item @arg on the evaluation stack can be stored
2005 * in the target type (can be a local, or field, etc).
2006 * The cfg arg can be used to check if we need verification or just
2009 * Returns: non-0 value if arg can't be stored on a target.
2012 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2014 MonoType *simple_type;
2017 if (target->byref) {
2018 /* FIXME: check that the pointed to types match */
2019 if (arg->type == STACK_MP)
2020 return arg->klass != mono_class_from_mono_type (target);
2021 if (arg->type == STACK_PTR)
2025 simple_type = mono_type_get_underlying_type (target);
2026 switch (simple_type->type) {
2027 case MONO_TYPE_VOID:
2031 case MONO_TYPE_BOOLEAN:
2034 case MONO_TYPE_CHAR:
2037 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2041 /* STACK_MP is needed when setting pinned locals */
2042 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2047 case MONO_TYPE_FNPTR:
2048 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2051 case MONO_TYPE_CLASS:
2052 case MONO_TYPE_STRING:
2053 case MONO_TYPE_OBJECT:
2054 case MONO_TYPE_SZARRAY:
2055 case MONO_TYPE_ARRAY:
2056 if (arg->type != STACK_OBJ)
2058 /* FIXME: check type compatibility */
2062 if (arg->type != STACK_I8)
2067 if (arg->type != STACK_R8)
2070 case MONO_TYPE_VALUETYPE:
2071 if (arg->type != STACK_VTYPE)
2073 klass = mono_class_from_mono_type (simple_type);
2074 if (klass != arg->klass)
2077 case MONO_TYPE_TYPEDBYREF:
2078 if (arg->type != STACK_VTYPE)
2080 klass = mono_class_from_mono_type (simple_type);
2081 if (klass != arg->klass)
2084 case MONO_TYPE_GENERICINST:
2085 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2086 if (arg->type != STACK_VTYPE)
2088 klass = mono_class_from_mono_type (simple_type);
2089 if (klass != arg->klass)
2093 if (arg->type != STACK_OBJ)
2095 /* FIXME: check type compatibility */
2099 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2105 * Prepare arguments for passing to a function call.
2106 * Return a non-zero value if the arguments can't be passed to the given
2108 * The type checks are not yet complete and some conversions may need
2109 * casts on 32 or 64 bit architectures.
2111 * FIXME: implement this using target_type_is_incompatible ()
2114 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2116 MonoType *simple_type;
2120 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2124 for (i = 0; i < sig->param_count; ++i) {
2125 if (sig->params [i]->byref) {
2126 if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2130 simple_type = sig->params [i];
2132 switch (simple_type->type) {
2133 case MONO_TYPE_VOID:
2138 case MONO_TYPE_BOOLEAN:
2141 case MONO_TYPE_CHAR:
2144 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2150 case MONO_TYPE_FNPTR:
2151 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2154 case MONO_TYPE_CLASS:
2155 case MONO_TYPE_STRING:
2156 case MONO_TYPE_OBJECT:
2157 case MONO_TYPE_SZARRAY:
2158 case MONO_TYPE_ARRAY:
2159 if (args [i]->type != STACK_OBJ)
2164 if (args [i]->type != STACK_I8)
2169 if (args [i]->type != STACK_R8)
2172 case MONO_TYPE_VALUETYPE:
2173 if (simple_type->data.klass->enumtype) {
2174 simple_type = simple_type->data.klass->enum_basetype;
2177 if (args [i]->type != STACK_VTYPE)
2180 case MONO_TYPE_TYPEDBYREF:
2181 if (args [i]->type != STACK_VTYPE)
2184 case MONO_TYPE_GENERICINST:
2185 simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2189 g_error ("unknown type 0x%02x in check_call_signature",
2197 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object,
2198 const guint8 *ip, gboolean to_end)
2200 MonoInst *temp, *store, *ins = (MonoInst*)call;
2201 MonoType *ret = sig->ret;
2203 if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2205 call->inst.type = STACK_OBJ;
2206 call->inst.opcode = CEE_CALL;
2207 temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2209 type_to_eval_stack_type (ret, ins);
2210 temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2213 temp->flags |= MONO_INST_IS_TEMP;
2215 if (MONO_TYPE_ISSTRUCT (ret)) {
2216 MonoInst *loada, *dummy_store;
2219 * Emit a dummy store to the local holding the result so the
2220 * liveness info remains correct.
2222 NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2224 mono_add_ins_to_end (bblock, dummy_store);
2226 MONO_ADD_INS (bblock, dummy_store);
2228 /* we use this to allocate native sized structs */
2229 temp->unused = sig->pinvoke;
2231 NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2232 if (call->inst.opcode == OP_VCALL)
2233 ins->inst_left = loada;
2235 ins->inst_right = loada; /* a virtual or indirect call */
2238 mono_add_ins_to_end (bblock, ins);
2240 MONO_ADD_INS (bblock, ins);
2242 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2243 store->cil_code = ip;
2245 mono_add_ins_to_end (bblock, store);
2247 MONO_ADD_INS (bblock, store);
2249 return temp->inst_c0;
2252 mono_add_ins_to_end (bblock, ins);
2254 MONO_ADD_INS (bblock, ins);
2259 inline static MonoCallInst *
2260 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2261 MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2266 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual));
2268 call->inst.cil_code = ip;
2270 call->signature = sig;
2271 call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2272 type_to_eval_stack_type (sig->ret, &call->inst);
2274 for (arg = call->out_args; arg;) {
2275 MonoInst *narg = arg->next;
2280 mono_add_ins_to_end (bblock, arg);
2282 MONO_ADD_INS (bblock, arg);
2289 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2290 MonoInst **args, MonoInst *addr, const guint8 *ip)
2292 MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2294 call->inst.inst_i0 = addr;
2296 return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2299 static MonoCallInst*
2300 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2301 MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2303 gboolean virtual = this != NULL;
2306 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2308 if (this && sig->hasthis &&
2309 (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2310 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2311 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2313 call->method = method;
2315 call->inst.flags |= MONO_INST_HAS_METHOD;
2316 call->inst.inst_left = this;
2318 if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2319 /* Needed by the code generated in inssel.brg */
2320 mono_get_got_var (cfg);
2325 static MonoCallInst*
2326 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2327 MonoInst **args, const guint8 *ip, MonoInst *this)
2329 return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2333 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2334 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2336 MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2338 return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2342 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2343 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2344 gboolean ret_object, gboolean to_end)
2346 MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2348 return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2352 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2353 MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2359 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2362 return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2366 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2368 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2371 g_warning ("unregistered JIT ICall");
2372 g_assert_not_reached ();
2375 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2379 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2381 MonoInst *ins, *temp = NULL, *store, *load, *begin;
2382 MonoInst *last_arg = NULL;
2386 //g_print ("emulating: ");
2387 //mono_print_tree_nl (tree);
2388 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE));
2389 ins = (MonoInst*)call;
2391 call->inst.cil_code = tree->cil_code;
2393 call->signature = info->sig;
2395 call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2397 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2398 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2399 temp->flags |= MONO_INST_IS_TEMP;
2400 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2401 store->cil_code = tree->cil_code;
2406 nargs = info->sig->param_count + info->sig->hasthis;
2408 for (last_arg = call->out_args; last_arg && last_arg->next; last_arg = last_arg->next) ;
2411 last_arg->next = store;
2414 begin = call->out_args;
2418 if (cfg->prev_ins) {
2420 * This assumes that that in a tree, emulate_opcode is called for a
2421 * node before it is called for its children. dec_foreach needs to
2422 * take this into account.
2424 store->next = cfg->prev_ins->next;
2425 cfg->prev_ins->next = begin;
2427 store->next = cfg->cbb->code;
2428 cfg->cbb->code = begin;
2431 call->fptr = mono_icall_get_wrapper (info);
2433 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2434 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2439 static MonoMethodSignature *
2440 mono_get_element_address_signature (int arity)
2442 static GHashTable *sighash = NULL;
2443 MonoMethodSignature *res;
2448 sighash = g_hash_table_new (NULL, NULL);
2450 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2451 LeaveCriticalSection (&jit_mutex);
2455 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2458 #ifdef MONO_ARCH_VARARG_ICALLS
2459 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2460 res->call_convention = MONO_CALL_VARARG;
2462 res->params [0] = &mono_defaults.array_class->byval_arg;
2464 for (i = 1; i <= arity; i++)
2465 res->params [i] = &mono_defaults.int_class->byval_arg;
2467 res->ret = &mono_defaults.int_class->byval_arg;
2469 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2475 static MonoMethodSignature *
2476 mono_get_array_new_va_signature (int arity)
2478 static GHashTable *sighash = NULL;
2479 MonoMethodSignature *res;
2484 sighash = g_hash_table_new (NULL, NULL);
2486 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2491 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2494 #ifdef MONO_ARCH_VARARG_ICALLS
2495 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2496 res->call_convention = MONO_CALL_VARARG;
2499 res->params [0] = &mono_defaults.int_class->byval_arg;
2500 for (i = 0; i < arity; i++)
2501 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2503 res->ret = &mono_defaults.int_class->byval_arg;
2505 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2512 get_memcpy_method (void)
2514 static MonoMethod *memcpy_method = NULL;
2515 if (!memcpy_method) {
2516 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2518 g_error ("Old corlib found. Install a new one");
2520 return memcpy_method;
2524 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
2525 MonoInst *iargs [3];
2528 MonoMethod *memcpy_method;
2532 * This check breaks with spilled vars... need to handle it during verification anyway.
2533 * g_assert (klass && klass == src->klass && klass == dest->klass);
2537 n = mono_class_native_size (klass, &align);
2539 n = mono_class_value_size (klass, &align);
2541 #if HAVE_WRITE_BARRIERS
2542 /* if native is true there should be no references in the struct */
2543 if (write_barrier && klass->has_references && !native) {
2546 NEW_PCONST (cfg, iargs [2], klass);
2548 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
2553 /* FIXME: add write barrier handling */
2554 if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
2556 if (dest->opcode == OP_LDADDR) {
2557 /* Keep liveness info correct */
2558 NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
2559 MONO_ADD_INS (bblock, inst);
2561 MONO_INST_NEW (cfg, inst, OP_MEMCPY);
2562 inst->inst_left = dest;
2563 inst->inst_right = src;
2564 inst->cil_code = ip;
2566 MONO_ADD_INS (bblock, inst);
2571 NEW_ICONST (cfg, iargs [2], n);
2573 memcpy_method = get_memcpy_method ();
2574 mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
2578 get_memset_method (void)
2580 static MonoMethod *memset_method = NULL;
2581 if (!memset_method) {
2582 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
2584 g_error ("Old corlib found. Install a new one");
2586 return memset_method;
2590 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
2592 MonoInst *iargs [3];
2593 MonoInst *ins, *zero_int32;
2595 MonoMethod *memset_method;
2597 NEW_ICONST (cfg, zero_int32, 0);
2599 mono_class_init (klass);
2600 n = mono_class_value_size (klass, NULL);
2601 MONO_INST_NEW (cfg, ins, 0);
2603 ins->inst_left = dest;
2604 ins->inst_right = zero_int32;
2607 ins->opcode = CEE_STIND_I1;
2608 MONO_ADD_INS (bblock, ins);
2611 ins->opcode = CEE_STIND_I2;
2612 MONO_ADD_INS (bblock, ins);
2615 ins->opcode = CEE_STIND_I4;
2616 MONO_ADD_INS (bblock, ins);
2619 if (n <= sizeof (gpointer) * 5) {
2620 ins->opcode = OP_MEMSET;
2623 MONO_ADD_INS (bblock, ins);
2626 memset_method = get_memset_method ();
2627 handle_loaded_temps (cfg, bblock, stack_start, sp);
2629 NEW_ICONST (cfg, iargs [1], 0);
2630 NEW_ICONST (cfg, iargs [2], n);
2631 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
2637 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
2639 MonoInst *iargs [2];
2642 if (cfg->opt & MONO_OPT_SHARED) {
2643 NEW_DOMAINCONST (cfg, iargs [0]);
2644 NEW_CLASSCONST (cfg, iargs [1], klass);
2646 alloc_ftn = mono_object_new;
2647 } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
2648 /* This happens often in argument checking code, eg. throw new FooException... */
2649 /* Avoid relocations by calling a helper function specialized to mscorlib */
2650 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
2651 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
2653 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
2656 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
2658 guint32 lw = vtable->klass->instance_size;
2659 lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
2660 NEW_ICONST (cfg, iargs [0], lw);
2661 NEW_VTABLECONST (cfg, iargs [1], vtable);
2664 NEW_VTABLECONST (cfg, iargs [0], vtable);
2667 return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
2671 * Handles unbox of a Nullable<T>, returning a temp variable
2672 * where the result is stored
2675 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
2677 MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
2678 return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
2685 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
2687 MonoInst *dest, *vtoffset, *add, *vstore;
2690 if (mono_class_is_nullable (klass)) {
2691 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
2692 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
2693 NEW_TEMPLOAD (cfg, dest, temp);
2698 temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
2699 NEW_TEMPLOAD (cfg, dest, temp);
2700 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
2701 MONO_INST_NEW (cfg, add, OP_PADD);
2702 add->inst_left = dest;
2703 add->inst_right = vtoffset;
2706 MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
2707 vstore->opcode = mono_type_to_stind (&klass->byval_arg);
2708 vstore->cil_code = ip;
2709 vstore->inst_left = add;
2710 vstore->inst_right = val;
2712 if (vstore->opcode == CEE_STOBJ) {
2713 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
2715 MONO_ADD_INS (bblock, vstore);
2717 NEW_TEMPLOAD (cfg, dest, temp);
2722 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
2724 MonoMethodSignature *esig;
2725 char icall_name [256];
2727 MonoJitICallInfo *info;
2729 /* Need to register the icall so it gets an icall wrapper */
2730 sprintf (icall_name, "ves_array_new_va_%d", rank);
2732 info = mono_find_jit_icall_by_name (icall_name);
2734 esig = mono_get_array_new_va_signature (rank);
2735 name = g_strdup (icall_name);
2736 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
2739 g_hash_table_insert (jit_icall_name_hash, name, name);
2743 cfg->flags |= MONO_CFG_HAS_VARARGS;
2745 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
2749 mono_emit_load_got_addr (MonoCompile *cfg)
2751 MonoInst *load, *store, *dummy_use;
2754 if (!cfg->got_var || cfg->got_var_allocated)
2757 MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
2758 NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
2760 /* Add it to the start of the first bblock */
2761 if (cfg->bb_entry->code) {
2762 store->next = cfg->bb_entry->code;
2763 cfg->bb_entry->code = store;
2766 MONO_ADD_INS (cfg->bb_entry, store);
2768 cfg->got_var_allocated = TRUE;
2771 * Add a dummy use to keep the got_var alive, since real uses might
2772 * only be generated in the decompose or instruction selection phases.
2773 * Add it to end_bblock, so the variable's lifetime covers the whole
2776 NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
2777 NEW_DUMMY_USE (cfg, dummy_use, load);
2778 MONO_ADD_INS (cfg->bb_exit, dummy_use);
2781 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
2784 mini_class_is_system_array (MonoClass *klass)
2786 if (klass->parent == mono_defaults.array_class)
2788 else if (mono_defaults.generic_array_class && klass->parent && klass->parent->generic_class)
2789 return klass->parent->generic_class->container_class == mono_defaults.generic_array_class;
2795 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
2797 MonoMethodHeader *header = mono_method_get_header (method);
2798 MonoMethodSignature *signature = mono_method_signature (method);
2802 #ifdef MONO_ARCH_HAVE_LMF_OPS
2803 if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2804 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
2805 !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
2809 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2810 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2811 (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
2812 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
2813 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2814 (method->klass->marshalbyref) ||
2815 !header || header->num_clauses ||
2816 /* fixme: why cant we inline valuetype returns? */
2817 MONO_TYPE_ISSTRUCT (signature->ret))
2820 /* its not worth to inline methods with valuetype arguments?? */
2821 for (i = 0; i < signature->param_count; i++) {
2822 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
2828 * if we can initialize the class of the method right away, we do,
2829 * otherwise we don't allow inlining if the class needs initialization,
2830 * since it would mean inserting a call to mono_runtime_class_init()
2831 * inside the inlined code
2833 if (!(cfg->opt & MONO_OPT_SHARED)) {
2834 vtable = mono_class_vtable (cfg->domain, method->klass);
2835 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
2836 if (cfg->run_cctors)
2837 mono_runtime_class_init (vtable);
2839 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
2843 * If we're compiling for shared code
2844 * the cctor will need to be run at aot method load time, for example,
2845 * or at the end of the compilation of the inlining method.
2847 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2850 //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
2853 * CAS - do not inline methods with declarative security
2854 * Note: this has to be before any possible return TRUE;
2856 if (mono_method_has_declsec (method))
2859 /* also consider num_locals? */
2860 if (getenv ("MONO_INLINELIMIT")) {
2861 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
2864 } else if (header->code_size < INLINE_LENGTH_LIMIT)
2871 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
2873 if (vtable->initialized && !cfg->compile_aot)
2876 if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
2879 if (!mono_class_needs_cctor_run (vtable->klass, method))
2882 if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
2883 /* The initialization is already done before the method is called */
2890 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
2894 MonoMethodSignature *esig;
2895 char icall_name [256];
2897 MonoJitICallInfo *info;
2899 rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
2902 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
2903 addr->inst_left = sp [0];
2904 addr->inst_right = sp [1];
2905 addr->cil_code = ip;
2906 addr->type = STACK_MP;
2907 addr->klass = cmethod->klass->element_class;
2911 if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
2912 #ifdef MONO_ARCH_EMULATE_MUL_DIV
2913 /* OP_LDELEMA2D depends on OP_LMUL */
2916 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
2917 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
2918 addr->inst_left = sp [0];
2919 addr->inst_right = indexes;
2920 addr->cil_code = ip;
2921 addr->type = STACK_MP;
2922 addr->klass = cmethod->klass;
2927 /* Need to register the icall so it gets an icall wrapper */
2928 sprintf (icall_name, "ves_array_element_address_%d", rank);
2930 info = mono_find_jit_icall_by_name (icall_name);
2932 esig = mono_get_element_address_signature (rank);
2933 name = g_strdup (icall_name);
2934 info = mono_register_jit_icall (ves_array_element_address, name, esig, FALSE);
2937 g_hash_table_insert (jit_icall_name_hash, name, name);
2941 temp = mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, FALSE, FALSE);
2942 cfg->flags |= MONO_CFG_HAS_VARARGS;
2944 NEW_TEMPLOAD (cfg, addr, temp);
2948 MonoJitICallInfo **emul_opcode_map = NULL;
2951 mono_find_jit_opcode_emulation (int opcode)
2953 if (emul_opcode_map)
2954 return emul_opcode_map [opcode];
2960 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
2962 MonoInst *ins = NULL;
2964 static MonoClass *runtime_helpers_class = NULL;
2965 if (! runtime_helpers_class)
2966 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
2967 "System.Runtime.CompilerServices", "RuntimeHelpers");
2969 if (cmethod->klass == mono_defaults.string_class) {
2970 if (strcmp (cmethod->name, "get_Chars") == 0) {
2971 MONO_INST_NEW (cfg, ins, OP_GETCHR);
2972 ins->inst_i0 = args [0];
2973 ins->inst_i1 = args [1];
2975 } else if (strcmp (cmethod->name, "get_Length") == 0) {
2976 MONO_INST_NEW (cfg, ins, OP_STRLEN);
2977 ins->inst_i0 = args [0];
2979 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
2981 MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
2982 get_addr->inst_i0 = args [0];
2983 get_addr->inst_i1 = args [1];
2984 MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
2985 ins->inst_i0 = get_addr;
2986 ins->inst_i1 = args [2];
2990 } else if (cmethod->klass == mono_defaults.object_class) {
2991 if (strcmp (cmethod->name, "GetType") == 0) {
2992 MONO_INST_NEW (cfg, ins, OP_GETTYPE);
2993 ins->inst_i0 = args [0];
2995 /* The OP_GETHASHCODE rule depends on OP_MUL */
2996 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
2997 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
2998 MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
2999 ins->inst_i0 = args [0];
3002 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3003 MONO_INST_NEW (cfg, ins, CEE_NOP);
3007 } else if (cmethod->klass == mono_defaults.array_class) {
3008 if (cmethod->name [0] != 'g')
3011 if (strcmp (cmethod->name, "get_Rank") == 0) {
3012 MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3013 ins->inst_i0 = args [0];
3015 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3016 MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3017 ins->inst_i0 = args [0];
3021 } else if (cmethod->klass == runtime_helpers_class) {
3022 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3023 NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3027 } else if (cmethod->klass == mono_defaults.thread_class) {
3028 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3030 } else if (mini_class_is_system_array (cmethod->klass) &&
3031 strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3033 MonoInst *ldelem, *store, *load;
3034 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3036 n = mono_type_to_stind (&eklass->byval_arg);
3041 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3042 ldelem->flags |= MONO_INST_NORANGECHECK;
3043 MONO_INST_NEW (cfg, store, n);
3044 n = mono_type_to_ldind (&eklass->byval_arg);
3045 MONO_INST_NEW (cfg, load, mono_type_to_ldind (&eklass->byval_arg));
3046 type_to_eval_stack_type (&eklass->byval_arg, load);
3047 load->inst_left = ldelem;
3048 store->inst_left = args [2];
3049 store->inst_right = load;
3053 return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3057 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3059 MonoInst *store, *temp;
3062 g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3064 if (!sig->hasthis && sig->param_count == 0)
3068 if (sp [0]->opcode == OP_ICONST) {
3071 temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3073 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3074 store->cil_code = sp [0]->cil_code;
3075 MONO_ADD_INS (bblock, store);
3080 for (i = 0; i < sig->param_count; ++i) {
3081 if (sp [0]->opcode == OP_ICONST) {
3084 temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3086 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3087 store->cil_code = sp [0]->cil_code;
3088 if (store->opcode == CEE_STOBJ) {
3089 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3090 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3092 MONO_ADD_INS (bblock, store);
3098 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
3099 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
3101 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3103 mono_inline_called_method_name_limit = NULL;
3104 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3105 char *called_method_name = mono_method_full_name (called_method, TRUE);
3108 if (mono_inline_called_method_name_limit == NULL) {
3109 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3110 if (limit_string != NULL) {
3111 mono_inline_called_method_name_limit = limit_string;
3113 mono_inline_called_method_name_limit = (char *) "";
3117 strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3118 g_free (called_method_name);
3120 //return (strncmp_result <= 0);
3121 return (strncmp_result == 0);
3125 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3127 mono_inline_caller_method_name_limit = NULL;
3128 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3129 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3132 if (mono_inline_caller_method_name_limit == NULL) {
3133 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3134 if (limit_string != NULL) {
3135 mono_inline_caller_method_name_limit = limit_string;
3137 mono_inline_caller_method_name_limit = (char *) "";
3141 strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3142 g_free (caller_method_name);
3144 //return (strncmp_result <= 0);
3145 return (strncmp_result == 0);
3150 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3151 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3153 MonoInst *ins, *rvar = NULL;
3154 MonoMethodHeader *cheader;
3155 MonoBasicBlock *ebblock, *sbblock;
3156 int i, costs, new_locals_offset;
3157 MonoMethod *prev_inlined_method;
3158 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3159 if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3162 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3163 if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3167 if (cfg->verbose_level > 2)
3168 g_print ("INLINE START %p %s -> %s\n", cmethod, mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3170 if (!cmethod->inline_info) {
3171 mono_jit_stats.inlineable_methods++;
3172 cmethod->inline_info = 1;
3174 /* allocate space to store the return value */
3175 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3176 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3179 /* allocate local variables */
3180 cheader = mono_method_get_header (cmethod);
3181 new_locals_offset = cfg->num_varinfo;
3182 for (i = 0; i < cheader->num_locals; ++i)
3183 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3185 /* allocate starte and end blocks */
3186 sbblock = NEW_BBLOCK (cfg);
3187 sbblock->block_num = cfg->num_bblocks++;
3188 sbblock->real_offset = real_offset;
3190 ebblock = NEW_BBLOCK (cfg);
3191 ebblock->block_num = cfg->num_bblocks++;
3192 ebblock->real_offset = real_offset;
3194 prev_inlined_method = cfg->inlined_method;
3195 cfg->inlined_method = cmethod;
3197 costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3199 cfg->inlined_method = prev_inlined_method;
3201 if ((costs >= 0 && costs < 60) || inline_allways) {
3202 if (cfg->verbose_level > 2)
3203 g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3205 mono_jit_stats.inlined_methods++;
3207 /* always add some code to avoid block split failures */
3208 MONO_INST_NEW (cfg, ins, CEE_NOP);
3209 MONO_ADD_INS (bblock, ins);
3212 bblock->next_bb = sbblock;
3213 link_bblock (cfg, bblock, sbblock);
3216 NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3222 if (cfg->verbose_level > 2)
3223 g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
3229 * Some of these comments may well be out-of-date.
3230 * Design decisions: we do a single pass over the IL code (and we do bblock
3231 * splitting/merging in the few cases when it's required: a back jump to an IL
3232 * address that was not already seen as bblock starting point).
3233 * Code is validated as we go (full verification is still better left to metadata/verify.c).
3234 * Complex operations are decomposed in simpler ones right away. We need to let the
3235 * arch-specific code peek and poke inside this process somehow (except when the
3236 * optimizations can take advantage of the full semantic info of coarse opcodes).
3237 * All the opcodes of the form opcode.s are 'normalized' to opcode.
3238 * MonoInst->opcode initially is the IL opcode or some simplification of that
3239 * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific
3240 * opcode with value bigger than OP_LAST.
3241 * At this point the IR can be handed over to an interpreter, a dumb code generator
3242 * or to the optimizing code generator that will translate it to SSA form.
3244 * Profiling directed optimizations.
3245 * We may compile by default with few or no optimizations and instrument the code
3246 * or the user may indicate what methods to optimize the most either in a config file
3247 * or through repeated runs where the compiler applies offline the optimizations to
3248 * each method and then decides if it was worth it.
3251 * * consider using an array instead of an hash table (bb_hash)
3254 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
3255 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
3256 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
3257 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
3258 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
3259 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
3262 /* offset from br.s -> br like opcodes */
3263 #define BIG_BRANCH_OFFSET 13
3266 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
3268 MonoBasicBlock *b = g_hash_table_lookup (cfg->bb_hash, ip);
3270 return b == NULL || b == bb;
3274 get_basic_blocks (MonoCompile *cfg, GHashTable *bbhash, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
3276 unsigned char *ip = start;
3277 unsigned char *target;
3280 MonoBasicBlock *bblock;
3281 const MonoOpcode *opcode;
3284 cli_addr = ip - start;
3285 i = mono_opcode_value ((const guint8 **)&ip, end);
3288 opcode = &mono_opcodes [i];
3289 switch (opcode->argument) {
3290 case MonoInlineNone:
3293 case MonoInlineString:
3294 case MonoInlineType:
3295 case MonoInlineField:
3296 case MonoInlineMethod:
3299 case MonoShortInlineR:
3306 case MonoShortInlineVar:
3307 case MonoShortInlineI:
3310 case MonoShortInlineBrTarget:
3311 target = start + cli_addr + 2 + (signed char)ip [1];
3312 GET_BBLOCK (cfg, bbhash, bblock, target);
3315 GET_BBLOCK (cfg, bbhash, bblock, ip);
3317 case MonoInlineBrTarget:
3318 target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
3319 GET_BBLOCK (cfg, bbhash, bblock, target);
3322 GET_BBLOCK (cfg, bbhash, bblock, ip);
3324 case MonoInlineSwitch: {
3325 guint32 n = read32 (ip + 1);
3328 cli_addr += 5 + 4 * n;
3329 target = start + cli_addr;
3330 GET_BBLOCK (cfg, bbhash, bblock, target);
3332 for (j = 0; j < n; ++j) {
3333 target = start + cli_addr + (gint32)read32 (ip);
3334 GET_BBLOCK (cfg, bbhash, bblock, target);
3344 g_assert_not_reached ();
3347 if (i == CEE_THROW) {
3348 unsigned char *bb_start = ip - 1;
3350 /* Find the start of the bblock containing the throw */
3352 while ((bb_start >= start) && !bblock) {
3353 bblock = g_hash_table_lookup (bbhash, (bb_start));
3357 bblock->out_of_line = 1;
3367 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
3369 MonoInst *store, *temp, *load;
3371 if (ip_in_bb (cfg, bblock, ip_next) &&
3372 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
3375 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3376 temp->flags |= MONO_INST_IS_TEMP;
3377 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3378 store->cil_code = ins->cil_code;
3379 MONO_ADD_INS (bblock, store);
3380 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3381 load->cil_code = ins->cil_code;
3385 static inline MonoMethod *
3386 mini_get_method (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
3390 if (m->wrapper_type != MONO_WRAPPER_NONE)
3391 return mono_method_get_wrapper_data (m, token);
3393 method = mono_get_method_full (m->klass->image, token, klass, context);
3395 if (method && method->is_inflated)
3396 method = mono_get_inflated_method (method);
3401 static inline MonoClass*
3402 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
3406 if (method->wrapper_type != MONO_WRAPPER_NONE)
3407 klass = mono_method_get_wrapper_data (method, token);
3409 klass = mono_class_get_full (method->klass->image, token, context);
3411 mono_class_init (klass);
3416 void check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
3418 guint32 result = mono_declsec_linkdemand (cfg->domain, caller, callee);
3419 if (result == MONO_JIT_SECURITY_OK)
3422 if (result == MONO_JIT_LINKDEMAND_ECMA) {
3423 /* Generate code to throw a SecurityException before the actual call/link */
3424 MonoAssembly *assembly = mono_image_get_assembly (caller->klass->image);
3425 MonoReflectionAssembly *refass = (MonoReflectionAssembly*) mono_assembly_get_object (cfg->domain, assembly);
3426 MonoReflectionMethod *refmet = mono_method_get_object (cfg->domain, caller, NULL);
3427 MonoSecurityManager *secman = mono_security_manager_get_methods ();
3430 NEW_ICONST (cfg, args [0], 4);
3431 NEW_PCONST (cfg, args [1], refass);
3432 NEW_PCONST (cfg, args [2], refmet);
3433 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
3434 } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
3435 /* don't hide previous results */
3436 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
3437 cfg->exception_data = result;
3442 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
3445 if (accessing == accessed)
3447 if (!accessed || !accessing)
3449 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
3450 MonoAssemblyName *friend = tmp->data;
3451 /* Be conservative with checks */
3454 if (strcmp (accessing->aname.name, friend->name))
3456 if (friend->public_key_token [0]) {
3457 if (!accessing->aname.public_key_token [0])
3459 if (strcmp ((char*)friend->public_key_token, (char*)accessing->aname.public_key_token))
3467 /* FIXME: check visibility of type, too */
3469 can_access_member (MonoClass *access_klass, MonoClass *member_klass, int access_level)
3471 /* Partition I 8.5.3.2 */
3472 /* the access level values are the same for fields and methods */
3473 switch (access_level) {
3474 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
3475 /* same compilation unit */
3476 return access_klass->image == member_klass->image;
3477 case FIELD_ATTRIBUTE_PRIVATE:
3478 return access_klass == member_klass;
3479 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
3480 if (mono_class_has_parent (access_klass, member_klass) &&
3481 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
3484 case FIELD_ATTRIBUTE_ASSEMBLY:
3485 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
3486 case FIELD_ATTRIBUTE_FAMILY:
3487 if (mono_class_has_parent (access_klass, member_klass))
3490 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
3491 if (mono_class_has_parent (access_klass, member_klass))
3493 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
3494 case FIELD_ATTRIBUTE_PUBLIC:
3501 can_access_field (MonoMethod *method, MonoClassField *field)
3503 /* FIXME: check all overlapping fields */
3504 int can = can_access_member (method->klass, field->parent, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
3506 MonoClass *nested = method->klass->nested_in;
3508 can = can_access_member (nested, field->parent, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
3511 nested = nested->nested_in;
3518 can_access_method (MonoMethod *method, MonoMethod *called)
3520 int can = can_access_member (method->klass, called->klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
3522 MonoClass *nested = method->klass->nested_in;
3524 can = can_access_member (nested, called->klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
3527 nested = nested->nested_in;
3532 * with generics calls to explicit interface implementations can be expressed
3533 * directly: the method is private, but we must allow it. This may be opening
3534 * a hole or the generics code should handle this differently.
3535 * Maybe just ensure the interface type is public.
3537 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
3543 * mono_method_to_ir: translates IL into basic blocks containing trees
3546 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
3547 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
3548 guint inline_offset, gboolean is_virtual_call)
3550 MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
3551 MonoInst *ins, **sp, **stack_start;
3552 MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
3554 MonoMethod *cmethod;
3555 MonoInst **arg_array;
3556 MonoMethodHeader *header;
3558 guint32 token, ins_flag;
3560 MonoClass *constrained_call = NULL;
3561 unsigned char *ip, *end, *target, *err_pos;
3562 static double r8_0 = 0.0;
3563 MonoMethodSignature *sig;
3564 MonoGenericContext *generic_context = NULL;
3565 MonoGenericContainer *generic_container = NULL;
3566 MonoType **param_types;
3567 GList *bb_recheck = NULL, *tmp;
3568 int i, n, start_new_bblock, ialign;
3569 int num_calls = 0, inline_costs = 0;
3570 int breakpoint_id = 0;
3572 guint real_offset, num_args;
3573 MonoBoolean security, pinvoke;
3574 MonoSecurityManager* secman = NULL;
3575 MonoDeclSecurityActions actions;
3576 GSList *class_inits = NULL;
3577 gboolean dont_verify, dont_verify_stloc;
3579 /* serialization and xdomain stuff may need access to private fields and methods */
3580 dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
3581 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
3582 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
3583 dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
3585 /* still some type unsefety issues in marshal wrappers... (unknown is PtrToStructure) */
3586 dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
3587 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
3588 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
3590 image = method->klass->image;
3591 header = mono_method_get_header (method);
3592 generic_container = method->generic_container;
3593 sig = mono_method_signature (method);
3594 num_args = sig->hasthis + sig->param_count;
3595 ip = (unsigned char*)header->code;
3596 end = ip + header->code_size;
3597 mono_jit_stats.cil_code_size += header->code_size;
3599 if (sig->is_inflated)
3600 generic_context = ((MonoMethodInflated *) method)->context;
3601 else if (generic_container)
3602 generic_context = &generic_container->context;
3604 g_assert (!sig->has_type_parameters);
3606 if (cfg->method == method) {
3608 bbhash = cfg->bb_hash;
3610 real_offset = inline_offset;
3611 bbhash = g_hash_table_new (g_direct_hash, NULL);
3614 if (cfg->verbose_level > 2)
3615 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
3617 dont_inline = g_list_prepend (dont_inline, method);
3618 if (cfg->method == method) {
3620 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
3621 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
3624 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
3625 start_bblock->cil_code = NULL;
3626 start_bblock->cil_length = 0;
3627 start_bblock->block_num = cfg->num_bblocks++;
3630 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
3631 end_bblock->cil_code = NULL;
3632 end_bblock->cil_length = 0;
3633 end_bblock->block_num = cfg->num_bblocks++;
3634 g_assert (cfg->num_bblocks == 2);
3636 arg_array = alloca (sizeof (MonoInst *) * num_args);
3637 for (i = num_args - 1; i >= 0; i--)
3638 arg_array [i] = cfg->varinfo [i];
3640 if (header->num_clauses) {
3641 cfg->spvars = g_hash_table_new (NULL, NULL);
3642 cfg->exvars = g_hash_table_new (NULL, NULL);
3644 /* handle exception clauses */
3645 for (i = 0; i < header->num_clauses; ++i) {
3646 MonoBasicBlock *try_bb;
3647 MonoExceptionClause *clause = &header->clauses [i];
3648 GET_BBLOCK (cfg, bbhash, try_bb, ip + clause->try_offset);
3649 try_bb->real_offset = clause->try_offset;
3650 GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
3651 tblock->real_offset = clause->handler_offset;
3652 tblock->flags |= BB_EXCEPTION_HANDLER;
3654 link_bblock (cfg, try_bb, tblock);
3656 if (*(ip + clause->handler_offset) == CEE_POP)
3657 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
3659 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
3660 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3661 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
3662 MONO_ADD_INS (tblock, ins);
3664 /* todo: is a fault block unsafe to optimize? */
3665 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
3666 tblock->flags |= BB_EXCEPTION_UNSAFE;
3670 /*g_print ("clause try IL_%04x to IL_%04x handler %d at IL_%04x to IL_%04x\n", clause->try_offset, clause->try_offset + clause->try_len, clause->flags, clause->handler_offset, clause->handler_offset + clause->handler_len);
3672 g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
3674 /* catch and filter blocks get the exception object on the stack */
3675 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
3676 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3677 MonoInst *load, *dummy_use;
3679 /* mostly like handle_stack_args (), but just sets the input args */
3680 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
3681 tblock->in_scount = 1;
3682 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
3683 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
3686 * Add a dummy use for the exvar so its liveness info will be
3689 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
3690 NEW_DUMMY_USE (cfg, dummy_use, load);
3691 MONO_ADD_INS (tblock, dummy_use);
3693 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3694 GET_BBLOCK (cfg, bbhash, tblock, ip + clause->data.filter_offset);
3695 tblock->real_offset = clause->data.filter_offset;
3696 tblock->in_scount = 1;
3697 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
3698 /* The filter block shares the exvar with the handler block */
3699 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
3700 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
3701 MONO_ADD_INS (tblock, ins);
3706 arg_array = alloca (sizeof (MonoInst *) * num_args);
3707 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
3710 /* FIRST CODE BLOCK */
3711 bblock = NEW_BBLOCK (cfg);
3712 bblock->cil_code = ip;
3714 ADD_BBLOCK (cfg, bbhash, bblock);
3716 if (cfg->method == method) {
3717 breakpoint_id = mono_debugger_method_has_breakpoint (method);
3718 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
3719 MONO_INST_NEW (cfg, ins, CEE_BREAK);
3720 MONO_ADD_INS (bblock, ins);
3724 if (mono_use_security_manager)
3725 secman = mono_security_manager_get_methods ();
3727 security = (secman && mono_method_has_declsec (method));
3728 /* at this point having security doesn't mean we have any code to generate */
3729 if (security && (cfg->method == method)) {
3730 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
3731 * And we do not want to enter the next section (with allocation) if we
3732 * have nothing to generate */
3733 security = mono_declsec_get_demands (method, &actions);
3736 /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
3737 pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
3739 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
3740 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3741 MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
3743 /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
3744 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
3749 custom = mono_custom_attrs_from_class (wrapped->klass);
3750 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
3755 /* not a P/Invoke after all */
3760 if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || mono_compile_aot || security || pinvoke) {
3761 /* we use a separate basic block for the initialization code */
3762 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
3763 init_localsbb->real_offset = real_offset;
3764 start_bblock->next_bb = init_localsbb;
3765 init_localsbb->next_bb = bblock;
3766 link_bblock (cfg, start_bblock, init_localsbb);
3767 link_bblock (cfg, init_localsbb, bblock);
3768 init_localsbb->block_num = cfg->num_bblocks++;
3770 start_bblock->next_bb = bblock;
3771 link_bblock (cfg, start_bblock, bblock);
3774 /* at this point we know, if security is TRUE, that some code needs to be generated */
3775 if (security && (cfg->method == method)) {
3778 mono_jit_stats.cas_demand_generation++;
3780 if (actions.demand.blob) {
3781 /* Add code for SecurityAction.Demand */
3782 NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
3783 NEW_ICONST (cfg, args [1], actions.demand.size);
3784 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
3785 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
3787 if (actions.noncasdemand.blob) {
3788 /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
3789 /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
3790 NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
3791 NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
3792 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
3793 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
3795 if (actions.demandchoice.blob) {
3796 /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
3797 NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
3798 NEW_ICONST (cfg, args [1], actions.demandchoice.size);
3799 /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
3800 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
3804 /* we must Demand SecurityPermission.Unmanaged before p/invoking */
3806 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
3809 if (get_basic_blocks (cfg, bbhash, header, real_offset, ip, end, &err_pos)) {
3814 if (cfg->method == method)
3815 mono_debug_init_method (cfg, bblock, breakpoint_id);
3817 param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
3819 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
3820 for (n = 0; n < sig->param_count; ++n)
3821 param_types [n + sig->hasthis] = sig->params [n];
3822 for (n = 0; n < header->num_locals; ++n) {
3823 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
3828 /* do this somewhere outside - not here */
3829 NEW_ICONST (cfg, zero_int32, 0);
3830 NEW_ICONST (cfg, zero_int64, 0);
3831 zero_int64->type = STACK_I8;
3832 NEW_PCONST (cfg, zero_ptr, 0);
3833 NEW_PCONST (cfg, zero_obj, 0);
3834 zero_obj->type = STACK_OBJ;
3836 MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
3837 zero_r8->type = STACK_R8;
3838 zero_r8->inst_p0 = &r8_0;
3840 /* add a check for this != NULL to inlined methods */
3841 if (is_virtual_call) {
3842 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
3843 NEW_ARGLOAD (cfg, ins->inst_left, 0);
3845 MONO_ADD_INS (bblock, ins);
3848 /* we use a spare stack slot in SWITCH and NEWOBJ and others */
3849 stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
3852 start_new_bblock = 0;
3855 if (cfg->method == method)
3856 real_offset = ip - header->code;
3858 real_offset = inline_offset;
3860 if (start_new_bblock) {
3861 bblock->cil_length = ip - bblock->cil_code;
3862 if (start_new_bblock == 2) {
3863 g_assert (ip == tblock->cil_code);
3865 GET_BBLOCK (cfg, bbhash, tblock, ip);
3867 bblock->next_bb = tblock;
3869 start_new_bblock = 0;
3870 for (i = 0; i < bblock->in_scount; ++i) {
3871 if (cfg->verbose_level > 3)
3872 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
3873 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
3876 g_slist_free (class_inits);
3879 if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
3880 link_bblock (cfg, bblock, tblock);
3881 if (sp != stack_start) {
3882 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3885 bblock->next_bb = tblock;
3887 for (i = 0; i < bblock->in_scount; ++i) {
3888 if (cfg->verbose_level > 3)
3889 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
3890 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
3893 g_slist_free (class_inits);
3898 bblock->real_offset = real_offset;
3900 if ((cfg->method == method) && cfg->coverage_info) {
3901 MonoInst *store, *one;
3902 guint32 cil_offset = ip - header->code;
3903 cfg->coverage_info->data [cil_offset].cil_code = ip;
3905 /* TODO: Use an increment here */
3906 NEW_ICONST (cfg, one, 1);
3909 NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
3912 MONO_INST_NEW (cfg, store, CEE_STIND_I);
3913 store->cil_code = ip;
3914 store->inst_left = ins;
3915 store->inst_right = one;
3917 MONO_ADD_INS (bblock, store);
3920 if (cfg->verbose_level > 3)
3921 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
3926 MONO_INST_NEW (cfg, ins, *ip);
3927 ins->cil_code = ip++;
3928 MONO_ADD_INS (bblock, ins);
3934 CHECK_STACK_OVF (1);
3935 n = (*ip)-CEE_LDARG_0;
3937 NEW_ARGLOAD (cfg, ins, n);
3938 ins->cil_code = ip++;
3945 CHECK_STACK_OVF (1);
3946 n = (*ip)-CEE_LDLOC_0;
3948 NEW_LOCLOAD (cfg, ins, n);
3949 ins->cil_code = ip++;
3957 n = (*ip)-CEE_STLOC_0;
3960 handle_loaded_temps (cfg, bblock, stack_start, sp);
3961 NEW_LOCSTORE (cfg, ins, n, *sp);
3963 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
3965 if (ins->opcode == CEE_STOBJ) {
3966 NEW_LOCLOADA (cfg, ins, n);
3967 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
3969 MONO_ADD_INS (bblock, ins);
3975 CHECK_STACK_OVF (1);
3977 NEW_ARGLOAD (cfg, ins, ip [1]);
3984 CHECK_STACK_OVF (1);
3986 NEW_ARGLOADA (cfg, ins, ip [1]);
3996 NEW_ARGSTORE (cfg, ins, ip [1], *sp);
3997 handle_loaded_temps (cfg, bblock, stack_start, sp);
3999 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
4001 if (ins->opcode == CEE_STOBJ) {
4002 NEW_ARGLOADA (cfg, ins, ip [1]);
4003 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4005 MONO_ADD_INS (bblock, ins);
4010 CHECK_STACK_OVF (1);
4011 CHECK_LOCAL (ip [1]);
4012 NEW_LOCLOAD (cfg, ins, ip [1]);
4019 CHECK_STACK_OVF (1);
4020 CHECK_LOCAL (ip [1]);
4021 NEW_LOCLOADA (cfg, ins, ip [1]);
4030 handle_loaded_temps (cfg, bblock, stack_start, sp);
4031 CHECK_LOCAL (ip [1]);
4032 NEW_LOCSTORE (cfg, ins, ip [1], *sp);
4034 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
4036 if (ins->opcode == CEE_STOBJ) {
4037 NEW_LOCLOADA (cfg, ins, ip [1]);
4038 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4040 MONO_ADD_INS (bblock, ins);
4045 CHECK_STACK_OVF (1);
4046 NEW_PCONST (cfg, ins, NULL);
4048 ins->type = STACK_OBJ;
4053 CHECK_STACK_OVF (1);
4054 NEW_ICONST (cfg, ins, -1);
4068 CHECK_STACK_OVF (1);
4069 NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
4076 CHECK_STACK_OVF (1);
4078 NEW_ICONST (cfg, ins, *((signed char*)ip));
4085 CHECK_STACK_OVF (1);
4086 NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
4093 CHECK_STACK_OVF (1);
4094 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4096 ins->type = STACK_I8;
4098 ins->inst_l = (gint64)read64 (ip);
4104 /* we should really allocate this only late in the compilation process */
4105 mono_domain_lock (cfg->domain);
4106 f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
4107 mono_domain_unlock (cfg->domain);
4109 CHECK_STACK_OVF (1);
4110 MONO_INST_NEW (cfg, ins, OP_R4CONST);
4111 ins->type = STACK_R8;
4122 mono_domain_lock (cfg->domain);
4123 d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
4124 mono_domain_unlock (cfg->domain);
4126 CHECK_STACK_OVF (1);
4127 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4128 ins->type = STACK_R8;
4138 MonoInst *temp, *store;
4140 CHECK_STACK_OVF (1);
4145 * small optimization: if the loaded value was from a local already,
4146 * just load it twice.
4148 if (ins->ssa_op == MONO_SSA_LOAD &&
4149 (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
4151 MONO_INST_NEW (cfg, temp, 0);
4153 temp->cil_code = ip;
4156 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4157 temp->flags |= MONO_INST_IS_TEMP;
4158 temp->cil_code = ip;
4159 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4160 store->cil_code = ip;
4161 if (store->opcode == CEE_STOBJ) {
4162 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
4163 handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
4165 MONO_ADD_INS (bblock, store);
4167 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
4170 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
4180 MONO_INST_NEW (cfg, ins, CEE_POP);
4181 MONO_ADD_INS (bblock, ins);
4182 ins->cil_code = ip++;
4188 if (stack_start != sp)
4190 MONO_INST_NEW (cfg, ins, CEE_JMP);
4191 token = read32 (ip + 1);
4192 /* FIXME: check the signature matches */
4193 cmethod = mini_get_method (method, token, NULL, generic_context);
4198 if (mono_use_security_manager) {
4199 check_linkdemand (cfg, method, cmethod, bblock, ip);
4202 ins->inst_p0 = cmethod;
4203 MONO_ADD_INS (bblock, ins);
4205 start_new_bblock = 1;
4209 case CEE_CALLVIRT: {
4210 MonoInst *addr = NULL;
4211 MonoMethodSignature *fsig = NULL;
4212 int temp, array_rank = 0;
4213 int virtual = *ip == CEE_CALLVIRT;
4216 token = read32 (ip + 1);
4218 if (*ip == CEE_CALLI) {
4223 if (method->wrapper_type != MONO_WRAPPER_NONE)
4224 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
4226 fsig = mono_metadata_parse_signature (image, token);
4228 n = fsig->param_count + fsig->hasthis;
4230 if (method->wrapper_type != MONO_WRAPPER_NONE) {
4231 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
4232 } else if (constrained_call) {
4233 cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context);
4234 cmethod = mono_get_inflated_method (cmethod);
4236 cmethod = mini_get_method (method, token, NULL, generic_context);
4241 if (!dont_verify && !can_access_method (method, cmethod))
4244 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
4245 /* MS.NET seems to silently convert this to a callvirt */
4248 if (!cmethod->klass->inited){
4249 if (!mono_class_init (cmethod->klass))
4253 if (mono_method_signature (cmethod)->pinvoke) {
4254 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
4255 fsig = mono_method_signature (wrapper);
4256 } else if (constrained_call) {
4257 fsig = mono_method_signature (cmethod);
4259 fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
4262 n = fsig->param_count + fsig->hasthis;
4264 if (mono_use_security_manager) {
4265 check_linkdemand (cfg, method, cmethod, bblock, ip);
4268 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
4269 mini_class_is_system_array (cmethod->klass)) {
4270 array_rank = cmethod->klass->rank;
4273 if (cmethod->string_ctor)
4274 g_assert_not_reached ();
4278 if (cmethod && cmethod->klass->generic_container)
4283 //g_assert (!virtual || fsig->hasthis);
4287 if (constrained_call) {
4289 * We have the `constrained.' prefix opcode.
4291 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
4294 * The type parameter is instantiated as a valuetype,
4295 * but that type doesn't override the method we're
4296 * calling, so we need to box `this'.
4297 * sp [0] is a pointer to the data: we need the value
4298 * in handle_box (), so load it here.
4300 MONO_INST_NEW (cfg, load, mono_type_to_ldind (&constrained_call->byval_arg));
4301 type_to_eval_stack_type (&constrained_call->byval_arg, load);
4302 load->cil_code = ip;
4303 load->inst_left = sp [0];
4304 sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
4305 } else if (!constrained_call->valuetype) {
4309 * The type parameter is instantiated as a reference
4310 * type. We have a managed pointer on the stack, so
4311 * we need to dereference it here.
4314 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
4316 ins->inst_i0 = sp [0];
4317 ins->type = STACK_OBJ;
4319 } else if (cmethod->klass->valuetype)
4321 constrained_call = NULL;
4324 if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
4327 if (cmethod && virtual &&
4328 (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
4329 !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) &&
4330 cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
4331 mono_method_signature (cmethod)->generic_param_count) {
4332 MonoInst *this_temp, *store;
4333 MonoInst *iargs [3];
4335 g_assert (mono_method_signature (cmethod)->is_inflated);
4336 /* Prevent inlining of methods that contain indirect calls */
4339 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
4340 this_temp->cil_code = ip;
4341 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
4343 store->cil_code = ip;
4344 MONO_ADD_INS (bblock, store);
4346 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
4347 NEW_PCONST (cfg, iargs [1], cmethod);
4348 NEW_PCONST (cfg, iargs [2], ((MonoMethodInflated *) cmethod)->context);
4349 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
4351 NEW_TEMPLOAD (cfg, addr, temp);
4352 NEW_TEMPLOAD (cfg, sp [0], this_temp->inst_c0);
4354 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
4355 NEW_TEMPLOAD (cfg, *sp, temp);
4363 if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
4364 (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
4366 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
4368 /* FIXME: This assumes the two methods has the same number and type of arguments */
4369 for (i = 0; i < n; ++i) {
4370 /* Check if argument is the same */
4371 NEW_ARGLOAD (cfg, ins, i);
4372 if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
4375 /* Prevent argument from being register allocated */
4376 arg_array [i]->flags |= MONO_INST_VOLATILE;
4377 NEW_ARGSTORE (cfg, ins, i, sp [i]);
4379 if (ins->opcode == CEE_STOBJ) {
4380 NEW_ARGLOADA (cfg, ins, i);
4381 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
4384 MONO_ADD_INS (bblock, ins);
4386 MONO_INST_NEW (cfg, ins, CEE_JMP);
4388 ins->inst_p0 = cmethod;
4389 ins->inst_p1 = arg_array [0];
4390 MONO_ADD_INS (bblock, ins);
4391 link_bblock (cfg, bblock, end_bblock);
4392 start_new_bblock = 1;
4393 /* skip CEE_RET as well */
4398 if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
4401 if (MONO_TYPE_IS_VOID (fsig->ret)) {
4402 MONO_ADD_INS (bblock, ins);
4404 type_to_eval_stack_type (fsig->ret, ins);
4413 handle_loaded_temps (cfg, bblock, stack_start, sp);
4415 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
4416 (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) &&
4417 mono_method_check_inlining (cfg, cmethod) &&
4418 !g_list_find (dont_inline, cmethod)) {
4420 MonoBasicBlock *ebblock;
4421 gboolean allways = FALSE;
4423 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4424 (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4425 /* Prevent inlining of methods that call wrappers */
4427 cmethod = mono_marshal_get_native_wrapper (cmethod);
4431 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
4435 GET_BBLOCK (cfg, bbhash, bblock, ip);
4436 ebblock->next_bb = bblock;
4437 link_bblock (cfg, ebblock, bblock);
4439 if (!MONO_TYPE_IS_VOID (fsig->ret))
4442 /* indicates start of a new block, and triggers a load of all
4443 stack arguments at bb boundarie */
4446 inline_costs += costs;
4451 inline_costs += 10 * num_calls++;
4453 /* tail recursion elimination */
4454 if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
4455 gboolean has_vtargs = FALSE;
4458 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
4460 /* keep it simple */
4461 for (i = fsig->param_count - 1; i >= 0; i--) {
4462 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i]))
4467 for (i = 0; i < n; ++i) {
4468 NEW_ARGSTORE (cfg, ins, i, sp [i]);
4470 MONO_ADD_INS (bblock, ins);
4472 MONO_INST_NEW (cfg, ins, CEE_BR);
4474 MONO_ADD_INS (bblock, ins);
4475 tblock = start_bblock->out_bb [0];
4476 link_bblock (cfg, bblock, tblock);
4477 ins->inst_target_bb = tblock;
4478 start_new_bblock = 1;
4480 /* skip the CEE_RET, too */
4481 if (ip_in_bb (cfg, bblock, ip + 5))
4490 if (*ip == CEE_CALLI) {
4491 /* Prevent inlining of methods with indirect calls */
4493 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
4494 NEW_TEMPLOAD (cfg, *sp, temp);
4497 } else if (array_rank) {
4500 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */
4501 if (sp [fsig->param_count]->type == STACK_OBJ) {
4502 MonoInst *iargs [2];
4503 MonoInst *array, *to_store, *store;
4505 handle_loaded_temps (cfg, bblock, stack_start, sp);
4507 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
4508 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
4509 store->cil_code = ip;
4510 MONO_ADD_INS (bblock, store);
4511 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
4513 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
4514 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
4515 store->cil_code = ip;
4516 MONO_ADD_INS (bblock, store);
4517 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
4520 * We first save the args for the call so that the args are copied to the stack
4521 * and a new instruction tree for them is created. If we don't do this,
4522 * the same MonoInst is added to two different trees and this is not
4525 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
4527 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
4528 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
4531 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
4532 NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
4534 if (ins->opcode == CEE_STOBJ) {
4535 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
4537 MONO_ADD_INS (bblock, ins);
4540 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
4541 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
4542 NEW_INDLOAD (cfg, ins, addr, fsig->ret);
4546 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
4547 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
4550 g_assert_not_reached ();
4554 /* Prevent inlining of methods which call other methods */
4556 if (ip_in_bb (cfg, bblock, ip + 5)
4557 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
4558 && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)
4559 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET)) {
4560 /* no need to spill */
4561 ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
4564 if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
4565 NEW_TEMPLOAD (cfg, *sp, temp);
4575 if (cfg->method != method) {
4576 /* return from inlined methode */
4581 //g_assert (returnvar != -1);
4582 NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
4583 store->cil_code = sp [0]->cil_code;
4584 if (store->opcode == CEE_STOBJ) {
4585 g_assert_not_reached ();
4586 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
4587 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
4588 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
4590 MONO_ADD_INS (bblock, store);
4594 g_assert (!return_var);
4597 MONO_INST_NEW (cfg, ins, CEE_NOP);
4598 ins->opcode = mono_type_to_stind (mono_method_signature (method)->ret);
4599 if (ins->opcode == CEE_STOBJ) {
4600 NEW_RETLOADA (cfg, ins);
4601 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
4602 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4604 ins->opcode = OP_SETRET;
4606 ins->inst_i0 = *sp;;
4607 ins->inst_i1 = NULL;
4608 MONO_ADD_INS (bblock, ins);
4612 if (sp != stack_start)
4614 MONO_INST_NEW (cfg, ins, CEE_BR);
4615 ins->cil_code = ip++;
4616 ins->inst_target_bb = end_bblock;
4617 MONO_ADD_INS (bblock, ins);
4618 link_bblock (cfg, bblock, end_bblock);
4619 start_new_bblock = 1;
4623 MONO_INST_NEW (cfg, ins, CEE_BR);
4624 ins->cil_code = ip++;
4625 MONO_ADD_INS (bblock, ins);
4626 target = ip + 1 + (signed char)(*ip);
4628 GET_BBLOCK (cfg, bbhash, tblock, target);
4629 link_bblock (cfg, bblock, tblock);
4630 CHECK_BBLOCK (target, ip, tblock);
4631 ins->inst_target_bb = tblock;
4632 if (sp != stack_start) {
4633 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4636 start_new_bblock = 1;
4637 inline_costs += BRANCH_COST;
4643 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
4645 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
4646 ins->cil_code = ip++;
4647 target = ip + 1 + *(signed char*)ip;
4649 ADD_UNCOND (ins->opcode == CEE_BRTRUE);
4650 if (sp != stack_start) {
4651 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4654 inline_costs += BRANCH_COST;
4668 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
4669 ins->cil_code = ip++;
4670 target = ip + 1 + *(signed char*)ip;
4673 if (sp != stack_start) {
4674 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4677 inline_costs += BRANCH_COST;
4681 MONO_INST_NEW (cfg, ins, CEE_BR);
4682 ins->cil_code = ip++;
4683 MONO_ADD_INS (bblock, ins);
4684 target = ip + 4 + (gint32)read32(ip);
4686 GET_BBLOCK (cfg, bbhash, tblock, target);
4687 link_bblock (cfg, bblock, tblock);
4688 CHECK_BBLOCK (target, ip, tblock);
4689 ins->inst_target_bb = tblock;
4690 if (sp != stack_start) {
4691 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4694 start_new_bblock = 1;
4695 inline_costs += BRANCH_COST;
4701 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
4703 MONO_INST_NEW (cfg, ins, *ip);
4704 ins->cil_code = ip++;
4705 target = ip + 4 + (gint32)read32(ip);
4707 ADD_UNCOND(ins->opcode == CEE_BRTRUE);
4708 if (sp != stack_start) {
4709 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4712 inline_costs += BRANCH_COST;
4726 MONO_INST_NEW (cfg, ins, *ip);
4727 ins->cil_code = ip++;
4728 target = ip + 4 + (gint32)read32(ip);
4731 if (sp != stack_start) {
4732 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4735 inline_costs += BRANCH_COST;
4740 n = read32 (ip + 1);
4741 MONO_INST_NEW (cfg, ins, *ip);
4743 ins->inst_left = *sp;
4744 if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR))
4748 CHECK_OPSIZE (n * sizeof (guint32));
4749 target = ip + n * sizeof (guint32);
4750 MONO_ADD_INS (bblock, ins);
4751 GET_BBLOCK (cfg, bbhash, tblock, target);
4752 link_bblock (cfg, bblock, tblock);
4753 ins->klass = GUINT_TO_POINTER (n);
4754 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
4755 ins->inst_many_bb [n] = tblock;
4757 for (i = 0; i < n; ++i) {
4758 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
4759 link_bblock (cfg, bblock, tblock);
4760 ins->inst_many_bb [i] = tblock;
4763 if (sp != stack_start) {
4764 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4767 /* Needed by the code generated in inssel.brg */
4768 mono_get_got_var (cfg);
4769 inline_costs += (BRANCH_COST * 2);
4783 MONO_INST_NEW (cfg, ins, *ip);
4788 ins->type = ldind_type [*ip - CEE_LDIND_I1];
4789 ins->flags |= ins_flag;
4801 #if HAVE_WRITE_BARRIERS
4802 if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER) {
4803 /* insert call to write barrier */
4804 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
4806 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
4811 MONO_INST_NEW (cfg, ins, *ip);
4812 ins->cil_code = ip++;
4814 handle_loaded_temps (cfg, bblock, stack_start, sp);
4815 MONO_ADD_INS (bblock, ins);
4816 ins->inst_i0 = sp [0];
4817 ins->inst_i1 = sp [1];
4818 ins->flags |= ins_flag;
4826 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
4827 /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
4828 if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
4829 switch (ins->opcode) {
4831 ins->opcode = OP_IMUL_IMM;
4832 ins->inst_imm = ins->inst_right->inst_c0;
4835 ins->opcode = OP_LMUL_IMM;
4836 ins->inst_imm = ins->inst_right->inst_c0;
4839 g_assert_not_reached ();
4844 if (mono_find_jit_opcode_emulation (ins->opcode)) {
4846 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
4864 /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
4865 * later apply the speedup to the left shift as well
4868 if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8)
4869 && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
4870 ins->opcode = OP_LONG_SHRUN_32;
4871 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
4875 if (mono_find_jit_opcode_emulation (ins->opcode)) {
4877 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
4891 case CEE_CONV_OVF_I8:
4892 case CEE_CONV_OVF_U8:
4896 if (mono_find_jit_opcode_emulation (ins->opcode)) {
4898 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
4902 case CEE_CONV_OVF_I4:
4903 case CEE_CONV_OVF_I1:
4904 case CEE_CONV_OVF_I2:
4905 case CEE_CONV_OVF_I:
4906 case CEE_CONV_OVF_U:
4909 if (sp [-1]->type == STACK_R8) {
4910 ADD_UNOP (CEE_CONV_OVF_I8);
4918 case CEE_CONV_OVF_U1:
4919 case CEE_CONV_OVF_U2:
4920 case CEE_CONV_OVF_U4:
4923 if (sp [-1]->type == STACK_R8) {
4924 ADD_UNOP (CEE_CONV_OVF_U8);
4932 case CEE_CONV_OVF_I1_UN:
4933 case CEE_CONV_OVF_I2_UN:
4934 case CEE_CONV_OVF_I4_UN:
4935 case CEE_CONV_OVF_I8_UN:
4936 case CEE_CONV_OVF_U1_UN:
4937 case CEE_CONV_OVF_U2_UN:
4938 case CEE_CONV_OVF_U4_UN:
4939 case CEE_CONV_OVF_U8_UN:
4940 case CEE_CONV_OVF_I_UN:
4941 case CEE_CONV_OVF_U_UN:
4949 token = read32 (ip + 1);
4950 klass = mini_get_class (method, token, generic_context);
4954 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4955 MonoInst *store, *load;
4956 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
4957 load->cil_code = ip;
4958 load->inst_i0 = sp [1];
4959 load->type = STACK_OBJ;
4960 load->flags |= ins_flag;
4961 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
4962 store->cil_code = ip;
4963 handle_loaded_temps (cfg, bblock, stack_start, sp);
4964 MONO_ADD_INS (bblock, store);
4965 store->inst_i0 = sp [0];
4966 store->inst_i1 = load;
4967 store->flags |= ins_flag;
4969 n = mono_class_value_size (klass, NULL);
4970 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
4972 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
4973 copy->inst_left = sp [0];
4974 copy->inst_right = sp [1];
4975 copy->cil_code = ip;
4977 MONO_ADD_INS (bblock, copy);
4979 MonoMethod *memcpy_method = get_memcpy_method ();
4980 MonoInst *iargs [3];
4983 NEW_ICONST (cfg, iargs [2], n);
4984 iargs [2]->cil_code = ip;
4986 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
4993 MonoInst *iargs [3];
4999 token = read32 (ip + 1);
5000 klass = mini_get_class (method, token, generic_context);
5003 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5004 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5006 ins->inst_i0 = sp [0];
5007 ins->type = STACK_OBJ;
5008 ins->flags |= ins_flag;
5015 /* Optimize the common ldobj+stloc combination */
5025 loc_index = ip [5] - CEE_STLOC_0;
5032 if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
5033 CHECK_LOCAL (loc_index);
5034 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
5036 if (ins->opcode == CEE_STOBJ) {
5037 handle_loaded_temps (cfg, bblock, stack_start, sp);
5039 g_assert (ins->opcode == CEE_STOBJ);
5040 NEW_LOCLOADA (cfg, ins, loc_index);
5041 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5048 n = mono_class_value_size (klass, NULL);
5049 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
5050 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
5051 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5053 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5054 copy->inst_left = iargs [0];
5055 copy->inst_right = *sp;
5056 copy->cil_code = ip;
5058 MONO_ADD_INS (bblock, copy);
5060 MonoMethod *memcpy_method = get_memcpy_method ();
5062 NEW_ICONST (cfg, iargs [2], n);
5063 iargs [2]->cil_code = ip;
5065 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
5067 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
5075 CHECK_STACK_OVF (1);
5077 n = read32 (ip + 1);
5079 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
5080 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
5082 ins->type = STACK_OBJ;
5085 else if (method->wrapper_type != MONO_WRAPPER_NONE) {
5087 MonoInst *iargs [1];
5089 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));
5090 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
5091 NEW_TEMPLOAD (cfg, *sp, temp);
5095 if (cfg->opt & MONO_OPT_SHARED) {
5097 MonoInst *iargs [3];
5098 MonoInst* domain_var;
5100 if (cfg->compile_aot) {
5101 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
5103 /* avoid depending on undefined C behavior in sequence points */
5104 domain_var = mono_get_domainvar (cfg);
5105 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
5106 NEW_IMAGECONST (cfg, iargs [1], image);
5107 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
5108 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
5109 NEW_TEMPLOAD (cfg, *sp, temp);
5110 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
5112 if (bblock->out_of_line) {
5113 MonoInst *iargs [2];
5116 if (cfg->compile_aot && cfg->method->klass->image == mono_defaults.corlib) {
5118 * Avoid relocations by using a version of helper_ldstr
5119 * specialized to mscorlib.
5121 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
5122 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
5124 /* Avoid creating the string object */
5125 NEW_IMAGECONST (cfg, iargs [0], image);
5126 NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
5127 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
5129 NEW_TEMPLOAD (cfg, *sp, temp);
5132 if (cfg->compile_aot) {
5133 NEW_LDSTRCONST (cfg, ins, image, n);
5137 NEW_PCONST (cfg, ins, NULL);
5139 ins->type = STACK_OBJ;
5140 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
5150 MonoInst *iargs [2];
5151 MonoMethodSignature *fsig;
5155 token = read32 (ip + 1);
5156 cmethod = mini_get_method (method, token, NULL, generic_context);
5159 fsig = mono_method_get_signature (cmethod, image, token);
5161 if (!mono_class_init (cmethod->klass))
5164 if (mono_use_security_manager) {
5165 check_linkdemand (cfg, method, cmethod, bblock, ip);
5168 n = fsig->param_count;
5171 /* move the args to allow room for 'this' in the first position */
5177 handle_loaded_temps (cfg, bblock, stack_start, sp);
5179 if (mini_class_is_system_array (cmethod->klass)) {
5180 NEW_METHODCONST (cfg, *sp, cmethod);
5181 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
5182 } else if (cmethod->string_ctor) {
5183 /* we simply pass a null pointer */
5184 NEW_PCONST (cfg, *sp, NULL);
5185 /* now call the string ctor */
5186 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
5188 MonoInst* callvirt_this_arg = NULL;
5190 if (cmethod->klass->valuetype) {
5191 iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
5192 temp = iargs [0]->inst_c0;
5194 NEW_TEMPLOADA (cfg, *sp, temp);
5196 handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
5198 NEW_TEMPLOADA (cfg, *sp, temp);
5201 * The code generated by mini_emit_virtual_call () expects
5202 * iargs [0] to be a boxed instance, but luckily the vcall
5203 * will be transformed into a normal call there.
5206 temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
5207 NEW_TEMPLOAD (cfg, *sp, temp);
5210 /* Avoid virtual calls to ctors if possible */
5211 if (cmethod->klass->marshalbyref)
5212 callvirt_this_arg = sp [0];
5214 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5215 mono_method_check_inlining (cfg, cmethod) &&
5216 !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
5217 !g_list_find (dont_inline, cmethod)) {
5219 MonoBasicBlock *ebblock;
5220 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
5225 GET_BBLOCK (cfg, bbhash, bblock, ip);
5226 ebblock->next_bb = bblock;
5227 link_bblock (cfg, ebblock, bblock);
5229 NEW_TEMPLOAD (cfg, *sp, temp);
5232 /* indicates start of a new block, and triggers a load
5233 of all stack arguments at bb boundarie */
5236 inline_costs += costs;
5240 /* Prevent inlining of methods which call other methods */
5242 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
5245 /* Prevent inlining of methods which call other methods */
5247 /* now call the actual ctor */
5248 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
5252 NEW_TEMPLOAD (cfg, *sp, temp);
5263 token = read32 (ip + 1);
5264 klass = mini_get_class (method, token, generic_context);
5267 if (sp [0]->type != STACK_OBJ)
5270 /* Needed by the code generated in inssel.brg */
5271 mono_get_got_var (cfg);
5273 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
5275 MonoMethod *mono_isinst;
5276 MonoInst *iargs [1];
5277 MonoBasicBlock *ebblock;
5281 mono_isinst = mono_marshal_get_isinst (klass);
5284 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock,
5285 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5287 g_assert (costs > 0);
5292 GET_BBLOCK (cfg, bbhash, bblock, ip);
5293 ebblock->next_bb = bblock;
5294 link_bblock (cfg, ebblock, bblock);
5296 temp = iargs [0]->inst_i0->inst_c0;
5297 NEW_TEMPLOAD (cfg, *sp, temp);
5301 inline_costs += costs;
5303 MONO_INST_NEW (cfg, ins, *ip);
5304 ins->type = STACK_OBJ;
5305 ins->inst_left = *sp;
5306 ins->inst_newa_class = klass;
5309 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
5313 case CEE_UNBOX_ANY: {
5314 MonoInst *add, *vtoffset;
5315 MonoInst *iargs [3];
5320 token = read32 (ip + 1);
5321 klass = mini_get_class (method, token, generic_context);
5325 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5327 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
5328 MonoMethod *mono_castclass;
5329 MonoInst *iargs [1];
5330 MonoBasicBlock *ebblock;
5334 mono_castclass = mono_marshal_get_castclass (klass);
5337 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
5338 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5340 g_assert (costs > 0);
5345 GET_BBLOCK (cfg, bbhash, bblock, ip);
5346 ebblock->next_bb = bblock;
5347 link_bblock (cfg, ebblock, bblock);
5349 temp = iargs [0]->inst_i0->inst_c0;
5350 NEW_TEMPLOAD (cfg, *sp, temp);
5354 inline_costs += costs;
5356 MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
5357 ins->type = STACK_OBJ;
5358 ins->inst_left = *sp;
5360 ins->inst_newa_class = klass;
5368 if (mono_class_is_nullable (klass)) {
5369 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
5370 NEW_TEMPLOAD (cfg, *sp, v);
5376 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
5377 ins->type = STACK_OBJ;
5378 ins->inst_left = *sp;
5380 ins->inst_newa_class = klass;
5383 MONO_INST_NEW (cfg, add, OP_PADD);
5384 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
5385 add->inst_left = ins;
5386 add->inst_right = vtoffset;
5387 add->type = STACK_MP;
5391 n = mono_class_value_size (klass, NULL);
5392 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
5393 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
5394 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5396 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5397 copy->inst_left = iargs [0];
5398 copy->inst_right = *sp;
5399 copy->cil_code = ip;
5401 MONO_ADD_INS (bblock, copy);
5403 MonoMethod *memcpy_method = get_memcpy_method ();
5405 NEW_ICONST (cfg, iargs [2], n);
5406 iargs [2]->cil_code = ip;
5408 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
5410 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
5416 MonoInst *add, *vtoffset;
5421 token = read32 (ip + 1);
5422 klass = mini_get_class (method, token, generic_context);
5426 if (mono_class_is_nullable (klass)) {
5427 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
5428 NEW_TEMPLOAD (cfg, *sp, v);
5434 /* Needed by the code generated in inssel.brg */
5435 mono_get_got_var (cfg);
5437 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
5438 ins->type = STACK_OBJ;
5439 ins->inst_left = *sp;
5441 ins->inst_newa_class = klass;
5444 MONO_INST_NEW (cfg, add, OP_PADD);
5445 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
5446 add->inst_left = ins;
5447 add->inst_right = vtoffset;
5448 add->type = STACK_MP;
5459 token = read32 (ip + 1);
5460 klass = mini_get_class (method, token, generic_context);
5463 if (sp [0]->type != STACK_OBJ)
5466 /* Needed by the code generated in inssel.brg */
5467 mono_get_got_var (cfg);
5469 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
5471 MonoMethod *mono_castclass;
5472 MonoInst *iargs [1];
5473 MonoBasicBlock *ebblock;
5477 mono_castclass = mono_marshal_get_castclass (klass);
5480 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
5481 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5483 g_assert (costs > 0);
5488 GET_BBLOCK (cfg, bbhash, bblock, ip);
5489 ebblock->next_bb = bblock;
5490 link_bblock (cfg, ebblock, bblock);
5492 temp = iargs [0]->inst_i0->inst_c0;
5493 NEW_TEMPLOAD (cfg, *sp, temp);
5497 inline_costs += costs;
5499 MONO_INST_NEW (cfg, ins, *ip);
5500 ins->type = STACK_OBJ;
5501 ins->inst_left = *sp;
5503 ins->inst_newa_class = klass;
5505 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
5511 MONO_INST_NEW (cfg, ins, *ip);
5513 ins->inst_left = *sp;
5514 ins->cil_code = ip++;
5515 bblock->out_of_line = TRUE;
5516 MONO_ADD_INS (bblock, ins);
5517 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
5518 ins->cil_code = ip - 1;
5519 MONO_ADD_INS (bblock, ins);
5522 link_bblock (cfg, bblock, end_bblock);
5523 start_new_bblock = 1;
5528 MonoInst *offset_ins;
5529 MonoClassField *field;
5530 MonoBasicBlock *ebblock;
5534 if (*ip == CEE_STFLD) {
5541 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
5543 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
5546 token = read32 (ip + 1);
5547 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5548 field = mono_method_get_wrapper_data (method, token);
5549 klass = field->parent;
5551 field = mono_field_from_token (image, token, &klass, generic_context);
5555 mono_class_init (klass);
5556 if (!dont_verify && !can_access_field (method, field))
5559 foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
5560 /* FIXME: mark instructions for use in SSA */
5561 if (*ip == CEE_STFLD) {
5562 if (target_type_is_incompatible (cfg, field->type, sp [1]))
5564 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
5565 MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type);
5566 MonoInst *iargs [5];
5569 NEW_CLASSCONST (cfg, iargs [1], klass);
5570 NEW_FIELDCONST (cfg, iargs [2], field);
5571 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) :
5575 if (cfg->opt & MONO_OPT_INLINE) {
5576 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock,
5577 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5578 g_assert (costs > 0);
5583 GET_BBLOCK (cfg, bbhash, bblock, ip);
5584 ebblock->next_bb = bblock;
5585 link_bblock (cfg, ebblock, bblock);
5587 /* indicates start of a new block, and triggers a load
5588 of all stack arguments at bb boundarie */
5591 inline_costs += costs;
5594 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
5596 #if HAVE_WRITE_BARRIERS
5597 } else if (mono_type_to_stind (field->type) == CEE_STIND_REF) {
5598 /* insert call to write barrier */
5599 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
5600 MonoInst *iargs [2];
5601 NEW_ICONST (cfg, offset_ins, foffset);
5602 MONO_INST_NEW (cfg, ins, OP_PADD);
5604 ins->inst_left = *sp;
5605 ins->inst_right = offset_ins;
5606 ins->type = STACK_MP;
5609 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
5613 NEW_ICONST (cfg, offset_ins, foffset);
5614 MONO_INST_NEW (cfg, ins, OP_PADD);
5616 ins->inst_left = *sp;
5617 ins->inst_right = offset_ins;
5618 ins->type = STACK_MP;
5620 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
5621 store->cil_code = ip;
5622 store->inst_left = ins;
5623 store->inst_right = sp [1];
5624 handle_loaded_temps (cfg, bblock, stack_start, sp);
5625 store->flags |= ins_flag;
5627 if (store->opcode == CEE_STOBJ) {
5628 handle_stobj (cfg, bblock, ins, sp [1], ip,
5629 mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
5631 MONO_ADD_INS (bblock, store);
5634 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
5635 MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type);
5636 MonoInst *iargs [4];
5640 NEW_CLASSCONST (cfg, iargs [1], klass);
5641 NEW_FIELDCONST (cfg, iargs [2], field);
5642 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
5643 if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
5644 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock,
5645 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5646 g_assert (costs > 0);
5651 GET_BBLOCK (cfg, bbhash, bblock, ip);
5652 ebblock->next_bb = bblock;
5653 link_bblock (cfg, ebblock, bblock);
5655 temp = iargs [0]->inst_i0->inst_c0;
5657 NEW_TEMPLOAD (cfg, *sp, temp);
5660 /* indicates start of a new block, and triggers a load of
5661 all stack arguments at bb boundarie */
5664 inline_costs += costs;
5667 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
5668 NEW_TEMPLOAD (cfg, *sp, temp);
5672 NEW_ICONST (cfg, offset_ins, foffset);
5673 MONO_INST_NEW (cfg, ins, OP_PADD);
5675 ins->inst_left = *sp;
5676 ins->inst_right = offset_ins;
5677 ins->type = STACK_MP;
5679 if (*ip == CEE_LDFLDA) {
5680 ins->klass = mono_class_from_mono_type (field->type);
5684 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
5685 type_to_eval_stack_type (field->type, load);
5686 load->cil_code = ip;
5687 load->inst_left = ins;
5688 load->flags |= ins_flag;
5700 MonoClassField *field;
5701 gpointer addr = NULL;
5704 token = read32 (ip + 1);
5705 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5706 field = mono_method_get_wrapper_data (method, token);
5707 klass = field->parent;
5710 field = mono_field_from_token (image, token, &klass, generic_context);
5713 mono_class_init (klass);
5715 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
5717 if ((*ip) == CEE_STSFLD)
5718 handle_loaded_temps (cfg, bblock, stack_start, sp);
5720 /* The special_static_fields field is init'd in mono_class_vtable, so it needs
5721 * to be called here.
5723 if (!(cfg->opt & MONO_OPT_SHARED))
5724 mono_class_vtable (cfg->domain, klass);
5725 mono_domain_lock (cfg->domain);
5726 if (cfg->domain->special_static_fields)
5727 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
5728 mono_domain_unlock (cfg->domain);
5730 if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
5732 MonoInst *iargs [2];
5733 MonoInst *domain_var;
5735 g_assert (field->parent);
5736 /* avoid depending on undefined C behavior in sequence points */
5737 domain_var = mono_get_domainvar (cfg);
5738 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
5739 NEW_FIELDCONST (cfg, iargs [1], field);
5740 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
5741 NEW_TEMPLOAD (cfg, ins, temp);
5744 vtable = mono_class_vtable (cfg->domain, klass);
5746 if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
5747 guint8 *tramp = mono_create_class_init_trampoline (vtable);
5748 mono_emit_native_call (cfg, bblock, tramp,
5749 helper_sig_class_init_trampoline,
5750 NULL, ip, FALSE, FALSE);
5751 if (cfg->verbose_level > 2)
5752 g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
5753 class_inits = g_slist_prepend (class_inits, vtable);
5755 if (cfg->run_cctors)
5756 mono_runtime_class_init (vtable);
5758 addr = (char*)vtable->data + field->offset;
5760 if (cfg->compile_aot)
5761 NEW_SFLDACONST (cfg, ins, field);
5763 NEW_PCONST (cfg, ins, addr);
5767 * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr))
5768 * This could be later optimized to do just a couple of
5769 * memory dereferences with constant offsets.
5772 MonoInst *iargs [1];
5773 NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
5774 temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
5775 NEW_TEMPLOAD (cfg, ins, temp);
5779 /* FIXME: mark instructions for use in SSA */
5780 if (*ip == CEE_LDSFLDA) {
5781 ins->klass = mono_class_from_mono_type (field->type);
5783 } else if (*ip == CEE_STSFLD) {
5787 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
5788 store->cil_code = ip;
5789 store->inst_left = ins;
5790 store->inst_right = sp [0];
5791 store->flags |= ins_flag;
5794 if (store->opcode == CEE_STOBJ) {
5795 handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
5797 MONO_ADD_INS (bblock, store);
5799 gboolean is_const = FALSE;
5800 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
5801 if (!((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) &&
5802 vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
5803 gpointer addr = (char*)vtable->data + field->offset;
5804 int ro_type = field->type->type;
5805 if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
5806 ro_type = field->type->data.klass->enum_basetype->type;
5808 /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
5811 case MONO_TYPE_BOOLEAN:
5813 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
5817 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
5820 case MONO_TYPE_CHAR:
5822 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
5826 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
5831 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
5835 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
5838 #ifndef HAVE_MOVING_COLLECTOR
5841 case MONO_TYPE_STRING:
5842 case MONO_TYPE_OBJECT:
5843 case MONO_TYPE_CLASS:
5844 case MONO_TYPE_SZARRAY:
5846 case MONO_TYPE_FNPTR:
5847 case MONO_TYPE_ARRAY:
5848 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
5849 type_to_eval_stack_type (field->type, *sp);
5855 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
5856 sp [0]->type = STACK_I8;
5857 sp [0]->inst_l = *((gint64 *)addr);
5862 case MONO_TYPE_VALUETYPE:
5871 CHECK_STACK_OVF (1);
5872 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
5873 type_to_eval_stack_type (field->type, load);
5874 load->cil_code = ip;
5875 load->inst_left = ins;
5877 load->flags |= ins_flag;
5879 /* fixme: dont see the problem why this does not work */
5880 //cfg->disable_aot = TRUE;
5890 token = read32 (ip + 1);
5891 klass = mini_get_class (method, token, generic_context);
5894 n = mono_type_to_stind (&klass->byval_arg);
5895 if (n == CEE_STOBJ) {
5896 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
5898 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
5900 MONO_INST_NEW (cfg, store, n);
5901 store->cil_code = ip;
5902 store->inst_left = sp [0];
5903 store->inst_right = sp [1];
5904 store->flags |= ins_flag;
5905 MONO_ADD_INS (bblock, store);
5917 token = read32 (ip + 1);
5918 klass = mini_get_class (method, token, generic_context);
5922 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5927 if (klass == mono_defaults.void_class)
5929 if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
5931 /* frequent check in generic code: box (struct), brtrue */
5932 if (!mono_class_is_nullable (klass) &&
5933 ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
5934 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
5935 MONO_INST_NEW (cfg, ins, CEE_POP);
5936 MONO_ADD_INS (bblock, ins);
5940 MONO_INST_NEW (cfg, ins, CEE_BR);
5942 MONO_ADD_INS (bblock, ins);
5943 if (*ip == CEE_BRTRUE_S) {
5946 target = ip + 1 + (signed char)(*ip);
5951 target = ip + 4 + (gint)(read32 (ip));
5954 GET_BBLOCK (cfg, bbhash, tblock, target);
5955 link_bblock (cfg, bblock, tblock);
5956 CHECK_BBLOCK (target, ip, tblock);
5957 ins->inst_target_bb = tblock;
5958 if (sp != stack_start) {
5959 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5962 start_new_bblock = 1;
5965 *sp++ = handle_box (cfg, bblock, val, ip, klass);
5972 MONO_INST_NEW (cfg, ins, *ip);
5977 token = read32 (ip + 1);
5979 /* allocate the domainvar - becaus this is used in decompose_foreach */
5980 if (cfg->opt & MONO_OPT_SHARED) {
5981 mono_get_domainvar (cfg);
5982 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
5983 cfg->domainvar->flags |= MONO_INST_VOLATILE;
5987 mono_get_got_var (cfg);
5989 klass = mini_get_class (method, token, generic_context);
5992 ins->inst_newa_class = klass;
5993 ins->inst_newa_len = *sp;
5994 ins->type = STACK_OBJ;
5998 * we store the object so calls to create the array are not interleaved
5999 * with the arguments of other calls.
6002 MonoInst *store, *temp, *load;
6004 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
6005 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
6006 store->cil_code = ins->cil_code;
6007 MONO_ADD_INS (bblock, store);
6008 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
6009 load->cil_code = ins->cil_code;
6017 if (sp [0]->type != STACK_OBJ)
6019 MONO_INST_NEW (cfg, ins, *ip);
6020 ins->cil_code = ip++;
6021 ins->inst_left = *sp;
6022 ins->type = STACK_PTR;
6029 if (sp [0]->type != STACK_OBJ)
6032 klass = mini_get_class (method, read32 (ip + 1), generic_context);
6035 /* we need to make sure that this array is exactly the type it needs
6036 * to be for correctness. the wrappers are lax with their usage
6037 * so we need to ignore them here
6039 if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
6041 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
6042 check->cil_code = ip;
6043 check->klass = klass;
6044 check->inst_left = sp [0];
6045 check->type = STACK_OBJ;
6049 mono_class_init (klass);
6050 NEW_LDELEMA (cfg, ins, sp, klass);
6055 case CEE_LDELEM_ANY: {
6059 if (sp [0]->type != STACK_OBJ)
6062 token = read32 (ip + 1);
6063 klass = mono_class_get_full (image, token, generic_context);
6066 mono_class_init (klass);
6067 NEW_LDELEMA (cfg, load, sp, klass);
6068 load->cil_code = ip;
6069 MONO_INST_NEW (cfg, ins, mono_type_to_ldind (&klass->byval_arg));
6071 ins->inst_left = load;
6073 type_to_eval_stack_type (&klass->byval_arg, ins);
6087 case CEE_LDELEM_REF: {
6091 * ldind.x (ldelema (array, index))
6092 * ldelema does the bounds check
6096 if (sp [0]->type != STACK_OBJ)
6098 klass = array_access_to_klass (*ip);
6099 NEW_LDELEMA (cfg, load, sp, klass);
6100 load->cil_code = ip;
6101 MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
6103 ins->inst_left = load;
6105 ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
6115 case CEE_STELEM_R8: {
6119 * stind.x (ldelema (array, index), val)
6120 * ldelema does the bounds check
6124 if (sp [0]->type != STACK_OBJ)
6126 klass = array_access_to_klass (*ip);
6127 NEW_LDELEMA (cfg, load, sp, klass);
6128 load->cil_code = ip;
6129 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
6131 ins->inst_left = load;
6132 ins->inst_right = sp [2];
6134 handle_loaded_temps (cfg, bblock, stack_start, sp);
6135 MONO_ADD_INS (bblock, ins);
6139 case CEE_STELEM_ANY: {
6143 * stind.x (ldelema (array, index), val)
6144 * ldelema does the bounds check
6148 if (sp [0]->type != STACK_OBJ)
6151 token = read32 (ip + 1);
6152 klass = mono_class_get_full (image, token, generic_context);
6155 mono_class_init (klass);
6156 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6157 MonoMethod* helper = mono_marshal_get_stelemref ();
6158 MonoInst *iargs [3];
6159 handle_loaded_temps (cfg, bblock, stack_start, sp);
6165 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
6167 NEW_LDELEMA (cfg, load, sp, klass);
6168 load->cil_code = ip;
6170 n = mono_type_to_stind (&klass->byval_arg);
6172 handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
6174 MONO_INST_NEW (cfg, ins, n);
6176 ins->inst_left = load;
6177 ins->inst_right = sp [2];
6178 handle_loaded_temps (cfg, bblock, stack_start, sp);
6179 MONO_ADD_INS (bblock, ins);
6186 case CEE_STELEM_REF: {
6187 MonoInst *iargs [3];
6188 MonoMethod* helper = mono_marshal_get_stelemref ();
6192 if (sp [0]->type != STACK_OBJ)
6194 if (sp [2]->type != STACK_OBJ)
6197 handle_loaded_temps (cfg, bblock, stack_start, sp);
6203 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
6207 NEW_GROUP (cfg, group, sp [0], sp [1]);
6208 MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
6210 ins->inst_left = group;
6211 ins->inst_right = sp [2];
6212 MONO_ADD_INS (bblock, ins);
6219 case CEE_CKFINITE: {
6220 MonoInst *store, *temp;
6223 /* this instr. can throw exceptions as side effect,
6224 * so we cant eliminate dead code which contains CKFINITE opdodes.
6225 * Spilling to memory makes sure that we always perform
6229 MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
6231 ins->inst_left = sp [-1];
6232 temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
6234 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
6235 store->cil_code = ip;
6236 MONO_ADD_INS (bblock, store);
6238 NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
6245 MONO_INST_NEW (cfg, ins, *ip);
6248 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
6251 mono_class_init (klass);
6252 ins->type = STACK_MP;
6253 ins->inst_left = *sp;
6255 ins->inst_newa_class = klass;
6260 case CEE_MKREFANY: {
6261 MonoInst *loc, *klassconst;
6264 MONO_INST_NEW (cfg, ins, *ip);
6267 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
6270 mono_class_init (klass);
6273 loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
6274 NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
6276 NEW_PCONST (cfg, klassconst, klass);
6277 NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
6279 MONO_ADD_INS (bblock, ins);
6281 NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
6288 MonoClass *handle_class;
6290 CHECK_STACK_OVF (1);
6293 n = read32 (ip + 1);
6295 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6296 handle = mono_method_get_wrapper_data (method, n);
6297 handle_class = mono_method_get_wrapper_data (method, n + 1);
6298 if (handle_class == mono_defaults.typehandle_class)
6299 handle = &((MonoClass*)handle)->byval_arg;
6302 handle = mono_ldtoken (image, n, &handle_class, generic_context);
6306 mono_class_init (handle_class);
6308 if (cfg->opt & MONO_OPT_SHARED) {
6310 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
6312 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
6314 NEW_IMAGECONST (cfg, iargs [0], image);
6315 NEW_ICONST (cfg, iargs [1], n);
6316 NEW_PCONST (cfg, iargs [2], generic_context);
6317 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
6318 NEW_TEMPLOAD (cfg, res, temp);
6319 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6320 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
6321 MONO_ADD_INS (bblock, store);
6322 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6324 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
6325 (cmethod->klass == mono_defaults.monotype_class->parent) &&
6326 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && ip_in_bb (cfg, bblock, ip + 5)) {
6327 MonoClass *tclass = mono_class_from_mono_type (handle);
6328 mono_class_init (tclass);
6329 if (cfg->compile_aot)
6330 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
6332 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
6333 ins->type = STACK_OBJ;
6334 ins->klass = cmethod->klass;
6337 MonoInst *store, *addr, *vtvar;
6339 if (cfg->compile_aot)
6340 NEW_LDTOKENCONST (cfg, ins, image, n);
6342 NEW_PCONST (cfg, ins, handle);
6343 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
6344 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6345 NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
6346 MONO_ADD_INS (bblock, store);
6347 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6363 case CEE_ADD_OVF_UN:
6365 case CEE_MUL_OVF_UN:
6367 case CEE_SUB_OVF_UN:
6370 if (mono_find_jit_opcode_emulation (ins->opcode)) {
6372 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6376 case CEE_ENDFINALLY:
6377 MONO_INST_NEW (cfg, ins, *ip);
6378 MONO_ADD_INS (bblock, ins);
6379 ins->cil_code = ip++;
6380 start_new_bblock = 1;
6383 * Control will leave the method so empty the stack, otherwise
6384 * the next basic block will start with a nonempty stack.
6386 while (sp != stack_start) {
6387 MONO_INST_NEW (cfg, ins, CEE_POP);
6391 MONO_ADD_INS (bblock, ins);
6398 if (*ip == CEE_LEAVE) {
6400 target = ip + 5 + (gint32)read32(ip + 1);
6403 target = ip + 2 + (signed char)(ip [1]);
6406 /* empty the stack */
6407 while (sp != stack_start) {
6408 MONO_INST_NEW (cfg, ins, CEE_POP);
6412 MONO_ADD_INS (bblock, ins);
6416 * If this leave statement is in a catch block, check for a
6417 * pending exception, and rethrow it if necessary.
6419 for (i = 0; i < header->num_clauses; ++i) {
6420 MonoExceptionClause *clause = &header->clauses [i];
6423 * Use <= in the final comparison to handle clauses with multiple
6424 * leave statements, like in bug #78024.
6425 * The ordering of the exception clauses guarantees that we find the
6428 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) && (ip - header->code + ((*ip == CEE_LEAVE) ? 5 : 2)) <= (clause->handler_offset + clause->handler_len)) {
6432 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
6433 load->cil_code = ip;
6435 temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
6436 NEW_TEMPLOAD (cfg, *sp, temp);
6438 MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
6439 ins->inst_left = *sp;
6440 ins->inst_right = load;
6442 MONO_ADD_INS (bblock, ins);
6446 /* fixme: call fault handler ? */
6448 if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
6450 for (tmp = handlers; tmp; tmp = tmp->next) {
6452 link_bblock (cfg, bblock, tblock);
6453 MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
6455 ins->inst_target_bb = tblock;
6456 MONO_ADD_INS (bblock, ins);
6458 g_list_free (handlers);
6461 MONO_INST_NEW (cfg, ins, CEE_BR);
6463 MONO_ADD_INS (bblock, ins);
6464 GET_BBLOCK (cfg, bbhash, tblock, target);
6465 link_bblock (cfg, bblock, tblock);
6466 CHECK_BBLOCK (target, ip, tblock);
6467 ins->inst_target_bb = tblock;
6468 start_new_bblock = 1;
6470 if (*ip == CEE_LEAVE)
6479 MONO_INST_NEW (cfg, ins, *ip);
6481 handle_loaded_temps (cfg, bblock, stack_start, sp);
6482 MONO_ADD_INS (bblock, ins);
6483 ins->cil_code = ip++;
6484 ins->inst_i0 = sp [0];
6485 ins->inst_i1 = sp [1];
6493 /* trampoline mono specific opcodes */
6494 case MONO_CUSTOM_PREFIX: {
6496 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
6501 case CEE_MONO_ICALL: {
6504 MonoJitICallInfo *info;
6506 token = read32 (ip + 2);
6507 func = mono_method_get_wrapper_data (method, token);
6508 info = mono_find_jit_icall_by_addr (func);
6511 CHECK_STACK (info->sig->param_count);
6512 sp -= info->sig->param_count;
6514 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
6515 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
6516 NEW_TEMPLOAD (cfg, *sp, temp);
6521 inline_costs += 10 * num_calls++;
6525 case CEE_MONO_LDPTR:
6526 CHECK_STACK_OVF (1);
6528 token = read32 (ip + 2);
6529 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
6533 inline_costs += 10 * num_calls++;
6534 /* Can't embed random pointers into AOT code */
6535 cfg->disable_aot = 1;
6537 case CEE_MONO_VTADDR:
6540 MONO_INST_NEW (cfg, ins, OP_VTADDR);
6542 ins->type = STACK_MP;
6543 ins->inst_left = *sp;
6547 case CEE_MONO_NEWOBJ: {
6548 MonoInst *iargs [2];
6550 CHECK_STACK_OVF (1);
6552 token = read32 (ip + 2);
6553 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6554 mono_class_init (klass);
6555 NEW_DOMAINCONST (cfg, iargs [0]);
6556 NEW_CLASSCONST (cfg, iargs [1], klass);
6557 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
6558 NEW_TEMPLOAD (cfg, *sp, temp);
6561 inline_costs += 10 * num_calls++;
6564 case CEE_MONO_OBJADDR:
6567 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
6569 ins->type = STACK_MP;
6570 ins->inst_left = *sp;
6574 case CEE_MONO_LDNATIVEOBJ:
6577 token = read32 (ip + 2);
6578 klass = mono_method_get_wrapper_data (method, token);
6579 g_assert (klass->valuetype);
6580 mono_class_init (klass);
6581 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
6585 case CEE_MONO_RETOBJ:
6586 g_assert (cfg->ret);
6587 g_assert (mono_method_signature (method)->pinvoke);
6592 token = read32 (ip + 2);
6593 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6595 NEW_RETLOADA (cfg, ins);
6596 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
6598 if (sp != stack_start)
6601 MONO_INST_NEW (cfg, ins, CEE_BR);
6603 ins->inst_target_bb = end_bblock;
6604 MONO_ADD_INS (bblock, ins);
6605 link_bblock (cfg, bblock, end_bblock);
6606 start_new_bblock = 1;
6609 case CEE_MONO_CISINST:
6610 case CEE_MONO_CCASTCLASS: {
6615 token = read32 (ip + 2);
6616 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6617 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
6618 ins->type = STACK_I4;
6619 ins->inst_left = *sp;
6620 ins->inst_newa_class = klass;
6622 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
6626 case CEE_MONO_SAVE_LMF:
6627 case CEE_MONO_RESTORE_LMF:
6628 #ifdef MONO_ARCH_HAVE_LMF_OPS
6629 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
6630 MONO_ADD_INS (bblock, ins);
6631 cfg->need_lmf_area = TRUE;
6635 case CEE_MONO_CLASSCONST:
6636 CHECK_STACK_OVF (1);
6638 token = read32 (ip + 2);
6639 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
6643 inline_costs += 10 * num_calls++;
6645 case CEE_MONO_NOT_TAKEN:
6646 bblock->out_of_line = TRUE;
6650 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
6659 /* somewhat similar to LDTOKEN */
6660 MonoInst *addr, *vtvar;
6661 CHECK_STACK_OVF (1);
6662 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL);
6664 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6665 addr->cil_code = ip;
6666 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
6668 ins->inst_left = addr;
6669 MONO_ADD_INS (bblock, ins);
6670 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6684 * The following transforms:
6685 * CEE_CEQ into OP_CEQ
6686 * CEE_CGT into OP_CGT
6687 * CEE_CGT_UN into OP_CGT_UN
6688 * CEE_CLT into OP_CLT
6689 * CEE_CLT_UN into OP_CLT_UN
6691 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
6693 MONO_INST_NEW (cfg, ins, cmp->opcode);
6695 cmp->inst_i0 = sp [0];
6696 cmp->inst_i1 = sp [1];
6700 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
6701 cmp->opcode = OP_LCOMPARE;
6703 cmp->opcode = OP_COMPARE;
6705 ins->type = STACK_I4;
6708 /* spill it to reduce the expression complexity
6709 * and workaround bug 54209
6711 if (cmp->inst_left->type == STACK_I8) {
6713 *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
6722 CHECK_STACK_OVF (1);
6724 n = read32 (ip + 2);
6725 cmethod = mini_get_method (method, n, NULL, generic_context);
6728 mono_class_init (cmethod->klass);
6730 if (mono_use_security_manager) {
6731 check_linkdemand (cfg, method, cmethod, bblock, ip);
6734 handle_loaded_temps (cfg, bblock, stack_start, sp);
6736 NEW_METHODCONST (cfg, argconst, cmethod);
6737 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
6738 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
6740 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
6741 NEW_TEMPLOAD (cfg, *sp, temp);
6745 inline_costs += 10 * num_calls++;
6748 case CEE_LDVIRTFTN: {
6754 n = read32 (ip + 2);
6755 cmethod = mini_get_method (method, n, NULL, generic_context);
6758 mono_class_init (cmethod->klass);
6760 if (mono_use_security_manager) {
6761 check_linkdemand (cfg, method, cmethod, bblock, ip);
6764 handle_loaded_temps (cfg, bblock, stack_start, sp);
6768 NEW_METHODCONST (cfg, args [1], cmethod);
6769 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
6770 NEW_TEMPLOAD (cfg, *sp, temp);
6774 inline_costs += 10 * num_calls++;
6778 CHECK_STACK_OVF (1);
6780 n = read16 (ip + 2);
6782 NEW_ARGLOAD (cfg, ins, n);
6788 CHECK_STACK_OVF (1);
6790 n = read16 (ip + 2);
6792 NEW_ARGLOADA (cfg, ins, n);
6800 handle_loaded_temps (cfg, bblock, stack_start, sp);
6802 n = read16 (ip + 2);
6804 NEW_ARGSTORE (cfg, ins, n, *sp);
6806 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
6808 if (ins->opcode == CEE_STOBJ) {
6809 NEW_ARGLOADA (cfg, ins, n);
6810 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6812 MONO_ADD_INS (bblock, ins);
6816 CHECK_STACK_OVF (1);
6818 n = read16 (ip + 2);
6820 NEW_LOCLOAD (cfg, ins, n);
6826 CHECK_STACK_OVF (1);
6828 n = read16 (ip + 2);
6830 NEW_LOCLOADA (cfg, ins, n);
6839 n = read16 (ip + 2);
6841 handle_loaded_temps (cfg, bblock, stack_start, sp);
6842 NEW_LOCSTORE (cfg, ins, n, *sp);
6843 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
6846 if (ins->opcode == CEE_STOBJ) {
6847 NEW_LOCLOADA (cfg, ins, n);
6848 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6850 MONO_ADD_INS (bblock, ins);
6857 if (sp != stack_start)
6859 if (cfg->method != method)
6861 * Inlining this into a loop in a parent could lead to
6862 * stack overflows which is different behavior than the
6863 * non-inlined case, thus disable inlining in this case.
6865 goto inline_failure;
6866 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
6867 ins->inst_left = *sp;
6869 ins->type = STACK_PTR;
6871 cfg->flags |= MONO_CFG_HAS_ALLOCA;
6872 if (header->init_locals)
6873 ins->flags |= MONO_INST_INIT;
6877 /* FIXME: set init flag if locals init is set in this method */
6879 case CEE_ENDFILTER: {
6880 MonoExceptionClause *clause, *nearest;
6881 int cc, nearest_num;
6885 if ((sp != stack_start) || (sp [0]->type != STACK_I4))
6887 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
6888 ins->inst_left = *sp;
6890 MONO_ADD_INS (bblock, ins);
6891 start_new_bblock = 1;
6896 for (cc = 0; cc < header->num_clauses; ++cc) {
6897 clause = &header->clauses [cc];
6898 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
6899 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
6900 (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
6906 if ((ip - header->code) != nearest->handler_offset)
6911 case CEE_UNALIGNED_:
6912 ins_flag |= MONO_INST_UNALIGNED;
6913 /* FIXME: record alignment? we can assume 1 for now */
6918 ins_flag |= MONO_INST_VOLATILE;
6922 ins_flag |= MONO_INST_TAILCALL;
6923 cfg->flags |= MONO_CFG_HAS_TAIL;
6924 /* Can't inline tail calls at this time */
6925 inline_costs += 100000;
6932 token = read32 (ip + 2);
6933 klass = mini_get_class (method, token, generic_context);
6936 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6937 MonoInst *store, *load;
6938 NEW_PCONST (cfg, load, NULL);
6939 load->cil_code = ip;
6940 load->type = STACK_OBJ;
6941 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6942 store->cil_code = ip;
6943 handle_loaded_temps (cfg, bblock, stack_start, sp);
6944 MONO_ADD_INS (bblock, store);
6945 store->inst_i0 = sp [0];
6946 store->inst_i1 = load;
6948 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
6953 case CEE_CONSTRAINED_:
6954 /* FIXME: implement */
6956 token = read32 (ip + 2);
6957 constrained_call = mono_class_get_full (image, token, generic_context);
6958 if (!constrained_call)
6964 MonoInst *iargs [3];
6967 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
6969 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
6970 copy->inst_left = sp [0];
6971 copy->inst_right = sp [1];
6972 copy->cil_code = ip;
6974 MONO_ADD_INS (bblock, copy);
6981 handle_loaded_temps (cfg, bblock, stack_start, sp);
6982 if (ip [1] == CEE_CPBLK) {
6983 MonoMethod *memcpy_method = get_memcpy_method ();
6984 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6986 MonoMethod *memset_method = get_memset_method ();
6987 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
6996 ins_flag |= MONO_INST_NOTYPECHECK;
6998 ins_flag |= MONO_INST_NORANGECHECK;
6999 /* we ignore the no-nullcheck for now since we
7000 * really do it explicitly only when doing callvirt->call
7006 int handler_offset = -1;
7008 for (i = 0; i < header->num_clauses; ++i) {
7009 MonoExceptionClause *clause = &header->clauses [i];
7010 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
7011 handler_offset = clause->handler_offset;
7014 bblock->flags |= BB_EXCEPTION_UNSAFE;
7016 g_assert (handler_offset != -1);
7018 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
7019 load->cil_code = ip;
7020 MONO_INST_NEW (cfg, ins, OP_RETHROW);
7021 ins->inst_left = load;
7023 MONO_ADD_INS (bblock, ins);
7025 link_bblock (cfg, bblock, end_bblock);
7026 start_new_bblock = 1;
7031 CHECK_STACK_OVF (1);
7033 token = read32 (ip + 2);
7034 /* FIXXME: handle generics. */
7035 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
7036 MonoType *type = mono_type_create_from_typespec (image, token);
7037 token = mono_type_size (type, &ialign);
7039 MonoClass *klass = mono_class_get_full (image, token, generic_context);
7042 mono_class_init (klass);
7043 token = mono_class_value_size (klass, &align);
7045 NEW_ICONST (cfg, ins, token);
7050 case CEE_REFANYTYPE:
7052 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
7054 ins->type = STACK_MP;
7055 ins->inst_left = *sp;
7056 ins->type = STACK_VTYPE;
7057 ins->klass = mono_defaults.typehandle_class;
7066 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
7071 g_error ("opcode 0x%02x not handled", *ip);
7074 if (start_new_bblock != 1)
7077 bblock->cil_length = ip - bblock->cil_code;
7078 bblock->next_bb = end_bblock;
7080 if (cfg->method == method && cfg->domainvar) {
7082 MonoInst *get_domain;
7084 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
7087 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
7088 call->signature = helper_sig_domain_get;
7089 call->inst.type = STACK_PTR;
7090 call->fptr = mono_domain_get;
7091 get_domain = (MonoInst*)call;
7094 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
7095 MONO_ADD_INS (init_localsbb, store);
7098 if (cfg->method == method && cfg->got_var)
7099 mono_emit_load_got_addr (cfg);
7101 if (header->init_locals) {
7103 for (i = 0; i < header->num_locals; ++i) {
7104 MonoType *ptype = header->locals [i];
7105 int t = ptype->type;
7106 if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
7107 t = ptype->data.klass->enum_basetype->type;
7109 NEW_PCONST (cfg, ins, NULL);
7110 NEW_LOCSTORE (cfg, store, i, ins);
7111 MONO_ADD_INS (init_localsbb, store);
7112 } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
7113 NEW_ICONST (cfg, ins, 0);
7114 NEW_LOCSTORE (cfg, store, i, ins);
7115 MONO_ADD_INS (init_localsbb, store);
7116 } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
7117 MONO_INST_NEW (cfg, ins, OP_I8CONST);
7118 ins->type = STACK_I8;
7120 NEW_LOCSTORE (cfg, store, i, ins);
7121 MONO_ADD_INS (init_localsbb, store);
7122 } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
7123 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7124 ins->type = STACK_R8;
7125 ins->inst_p0 = (void*)&r8_0;
7126 NEW_LOCSTORE (cfg, store, i, ins);
7127 MONO_ADD_INS (init_localsbb, store);
7128 } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
7129 ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
7130 NEW_LOCLOADA (cfg, ins, i);
7131 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
7133 NEW_PCONST (cfg, ins, NULL);
7134 NEW_LOCSTORE (cfg, store, i, ins);
7135 MONO_ADD_INS (init_localsbb, store);
7140 /* resolve backward branches in the middle of an existing basic block */
7141 for (tmp = bb_recheck; tmp; tmp = tmp->next) {
7143 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
7144 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
7145 if (tblock != start_bblock) {
7147 split_bblock (cfg, tblock, bblock);
7148 l = bblock->cil_code - header->code;
7149 bblock->cil_length = tblock->cil_length - l;
7150 tblock->cil_length = l;
7152 g_print ("recheck failed.\n");
7156 if (cfg->method == method) {
7158 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7159 bb->region = mono_find_block_region (cfg, bb->real_offset);
7161 mono_create_spvar_for_region (cfg, bb->region);
7162 if (cfg->verbose_level > 2)
7163 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
7166 g_hash_table_destroy (bbhash);
7169 g_slist_free (class_inits);
7170 dont_inline = g_list_remove (dont_inline, method);
7172 if (inline_costs < 0) {
7175 /* Method is too large */
7176 mname = mono_method_full_name (method, TRUE);
7177 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
7178 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
7183 return inline_costs;
7186 if (cfg->method != method)
7187 g_hash_table_destroy (bbhash);
7188 g_slist_free (class_inits);
7189 dont_inline = g_list_remove (dont_inline, method);
7193 if (cfg->method != method)
7194 g_hash_table_destroy (bbhash);
7195 g_slist_free (class_inits);
7196 dont_inline = g_list_remove (dont_inline, method);
7197 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
7201 if (cfg->method != method)
7202 g_hash_table_destroy (bbhash);
7203 g_slist_free (class_inits);
7204 dont_inline = g_list_remove (dont_inline, method);
7205 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
7206 cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n",
7207 mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
7212 mono_print_tree (MonoInst *tree) {
7218 arity = mono_burg_arity [tree->opcode];
7220 printf (" %s%s", arity?"(":"", mono_inst_name (tree->opcode));
7222 switch (tree->opcode) {
7224 printf ("[%d]", (int)tree->inst_c0);
7227 printf ("[%lld]", (long long)tree->inst_l);
7230 printf ("[%f]", *(double*)tree->inst_p0);
7233 printf ("[%f]", *(float*)tree->inst_p0);
7237 printf ("[%d]", (int)tree->inst_c0);
7240 if (tree->inst_offset < 0)
7241 printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
7243 printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
7246 printf ("[%s]", mono_arch_regname (tree->dreg));
7249 printf ("[%s]", tree->inst_newa_class->name);
7250 mono_print_tree (tree->inst_newa_len);
7261 case OP_VOIDCALLVIRT: {
7262 MonoCallInst *call = (MonoCallInst*)tree;
7264 printf ("[%s]", call->method->name);
7265 else if (call->fptr) {
7266 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
7268 printf ("[%s]", info->name);
7274 printf ("[%d (", (int)tree->inst_c0);
7275 for (i = 0; i < tree->inst_phi_args [0]; i++) {
7278 printf ("%d", tree->inst_phi_args [i + 1]);
7289 case OP_LOAD_MEMBASE:
7290 case OP_LOADI4_MEMBASE:
7291 case OP_LOADU4_MEMBASE:
7292 case OP_LOADU1_MEMBASE:
7293 case OP_LOADI1_MEMBASE:
7294 case OP_LOADU2_MEMBASE:
7295 case OP_LOADI2_MEMBASE:
7296 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
7299 case OP_CALL_HANDLER:
7300 printf ("[B%d]", tree->inst_target_bb->block_num);
7310 case OP_VOIDCALL_REG:
7311 mono_print_tree (tree->inst_left);
7323 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
7324 mono_print_tree (tree->inst_left);
7327 if (!mono_arch_print_tree(tree, arity)) {
7329 mono_print_tree (tree->inst_left);
7331 mono_print_tree (tree->inst_right);
7342 mono_print_tree_nl (MonoInst *tree)
7344 mono_print_tree (tree);
7349 create_helper_signature (void)
7351 helper_sig_domain_get = mono_create_icall_signature ("ptr");
7352 helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
7356 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
7359 MonoMethod *wrapper;
7361 if (callinfo->wrapper) {
7362 return callinfo->wrapper;
7365 if (callinfo->trampoline)
7366 return callinfo->trampoline;
7368 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
7369 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
7372 callinfo->trampoline = mono_create_ftnptr (mono_get_root_domain (), mono_create_jit_trampoline_in_domain (mono_get_root_domain (), wrapper));
7373 mono_register_jit_icall_wrapper (callinfo, callinfo->trampoline);
7375 return callinfo->trampoline;
7379 mono_init_trampolines (void)
7381 mono_trampoline_code [MONO_TRAMPOLINE_GENERIC] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC);
7382 mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_JUMP);
7383 mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
7384 #ifdef MONO_ARCH_HAVE_PIC_AOT
7385 mono_trampoline_code [MONO_TRAMPOLINE_AOT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT);
7386 mono_trampoline_code [MONO_TRAMPOLINE_AOT_PLT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT_PLT);
7388 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
7389 mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
7394 mono_init_exceptions (void)
7396 #ifndef CUSTOM_EXCEPTION_HANDLING
7397 mono_arch_get_restore_context ();
7398 mono_arch_get_call_filter ();
7399 mono_arch_get_throw_exception ();
7400 mono_arch_get_rethrow_exception ();
7405 mono_get_trampoline_code (MonoTrampolineType tramp_type)
7407 return mono_trampoline_code [tramp_type];
7411 mono_create_class_init_trampoline (MonoVTable *vtable)
7415 /* previously created trampoline code */
7416 mono_domain_lock (vtable->domain);
7418 g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
7420 mono_domain_unlock (vtable->domain);
7424 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7425 code = mono_arch_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, vtable->domain, NULL);
7427 code = mono_arch_create_class_init_trampoline (vtable);
7430 ptr = mono_create_ftnptr (vtable->domain, code);
7432 /* store trampoline address */
7433 mono_domain_lock (vtable->domain);
7434 g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
7436 mono_domain_unlock (vtable->domain);
7439 if (!class_init_hash_addr)
7440 class_init_hash_addr = g_hash_table_new (NULL, NULL);
7441 g_hash_table_insert (class_init_hash_addr, ptr, vtable);
7448 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method,
7449 gboolean add_sync_wrapper)
7453 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7457 if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
7458 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
7460 code = mono_jit_find_compiled_method (domain, method);
7464 mono_domain_lock (domain);
7465 code = g_hash_table_lookup (domain->jump_trampoline_hash, method);
7466 mono_domain_unlock (domain);
7470 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7471 code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
7473 mono_domain_lock (domain);
7474 ji = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
7475 mono_domain_unlock (domain);
7476 ji->code_start = code;
7477 ji->code_size = code_size;
7478 ji->method = method;
7480 ji = mono_arch_create_jump_trampoline (method);
7484 * mono_delegate_ctor needs to find the method metadata from the
7485 * trampoline address, so we save it here.
7488 mono_jit_info_table_add (domain, ji);
7490 mono_domain_lock (domain);
7491 g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
7492 mono_domain_unlock (domain);
7494 return ji->code_start;
7498 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
7502 mono_domain_lock (domain);
7503 tramp = g_hash_table_lookup (domain->jit_trampoline_hash, method);
7504 mono_domain_unlock (domain);
7508 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
7509 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
7511 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7512 tramp = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC, domain, NULL);
7514 tramp = mono_arch_create_jit_trampoline (method);
7517 mono_domain_lock (domain);
7518 g_hash_table_insert (domain->jit_trampoline_hash, method, tramp);
7519 mono_domain_unlock (domain);
7521 mono_jit_stats.method_trampolines++;
7527 mono_create_jit_trampoline (MonoMethod *method)
7529 return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
7532 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
7534 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
7538 MonoDomain *domain = mono_domain_get ();
7539 guint8 *buf, *start;
7541 mono_domain_lock (domain);
7542 buf = start = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
7543 mono_domain_unlock (domain);
7545 *(gpointer*)(gpointer)buf = image;
7546 buf += sizeof (gpointer);
7547 *(guint32*)(gpointer)buf = token;
7549 tramp = mono_arch_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
7551 mono_jit_stats.method_trampolines++;
7558 mono_create_delegate_trampoline (MonoMethod *method, gpointer addr)
7560 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
7563 MonoDomain *domain = mono_domain_get ();
7566 code = mono_jit_find_compiled_method (domain, method);
7571 * FIXME: We should return a function descriptor here but it is not stored
7572 * anywhere so it would be leaked.
7576 mono_domain_lock (domain);
7577 ptr = g_hash_table_lookup (domain->delegate_trampoline_hash, method);
7578 mono_domain_unlock (domain);
7582 code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_DELEGATE, domain, &code_size);
7584 ptr = mono_create_ftnptr (domain, code);
7586 /* store trampoline address */
7587 mono_domain_lock (domain);
7588 g_hash_table_insert (domain->delegate_trampoline_hash,
7590 mono_domain_unlock (domain);
7599 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
7604 if (class_init_hash_addr)
7605 res = g_hash_table_lookup (class_init_hash_addr, addr);
7613 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
7615 if (!domain->dynamic_code_hash)
7616 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
7617 g_hash_table_insert (domain->dynamic_code_hash, method, ji);
7620 static MonoJitDynamicMethodInfo*
7621 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
7623 MonoJitDynamicMethodInfo *res;
7625 if (domain->dynamic_code_hash)
7626 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
7639 * mono_allocate_stack_slots_full:
7641 * Allocate stack slots for all non register allocated variables using a
7642 * linear scan algorithm.
7643 * Returns: an array of stack offsets which the caller should free.
7644 * STACK_SIZE is set to the amount of stack space needed.
7645 * STACK_ALIGN is set to the alignment needed by the locals area.
7648 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
7650 int i, slot, offset, size;
7655 GList *vars = NULL, *l;
7656 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
7660 scalar_stack_slots = g_new0 (StackSlotInfo, MONO_TYPE_PINNED);
7661 vtype_stack_slots = g_new0 (StackSlotInfo, 256);
7664 offsets = g_new (gint32, m->num_varinfo);
7665 for (i = 0; i < m->num_varinfo; ++i)
7668 for (i = m->locals_start; i < m->num_varinfo; i++) {
7669 inst = m->varinfo [i];
7670 vmv = MONO_VARINFO (m, i);
7672 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
7675 vars = g_list_prepend (vars, vmv);
7678 vars = mono_varlist_sort (m, vars, 0);
7681 for (l = vars; l; l = l->next) {
7683 inst = m->varinfo [vmv->idx];
7685 /* inst->unused indicates native sized value types, this is used by the
7686 * pinvoke wrappers when they call functions returning structures */
7687 if (inst->unused && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
7688 size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
7692 size = mono_type_size (inst->inst_vtype, &ialign);
7696 t = mono_type_get_underlying_type (inst->inst_vtype);
7698 case MONO_TYPE_GENERICINST:
7699 if (!mono_type_generic_inst_is_valuetype (t)) {
7700 slot_info = &scalar_stack_slots [t->type];
7704 case MONO_TYPE_VALUETYPE:
7705 for (i = 0; i < nvtypes; ++i)
7706 if (t->data.klass == vtype_stack_slots [i].vtype)
7709 slot_info = &vtype_stack_slots [i];
7711 g_assert (nvtypes < 256);
7712 vtype_stack_slots [nvtypes].vtype = t->data.klass;
7713 slot_info = &vtype_stack_slots [nvtypes];
7718 slot_info = &scalar_stack_slots [t->type];
7722 if (m->comp_done & MONO_COMP_LIVENESS) {
7723 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
7725 /* expire old intervals in active */
7726 while (slot_info->active) {
7727 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
7729 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
7732 //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);
7734 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
7735 slot_info->slots = g_list_prepend (slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
7739 * This also handles the case when the variable is used in an
7740 * exception region, as liveness info is not computed there.
7743 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
7746 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
7747 if (slot_info->slots) {
7748 slot = GPOINTER_TO_INT (slot_info->slots->data);
7750 slot_info->slots = g_list_delete_link (slot_info->slots, slot_info->slots);
7753 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
7758 static int count = 0;
7762 if (count == atoi (getenv ("COUNT")))
7763 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
7764 if (count > atoi (getenv ("COUNT")))
7767 mono_print_tree_nl (inst);
7771 if (slot == 0xffffff) {
7773 * Allways allocate valuetypes to sizeof (gpointer) to allow more
7774 * efficient copying (and to work around the fact that OP_MEMCPY
7775 * and OP_MEMSET ignores alignment).
7777 if (MONO_TYPE_ISSTRUCT (t))
7778 align = sizeof (gpointer);
7782 offset += align - 1;
7783 offset &= ~(align - 1);
7787 offset += align - 1;
7788 offset &= ~(align - 1);
7793 if (*stack_align == 0)
7794 *stack_align = align;
7797 offsets [vmv->idx] = slot;
7800 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
7801 g_list_free (scalar_stack_slots [i].active);
7802 g_list_free (scalar_stack_slots [i].slots);
7804 for (i = 0; i < nvtypes; ++i) {
7805 g_list_free (vtype_stack_slots [i].active);
7806 g_list_free (vtype_stack_slots [i].slots);
7808 g_free (scalar_stack_slots);
7809 g_free (vtype_stack_slots);
7811 *stack_size = offset;
7816 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
7818 return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
7822 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
7824 MonoJitICallInfo *info;
7825 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
7827 if (!emul_opcode_map)
7828 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
7830 g_assert (!sig->hasthis);
7831 g_assert (sig->param_count < 3);
7833 info = mono_register_jit_icall (func, name, sig, no_throw);
7835 emul_opcode_map [opcode] = info;
7839 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
7841 MonoMethodSignature *sig;
7844 sig = mono_create_icall_signature (sigstr);
7848 mono_register_jit_icall (func, name, sig, save);
7852 decompose_foreach (MonoInst *tree, gpointer data)
7854 static MonoJitICallInfo *newarr_info = NULL;
7855 static MonoJitICallInfo *newarr_specific_info = NULL;
7856 MonoJitICallInfo *info;
7859 switch (tree->opcode) {
7861 MonoCompile *cfg = data;
7862 MonoInst *iargs [3];
7865 newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
7866 g_assert (newarr_info);
7867 newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
7868 g_assert (newarr_specific_info);
7871 if (cfg->opt & MONO_OPT_SHARED) {
7872 NEW_DOMAINCONST (cfg, iargs [0]);
7873 NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
7874 iargs [2] = tree->inst_newa_len;
7879 MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
7881 NEW_VTABLECONST (cfg, iargs [0], vtable);
7882 iargs [1] = tree->inst_newa_len;
7884 info = newarr_specific_info;
7887 mono_emulate_opcode (cfg, tree, iargs, info);
7889 /* Need to decompose arguments after the the opcode is decomposed */
7890 for (i = 0; i < info->sig->param_count; ++i)
7891 dec_foreach (iargs [i], cfg);
7901 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
7903 switch (mono_burg_arity [tree->opcode]) {
7906 mono_inst_foreach (tree->inst_left, func, data);
7909 mono_inst_foreach (tree->inst_left, func, data);
7910 mono_inst_foreach (tree->inst_right, func, data);
7913 g_assert_not_reached ();
7920 mono_print_bb_code (MonoBasicBlock *bb) {
7922 MonoInst *c = bb->code;
7924 mono_print_tree (c);
7932 print_dfn (MonoCompile *cfg) {
7937 g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
7939 for (i = 0; i < cfg->num_bblocks; ++i) {
7940 bb = cfg->bblocks [i];
7941 /*if (bb->cil_code) {
7942 char* code1, *code2;
7943 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
7944 if (bb->last_ins->cil_code)
7945 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
7947 code2 = g_strdup ("");
7949 code1 [strlen (code1) - 1] = 0;
7950 code = g_strdup_printf ("%s -> %s", code1, code2);
7954 code = g_strdup ("\n");
7955 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
7957 MonoInst *c = bb->code;
7959 mono_print_tree (c);
7967 g_print ("\tprev:");
7968 for (j = 0; j < bb->in_count; ++j) {
7969 g_print (" BB%d", bb->in_bb [j]->block_num);
7971 g_print ("\t\tsucc:");
7972 for (j = 0; j < bb->out_count; ++j) {
7973 g_print (" BB%d", bb->out_bb [j]->block_num);
7975 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
7978 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
7981 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
7983 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
7991 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
7995 g_assert (bb->code);
7996 bb->last_ins->next = inst;
7997 bb->last_ins = inst;
7999 bb->last_ins = bb->code = inst;
8004 mono_destroy_compile (MonoCompile *cfg)
8006 //mono_mempool_stats (cfg->mempool);
8007 g_hash_table_destroy (cfg->bb_hash);
8008 mono_free_loop_info (cfg);
8010 mono_regstate_free (cfg->rs);
8012 g_hash_table_destroy (cfg->spvars);
8014 g_hash_table_destroy (cfg->exvars);
8015 mono_mempool_destroy (cfg->mempool);
8016 g_list_free (cfg->ldstr_list);
8018 g_free (cfg->varinfo);
8020 g_free (cfg->exception_message);
8024 #ifdef HAVE_KW_THREAD
8025 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
8029 mono_get_jit_tls_key (void)
8031 return mono_jit_tls_id;
8035 mono_get_lmf_tls_offset (void)
8038 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
8043 mono_get_lmf_addr (void)
8045 #ifdef HAVE_KW_THREAD
8046 return mono_lmf_addr;
8048 MonoJitTlsData *jit_tls;
8050 if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
8051 return &jit_tls->lmf;
8053 g_assert_not_reached ();
8058 /* Called by native->managed wrappers */
8060 mono_jit_thread_attach (MonoDomain *domain)
8062 #ifdef HAVE_KW_THREAD
8063 if (!mono_lmf_addr) {
8064 mono_thread_attach (domain);
8067 if (!TlsGetValue (mono_jit_tls_id))
8068 mono_thread_attach (domain);
8073 * mono_thread_abort:
8074 * @obj: exception object
8076 * abort the thread, print exception information and stack trace
8079 mono_thread_abort (MonoObject *obj)
8081 /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
8083 /* handle_remove should be eventually called for this thread, too
8086 mono_thread_exit ();
8090 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
8092 MonoJitTlsData *jit_tls;
8095 jit_tls = TlsGetValue (mono_jit_tls_id);
8099 jit_tls = g_new0 (MonoJitTlsData, 1);
8101 TlsSetValue (mono_jit_tls_id, jit_tls);
8103 jit_tls->abort_func = abort_func;
8104 jit_tls->end_of_stack = stack_start;
8106 lmf = g_new0 (MonoLMF, 1);
8109 jit_tls->lmf = jit_tls->first_lmf = lmf;
8111 #ifdef HAVE_KW_THREAD
8112 mono_lmf_addr = &jit_tls->lmf;
8115 mono_arch_setup_jit_tls_data (jit_tls);
8117 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8118 mono_setup_altstack (jit_tls);
8125 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
8128 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
8129 thread = mono_thread_current ();
8131 thread->jit_data = jit_tls;
8134 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
8137 mono_thread_abort_dummy (MonoObject *obj)
8139 if (mono_thread_attach_aborted_cb)
8140 mono_thread_attach_aborted_cb (obj);
8142 mono_thread_abort (obj);
8146 mono_thread_attach_cb (gsize tid, gpointer stack_start)
8149 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
8150 thread = mono_thread_current ();
8152 thread->jit_data = jit_tls;
8153 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
8154 setup_stat_profiler ();
8158 mini_thread_cleanup (MonoThread *thread)
8160 MonoJitTlsData *jit_tls = thread->jit_data;
8163 mono_arch_free_jit_tls_data (jit_tls);
8165 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8166 mono_free_altstack (jit_tls);
8168 g_free (jit_tls->first_lmf);
8170 thread->jit_data = NULL;
8171 TlsSetValue (mono_jit_tls_id, NULL);
8176 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
8178 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
8182 ji->data.target = target;
8183 ji->next = cfg->patch_info;
8185 cfg->patch_info = ji;
8189 mono_remove_patch_info (MonoCompile *cfg, int ip)
8191 MonoJumpInfo **ji = &cfg->patch_info;
8194 if ((*ji)->ip.i == ip)
8197 ji = &((*ji)->next);
8202 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
8204 unsigned char *ip = patch_info->ip.i + code;
8205 gconstpointer target = NULL;
8207 switch (patch_info->type) {
8208 case MONO_PATCH_INFO_BB:
8209 target = patch_info->data.bb->native_offset + code;
8211 case MONO_PATCH_INFO_ABS:
8212 target = patch_info->data.target;
8214 case MONO_PATCH_INFO_LABEL:
8215 target = patch_info->data.inst->inst_c0 + code;
8217 case MONO_PATCH_INFO_IP:
8220 case MONO_PATCH_INFO_METHOD_REL:
8221 target = code + patch_info->data.offset;
8223 case MONO_PATCH_INFO_INTERNAL_METHOD: {
8224 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
8226 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
8227 g_assert_not_reached ();
8229 target = mono_icall_get_wrapper (mi);
8232 case MONO_PATCH_INFO_METHOD_JUMP: {
8235 /* get the trampoline to the method from the domain */
8236 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
8237 if (!domain->jump_target_hash)
8238 domain->jump_target_hash = g_hash_table_new (NULL, NULL);
8239 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
8240 list = g_slist_prepend (list, ip);
8241 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
8244 case MONO_PATCH_INFO_METHOD:
8245 if (patch_info->data.method == method) {
8248 /* get the trampoline to the method from the domain */
8249 target = mono_create_jit_trampoline (patch_info->data.method);
8251 case MONO_PATCH_INFO_SWITCH: {
8252 gpointer *jump_table;
8255 if (method && method->dynamic) {
8256 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
8258 mono_domain_lock (domain);
8259 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
8260 mono_domain_unlock (domain);
8263 for (i = 0; i < patch_info->data.table->table_size; i++) {
8264 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
8266 target = jump_table;
8269 case MONO_PATCH_INFO_METHODCONST:
8270 case MONO_PATCH_INFO_CLASS:
8271 case MONO_PATCH_INFO_IMAGE:
8272 case MONO_PATCH_INFO_FIELD:
8273 target = patch_info->data.target;
8275 case MONO_PATCH_INFO_IID:
8276 mono_class_init (patch_info->data.klass);
8277 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
8279 case MONO_PATCH_INFO_ADJUSTED_IID:
8280 mono_class_init (patch_info->data.klass);
8281 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
8283 case MONO_PATCH_INFO_VTABLE:
8284 target = mono_class_vtable (domain, patch_info->data.klass);
8286 case MONO_PATCH_INFO_CLASS_INIT:
8287 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
8289 case MONO_PATCH_INFO_SFLDA: {
8290 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
8291 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
8292 /* Done by the generated code */
8296 mono_runtime_class_init (vtable);
8298 target = (char*)vtable->data + patch_info->data.field->offset;
8301 case MONO_PATCH_INFO_R4:
8302 case MONO_PATCH_INFO_R8:
8303 target = patch_info->data.target;
8305 case MONO_PATCH_INFO_EXC_NAME:
8306 target = patch_info->data.name;
8308 case MONO_PATCH_INFO_LDSTR:
8310 mono_ldstr (domain, patch_info->data.token->image,
8311 mono_metadata_token_index (patch_info->data.token->token));
8313 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
8315 MonoClass *handle_class;
8317 handle = mono_ldtoken (patch_info->data.token->image,
8318 patch_info->data.token->token, &handle_class, NULL);
8319 mono_class_init (handle_class);
8320 mono_class_init (mono_class_from_mono_type (handle));
8323 mono_type_get_object (domain, handle);
8326 case MONO_PATCH_INFO_LDTOKEN: {
8328 MonoClass *handle_class;
8330 handle = mono_ldtoken (patch_info->data.token->image,
8331 patch_info->data.token->token, &handle_class, NULL);
8332 mono_class_init (handle_class);
8337 case MONO_PATCH_INFO_DECLSEC:
8338 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
8340 case MONO_PATCH_INFO_BB_OVF:
8341 case MONO_PATCH_INFO_EXC_OVF:
8342 case MONO_PATCH_INFO_GOT_OFFSET:
8343 case MONO_PATCH_INFO_NONE:
8346 g_assert_not_reached ();
8349 return (gpointer)target;
8353 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
8354 MonoJitICallInfo *info;
8356 decompose_foreach (tree, cfg);
8358 switch (mono_burg_arity [tree->opcode]) {
8361 dec_foreach (tree->inst_left, cfg);
8363 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
8364 MonoInst *iargs [2];
8366 iargs [0] = tree->inst_left;
8368 mono_emulate_opcode (cfg, tree, iargs, info);
8374 #ifdef MONO_ARCH_BIGMUL_INTRINS
8375 if (tree->opcode == OP_LMUL
8376 && (cfg->opt & MONO_OPT_INTRINS)
8377 && (tree->inst_left->opcode == CEE_CONV_I8
8378 || tree->inst_left->opcode == CEE_CONV_U8)
8379 && tree->inst_left->inst_left->type == STACK_I4
8380 && (tree->inst_right->opcode == CEE_CONV_I8
8381 || tree->inst_right->opcode == CEE_CONV_U8)
8382 && tree->inst_right->inst_left->type == STACK_I4
8383 && tree->inst_left->opcode == tree->inst_right->opcode) {
8384 tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
8385 tree->inst_left = tree->inst_left->inst_left;
8386 tree->inst_right = tree->inst_right->inst_left;
8387 dec_foreach (tree, cfg);
8390 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
8391 MonoInst *iargs [2];
8393 iargs [0] = tree->inst_i0;
8394 iargs [1] = tree->inst_i1;
8396 mono_emulate_opcode (cfg, tree, iargs, info);
8398 dec_foreach (iargs [0], cfg);
8399 dec_foreach (iargs [1], cfg);
8402 dec_foreach (tree->inst_left, cfg);
8403 dec_foreach (tree->inst_right, cfg);
8407 g_assert_not_reached ();
8412 decompose_pass (MonoCompile *cfg) {
8415 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8418 cfg->prev_ins = NULL;
8419 for (tree = cfg->cbb->code; tree; tree = tree->next) {
8420 dec_foreach (tree, cfg);
8421 cfg->prev_ins = tree;
8427 nullify_basic_block (MonoBasicBlock *bb)
8434 bb->code = bb->last_ins = NULL;
8435 bb->cil_code = NULL;
8439 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8443 for (i = 0; i < bb->out_count; i++) {
8444 MonoBasicBlock *ob = bb->out_bb [i];
8447 if (bb->out_count > 1) {
8448 bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
8452 bb->out_bb [i] = repl;
8459 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8463 for (i = 0; i < bb->in_count; i++) {
8464 MonoBasicBlock *ib = bb->in_bb [i];
8467 if (bb->in_count > 1) {
8468 bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
8472 bb->in_bb [i] = repl;
8479 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
8482 for (inst = bb->code; inst != NULL; inst = inst->next) {
8483 if (inst->opcode == OP_CALL_HANDLER) {
8484 if (inst->inst_target_bb == orig) {
8485 inst->inst_target_bb = repl;
8489 if (bb->last_ins != NULL) {
8490 switch (bb->last_ins->opcode) {
8492 if (bb->last_ins->inst_target_bb == orig) {
8493 bb->last_ins->inst_target_bb = repl;
8498 int n = GPOINTER_TO_INT (bb->last_ins->klass);
8499 for (i = 0; i < n; i++ ) {
8500 if (bb->last_ins->inst_many_bb [i] == orig) {
8501 bb->last_ins->inst_many_bb [i] = repl;
8516 if (bb->last_ins->inst_true_bb == orig) {
8517 bb->last_ins->inst_true_bb = repl;
8519 if (bb->last_ins->inst_false_bb == orig) {
8520 bb->last_ins->inst_false_bb = repl;
8530 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8534 for (i = 0; i < bb->out_count; i++) {
8535 MonoBasicBlock *ob = bb->out_bb [i];
8536 for (j = 0; j < ob->in_count; j++) {
8537 if (ob->in_bb [j] == orig) {
8538 ob->in_bb [j] = repl;
8546 * Check if a bb is useless (is just made of NOPs and ends with an
8547 * unconditional branch, or nothing).
8548 * If it is so, unlink it from the CFG and nullify it, and return TRUE.
8549 * Otherwise, return FALSE;
8552 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
8553 MonoBasicBlock *target_bb = NULL;
8556 /* Do not touch handlers */
8557 if (bb->region != -1) {
8558 bb->not_useless = TRUE;
8562 for (inst = bb->code; inst != NULL; inst = inst->next) {
8563 switch (inst->opcode) {
8567 target_bb = inst->inst_target_bb;
8570 bb->not_useless = TRUE;
8575 if (target_bb == NULL) {
8576 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
8577 target_bb = bb->next_bb;
8579 /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
8584 /* Do not touch BBs following a switch (they are the "default" branch) */
8585 if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == CEE_SWITCH)) {
8589 /* Do not touch BBs following the entry BB and jumping to something that is not */
8590 /* thiry "next" bb (the entry BB cannot contain the branch) */
8591 if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
8595 /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
8596 if ((target_bb != NULL) && (target_bb != bb)) {
8599 if (cfg->verbose_level > 1) {
8600 printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
8603 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
8604 while (bb->in_count) {
8605 MonoBasicBlock *in_bb = bb->in_bb [0];
8606 mono_unlink_bblock (cfg, in_bb, bb);
8607 link_bblock (cfg, in_bb, target_bb);
8608 replace_out_block_in_code (in_bb, bb, target_bb);
8611 mono_unlink_bblock (cfg, bb, target_bb);
8613 if ((previous_bb != cfg->bb_entry) &&
8614 (previous_bb->region == bb->region) &&
8615 ((previous_bb->last_ins == NULL) ||
8616 ((previous_bb->last_ins->opcode != CEE_BR) &&
8617 (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
8618 (previous_bb->last_ins->opcode != CEE_SWITCH)))) {
8619 for (i = 0; i < previous_bb->out_count; i++) {
8620 if (previous_bb->out_bb [i] == target_bb) {
8622 MONO_INST_NEW (cfg, jump, CEE_BR);
8623 MONO_ADD_INS (previous_bb, jump);
8624 jump->cil_code = previous_bb->cil_code;
8625 jump->inst_target_bb = target_bb;
8631 previous_bb->next_bb = bb->next_bb;
8632 nullify_basic_block (bb);
8641 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn)
8643 bb->out_count = bbn->out_count;
8644 bb->out_bb = bbn->out_bb;
8646 replace_basic_block (bb, bbn, bb);
8650 bb->last_ins->next = bbn->code;
8651 bb->last_ins = bbn->last_ins;
8654 bb->code = bbn->code;
8655 bb->last_ins = bbn->last_ins;
8657 bb->next_bb = bbn->next_bb;
8658 nullify_basic_block (bbn);
8662 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
8664 MonoBasicBlock *bbn, *next;
8668 /* Find the previous */
8669 for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
8672 bbn->next_bb = bb->next_bb;
8676 for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
8682 if (next && (!bb->last_ins || (bb->last_ins->opcode != OP_NOT_REACHED))) {
8685 MONO_INST_NEW (cfg, ins, CEE_BR);
8686 MONO_ADD_INS (bb, ins);
8687 link_bblock (cfg, bb, next);
8688 ins->inst_target_bb = next;
8692 /* checks that a and b represent the same instructions, conservatively,
8693 * it can return FALSE also for two trees that are equal.
8694 * FIXME: also make sure there are no side effects.
8697 same_trees (MonoInst *a, MonoInst *b)
8700 if (a->opcode != b->opcode)
8702 arity = mono_burg_arity [a->opcode];
8704 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
8706 return same_trees (a->inst_left, b->inst_left);
8707 } else if (arity == 2) {
8708 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
8709 } else if (arity == 0) {
8710 switch (a->opcode) {
8712 return a->inst_c0 == b->inst_c0;
8721 get_unsigned_condbranch (int opcode)
8724 case CEE_BLE: return CEE_BLE_UN;
8725 case CEE_BLT: return CEE_BLT_UN;
8726 case CEE_BGE: return CEE_BGE_UN;
8727 case CEE_BGT: return CEE_BGT_UN;
8729 g_assert_not_reached ();
8734 tree_is_unsigned (MonoInst* ins) {
8735 switch (ins->opcode) {
8737 return (int)ins->inst_c0 >= 0;
8738 /* array lengths are positive as are string sizes */
8745 case CEE_CONV_OVF_U1:
8746 case CEE_CONV_OVF_U2:
8747 case CEE_CONV_OVF_U4:
8758 /* check if an unsigned compare can be used instead of two signed compares
8759 * for (val < 0 || val > limit) conditionals.
8760 * Returns TRUE if the optimization has been applied.
8761 * Note that this can't be applied if the second arg is not positive...
8764 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb)
8766 MonoBasicBlock *truet, *falset;
8767 MonoInst *cmp_inst = bb->last_ins->inst_left;
8769 if (!cmp_inst->inst_right->inst_c0 == 0)
8771 truet = bb->last_ins->inst_true_bb;
8772 falset = bb->last_ins->inst_false_bb;
8773 if (falset->in_count != 1)
8775 condb = falset->last_ins;
8776 /* target bb must have one instruction */
8777 if (!condb || (condb != falset->code))
8779 if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
8780 || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
8781 && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
8782 if (!tree_is_unsigned (condb->inst_left->inst_right))
8784 condb->opcode = get_unsigned_condbranch (condb->opcode);
8785 /* change the original condbranch to just point to the new unsigned check */
8786 bb->last_ins->opcode = CEE_BR;
8787 bb->last_ins->inst_target_bb = falset;
8788 replace_out_block (bb, truet, NULL);
8789 replace_in_block (truet, bb, NULL);
8796 * Optimizes the branches on the Control Flow Graph
8800 optimize_branches (MonoCompile *cfg)
8802 int i, changed = FALSE;
8803 MonoBasicBlock *bb, *bbn;
8804 guint32 niterations;
8807 * Some crazy loops could cause the code below to go into an infinite
8808 * loop, see bug #53003 for an example. To prevent this, we put an upper
8809 * bound on the number of iterations.
8811 if (cfg->num_bblocks > 1000)
8812 niterations = cfg->num_bblocks * 2;
8817 MonoBasicBlock *previous_bb;
8821 /* we skip the entry block (exit is handled specially instead ) */
8822 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
8824 /* dont touch code inside exception clauses */
8825 if (bb->region != -1)
8828 if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
8833 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
8834 if (cfg->verbose_level > 2)
8835 g_print ("nullify block triggered %d\n", bbn->block_num);
8837 bb->next_bb = bbn->next_bb;
8839 for (i = 0; i < bbn->out_count; i++)
8840 replace_in_block (bbn->out_bb [i], bbn, NULL);
8842 nullify_basic_block (bbn);
8846 if (bb->out_count == 1) {
8847 bbn = bb->out_bb [0];
8849 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
8850 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
8852 MONO_INST_NEW (cfg, pop, CEE_POP);
8853 pop->inst_left = bb->last_ins->inst_left->inst_left;
8854 mono_add_ins_to_end (bb, pop);
8855 MONO_INST_NEW (cfg, pop, CEE_POP);
8856 pop->inst_left = bb->last_ins->inst_left->inst_right;
8857 mono_add_ins_to_end (bb, pop);
8858 bb->last_ins->opcode = CEE_BR;
8859 bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
8861 if (cfg->verbose_level > 2)
8862 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
8865 if (bb->region == bbn->region && bb->next_bb == bbn) {
8866 /* the block are in sequence anyway ... */
8868 /* branches to the following block can be removed */
8869 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
8870 bb->last_ins->opcode = CEE_NOP;
8872 if (cfg->verbose_level > 2)
8873 g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
8876 if (bbn->in_count == 1) {
8878 if (bbn != cfg->bb_exit) {
8879 if (cfg->verbose_level > 2)
8880 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
8881 merge_basic_blocks (bb, bbn);
8886 //mono_print_bb_code (bb);
8890 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
8891 if (cfg->verbose_level > 2) {
8892 g_print ("nullify block triggered %d\n", bbn->block_num);
8894 bb->next_bb = bbn->next_bb;
8896 for (i = 0; i < bbn->out_count; i++)
8897 replace_in_block (bbn->out_bb [i], bbn, NULL);
8899 nullify_basic_block (bbn);
8904 if (bb->out_count == 1) {
8905 bbn = bb->out_bb [0];
8907 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
8908 bbn = bb->last_ins->inst_target_bb;
8909 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8910 bbn->code->inst_target_bb->region == bb->region) {
8912 if (cfg->verbose_level > 2)
8913 g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name,
8914 bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num);
8916 replace_in_block (bbn, bb, NULL);
8917 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
8918 link_bblock (cfg, bb, bbn->code->inst_target_bb);
8919 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
8924 } else if (bb->out_count == 2) {
8925 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
8926 int branch_result = mono_eval_cond_branch (bb->last_ins);
8927 MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
8928 if (branch_result == BRANCH_TAKEN) {
8929 taken_branch_target = bb->last_ins->inst_true_bb;
8930 untaken_branch_target = bb->last_ins->inst_false_bb;
8931 } else if (branch_result == BRANCH_NOT_TAKEN) {
8932 taken_branch_target = bb->last_ins->inst_false_bb;
8933 untaken_branch_target = bb->last_ins->inst_true_bb;
8935 if (taken_branch_target) {
8936 /* if mono_eval_cond_branch () is ever taken to handle
8937 * non-constant values to compare, issue a pop here.
8939 bb->last_ins->opcode = CEE_BR;
8940 bb->last_ins->inst_target_bb = taken_branch_target;
8941 mono_unlink_bblock (cfg, bb, untaken_branch_target);
8945 bbn = bb->last_ins->inst_true_bb;
8946 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8947 bbn->code->inst_target_bb->region == bb->region) {
8948 if (cfg->verbose_level > 2)
8949 g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n",
8950 bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num,
8954 * Unlink, then relink bblocks to avoid various
8955 * tricky situations when the two targets of the branch
8956 * are equal, or will become equal after the change.
8958 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
8959 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
8961 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
8963 link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
8964 link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
8970 bbn = bb->last_ins->inst_false_bb;
8971 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8972 bbn->code->inst_target_bb->region == bb->region) {
8973 if (cfg->verbose_level > 2)
8974 g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n",
8975 bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num,
8978 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
8979 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
8981 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
8983 link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
8984 link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
8991 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
8992 if (bb->last_ins && bb->last_ins->opcode == CEE_BLT && bb->last_ins->inst_left->inst_right->opcode == OP_ICONST) {
8993 if (try_unsigned_compare (cfg, bb)) {
8994 /*g_print ("applied in bb %d (->%d) %s\n", bb->block_num, bb->last_ins->inst_target_bb->block_num, mono_method_full_name (cfg->method, TRUE));*/
9000 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
9001 if (bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region)) {
9002 /* Reverse the branch */
9003 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
9004 bbn = bb->last_ins->inst_false_bb;
9005 bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb;
9006 bb->last_ins->inst_true_bb = bbn;
9008 move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb);
9009 if (cfg->verbose_level > 2)
9010 g_print ("cbranch to throw block triggered %d.\n",
9016 } while (changed && (niterations > 0));
9021 mono_compile_create_vars (MonoCompile *cfg)
9023 MonoMethodSignature *sig;
9024 MonoMethodHeader *header;
9027 header = mono_method_get_header (cfg->method);
9029 sig = mono_method_signature (cfg->method);
9031 if (!MONO_TYPE_IS_VOID (sig->ret)) {
9032 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
9033 cfg->ret->opcode = OP_RETARG;
9034 cfg->ret->inst_vtype = sig->ret;
9035 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
9037 if (cfg->verbose_level > 2)
9038 g_print ("creating vars\n");
9041 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
9043 for (i = 0; i < sig->param_count; ++i) {
9044 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
9045 if (sig->params [i]->byref) {
9046 cfg->disable_ssa = TRUE;
9050 cfg->locals_start = cfg->num_varinfo;
9052 if (cfg->verbose_level > 2)
9053 g_print ("creating locals\n");
9054 for (i = 0; i < header->num_locals; ++i)
9055 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
9056 if (cfg->verbose_level > 2)
9057 g_print ("locals done\n");
9059 #ifdef MONO_ARCH_HAVE_CREATE_VARS
9060 mono_arch_create_vars (cfg);
9065 mono_print_code (MonoCompile *cfg)
9069 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9070 MonoInst *tree = bb->code;
9075 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
9077 for (; tree; tree = tree->next) {
9078 mono_print_tree (tree);
9083 bb->last_ins->next = NULL;
9087 extern const char * const mono_burg_rule_string [];
9090 emit_state (MonoCompile *cfg, MBState *state, int goal)
9093 int ern = mono_burg_rule (state, goal);
9094 const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
9097 //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
9101 // state->reg1 = state->reg2; /* chain rule */
9103 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
9106 state->reg1 = mono_regstate_next_int (cfg->rs);
9107 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
9110 state->reg1 = mono_regstate_next_int (cfg->rs);
9111 state->reg2 = mono_regstate_next_int (cfg->rs);
9114 state->reg1 = mono_regstate_next_float (cfg->rs);
9117 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
9119 * Enabling this might cause bugs to surface in the local register
9120 * allocators on some architectures like x86.
9122 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
9123 /* Do not optimize away reg-reg moves */
9124 if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
9125 state->right->reg1 = state->left->tree->dreg;
9134 mono_burg_kids (state, ern, kids);
9136 emit_state (cfg, kids [0], nts [0]);
9138 emit_state (cfg, kids [1], nts [1]);
9140 g_assert (!nts [3]);
9141 emit_state (cfg, kids [2], nts [2]);
9146 // g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
9147 if ((emit = mono_burg_func [ern]))
9148 emit (state, state->tree, cfg);
9151 #define DEBUG_SELECTION
9154 mini_select_instructions (MonoCompile *cfg)
9158 cfg->state_pool = mono_mempool_new ();
9159 cfg->rs = mono_regstate_new ();
9161 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9162 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
9163 bb->next_bb != bb->last_ins->inst_false_bb) {
9165 /* we are careful when inverting, since bugs like #59580
9166 * could show up when dealing with NaNs.
9168 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
9169 MonoBasicBlock *tmp = bb->last_ins->inst_true_bb;
9170 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
9171 bb->last_ins->inst_false_bb = tmp;
9173 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
9175 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
9176 inst->opcode = CEE_BR;
9177 inst->inst_target_bb = bb->last_ins->inst_false_bb;
9178 mono_bblock_add_inst (bb, inst);
9183 #ifdef DEBUG_SELECTION
9184 if (cfg->verbose_level >= 4) {
9185 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9186 MonoInst *tree = bb->code;
9187 g_print ("DUMP BLOCK %d:\n", bb->block_num);
9190 for (; tree; tree = tree->next) {
9191 mono_print_tree (tree);
9198 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9199 MonoInst *tree = bb->code, *next;
9205 bb->last_ins = NULL;
9208 mono_regstate_reset (cfg->rs);
9210 #ifdef DEBUG_SELECTION
9211 if (cfg->verbose_level >= 3)
9212 g_print ("LABEL BLOCK %d:\n", bb->block_num);
9214 for (; tree; tree = next) {
9216 #ifdef DEBUG_SELECTION
9217 if (cfg->verbose_level >= 3) {
9218 mono_print_tree (tree);
9223 if (!(mbstate = mono_burg_label (tree, cfg))) {
9224 g_warning ("unable to label tree %p", tree);
9225 mono_print_tree (tree);
9227 g_assert_not_reached ();
9229 emit_state (cfg, mbstate, MB_NTERM_stmt);
9231 bb->max_ireg = cfg->rs->next_vireg;
9232 bb->max_freg = cfg->rs->next_vfreg;
9235 bb->last_ins->next = NULL;
9237 mono_mempool_empty (cfg->state_pool);
9239 mono_mempool_destroy (cfg->state_pool);
9243 mono_codegen (MonoCompile *cfg)
9245 MonoJumpInfo *patch_info;
9247 int i, max_epilog_size;
9250 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9251 cfg->spill_count = 0;
9252 /* we reuse dfn here */
9253 /* bb->dfn = bb_count++; */
9254 mono_arch_local_regalloc (cfg, bb);
9257 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
9258 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
9260 code = mono_arch_emit_prolog (cfg);
9262 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
9263 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
9265 cfg->code_len = code - cfg->native_code;
9266 cfg->prolog_end = cfg->code_len;
9268 mono_debug_open_method (cfg);
9270 /* emit code all basic blocks */
9271 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9272 bb->native_offset = cfg->code_len;
9273 mono_arch_output_basic_block (cfg, bb);
9275 if (bb == cfg->bb_exit) {
9276 cfg->epilog_begin = cfg->code_len;
9278 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
9279 code = cfg->native_code + cfg->code_len;
9280 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
9281 cfg->code_len = code - cfg->native_code;
9284 mono_arch_emit_epilog (cfg);
9288 mono_arch_emit_exceptions (cfg);
9290 max_epilog_size = 0;
9292 code = cfg->native_code + cfg->code_len;
9294 /* we always allocate code in cfg->domain->code_mp to increase locality */
9295 cfg->code_size = cfg->code_len + max_epilog_size;
9296 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
9298 if (cfg->method->dynamic) {
9299 /* Allocate the code into a separate memory pool so it can be freed */
9300 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
9301 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
9302 mono_domain_lock (cfg->domain);
9303 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
9304 mono_domain_unlock (cfg->domain);
9306 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
9308 mono_domain_lock (cfg->domain);
9309 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
9310 mono_domain_unlock (cfg->domain);
9313 memcpy (code, cfg->native_code, cfg->code_len);
9314 g_free (cfg->native_code);
9315 cfg->native_code = code;
9316 code = cfg->native_code + cfg->code_len;
9318 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
9319 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
9320 switch (patch_info->type) {
9321 case MONO_PATCH_INFO_ABS: {
9322 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
9324 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
9325 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) &&
9326 strstr (cfg->method->name, info->name))
9328 * This is an icall wrapper, and this is a call to the
9333 /* for these array methods we currently register the same function pointer
9334 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
9335 * will return the incorrect one depending on the order they are registered.
9336 * See tests/test-arr.cs
9338 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
9339 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9340 patch_info->data.name = info->name;
9345 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
9347 patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
9348 patch_info->data.klass = vtable->klass;
9353 case MONO_PATCH_INFO_SWITCH: {
9355 if (cfg->method->dynamic) {
9356 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9358 mono_domain_lock (cfg->domain);
9359 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9360 mono_domain_unlock (cfg->domain);
9363 if (!cfg->compile_aot)
9364 /* In the aot case, the patch already points to the correct location */
9365 patch_info->ip.i = patch_info->ip.label->inst_c0;
9366 for (i = 0; i < patch_info->data.table->table_size; i++) {
9367 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
9369 patch_info->data.table->table = (MonoBasicBlock**)table;
9378 if (cfg->verbose_level > 0) {
9379 char* nm = mono_method_full_name (cfg->method, TRUE);
9380 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
9382 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
9386 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
9387 mono_arch_save_unwind_info (cfg);
9390 mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
9392 if (cfg->method->dynamic) {
9393 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
9395 mono_domain_lock (cfg->domain);
9396 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
9397 mono_domain_unlock (cfg->domain);
9400 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
9402 mono_debug_close_method (cfg);
9408 remove_critical_edges (MonoCompile *cfg) {
9410 MonoBasicBlock *previous_bb;
9412 if (cfg->verbose_level > 3) {
9413 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9415 printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
9416 for (i = 0; i < bb->in_count; i++) {
9417 printf (" %d", bb->in_bb [i]->block_num);
9420 for (i = 0; i < bb->out_count; i++) {
9421 printf (" %d", bb->out_bb [i]->block_num);
9424 if (bb->last_ins != NULL) {
9426 mono_print_tree (bb->last_ins);
9432 for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
9433 if (bb->in_count > 1) {
9435 for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
9436 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
9437 if (in_bb->out_count > 1) {
9438 MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
9439 new_bb->block_num = cfg->num_bblocks++;
9440 // new_bb->real_offset = bb->real_offset;
9441 new_bb->region = bb->region;
9443 /* Do not alter the CFG while altering the BB list */
9444 if (previous_bb->region == bb->region) {
9445 if (previous_bb != cfg->bb_entry) {
9446 /* If previous_bb "followed through" to bb, */
9447 /* keep it linked with a CEE_BR */
9448 if ((previous_bb->last_ins == NULL) ||
9449 ((previous_bb->last_ins->opcode != CEE_BR) &&
9450 (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
9451 (previous_bb->last_ins->opcode != CEE_SWITCH))) {
9453 /* Make sure previous_bb really falls through bb */
9454 for (i = 0; i < previous_bb->out_count; i++) {
9455 if (previous_bb->out_bb [i] == bb) {
9457 MONO_INST_NEW (cfg, jump, CEE_BR);
9458 MONO_ADD_INS (previous_bb, jump);
9459 jump->cil_code = previous_bb->cil_code;
9460 jump->inst_target_bb = bb;
9466 /* We cannot add any inst to the entry BB, so we must */
9467 /* put a new BB in the middle to hold the CEE_BR */
9469 MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
9470 new_bb_after_entry->block_num = cfg->num_bblocks++;
9471 // new_bb_after_entry->real_offset = bb->real_offset;
9472 new_bb_after_entry->region = bb->region;
9474 MONO_INST_NEW (cfg, jump, CEE_BR);
9475 MONO_ADD_INS (new_bb_after_entry, jump);
9476 jump->cil_code = bb->cil_code;
9477 jump->inst_target_bb = bb;
9479 previous_bb->next_bb = new_bb_after_entry;
9480 previous_bb = new_bb_after_entry;
9482 if (cfg->verbose_level > 2) {
9483 printf ("remove_critical_edges %s, added helper BB%d jumping to BB%d\n", mono_method_full_name (cfg->method, TRUE), new_bb_after_entry->block_num, bb->block_num);
9488 /* Insert new_bb in the BB list */
9489 previous_bb->next_bb = new_bb;
9490 new_bb->next_bb = bb;
9491 previous_bb = new_bb;
9493 /* Setup in_bb and out_bb */
9494 new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
9495 new_bb->in_bb [0] = in_bb;
9496 new_bb->in_count = 1;
9497 new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
9498 new_bb->out_bb [0] = bb;
9499 new_bb->out_count = 1;
9501 /* Relink in_bb and bb to (from) new_bb */
9502 replace_out_block (in_bb, bb, new_bb);
9503 replace_out_block_in_code (in_bb, bb, new_bb);
9504 replace_in_block (bb, in_bb, new_bb);
9506 if (cfg->verbose_level > 2) {
9507 printf ("remove_critical_edges %s, removed critical edge from BB%d to BB%d (added BB%d)\n", mono_method_full_name (cfg->method, TRUE), in_bb->block_num, bb->block_num, new_bb->block_num);
9514 if (cfg->verbose_level > 3) {
9515 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9517 printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
9518 for (i = 0; i < bb->in_count; i++) {
9519 printf (" %d", bb->in_bb [i]->block_num);
9522 for (i = 0; i < bb->out_count; i++) {
9523 printf (" %d", bb->out_bb [i]->block_num);
9526 if (bb->last_ins != NULL) {
9528 mono_print_tree (bb->last_ins);
9536 * mini_method_compile:
9537 * @method: the method to compile
9538 * @opts: the optimization flags to use
9539 * @domain: the domain where the method will be compiled in
9540 * @run_cctors: whether we should run type ctors if possible
9541 * @compile_aot: whether this is an AOT compilation
9542 * @parts: debug flag
9544 * Returns: a MonoCompile* pointer. Caller must check the exception_type
9545 * field in the returned struct to see if compilation succeded.
9548 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
9550 MonoMethodHeader *header = mono_method_get_header (method);
9554 int dfn = 0, i, code_size_ratio;
9555 gboolean deadce_has_run = FALSE;
9557 mono_jit_stats.methods_compiled++;
9558 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
9559 mono_profiler_method_jit (method);
9561 cfg = g_new0 (MonoCompile, 1);
9562 cfg->method = method;
9563 cfg->mempool = mono_mempool_new ();
9565 cfg->prof_options = mono_profiler_get_events ();
9566 cfg->run_cctors = run_cctors;
9567 cfg->bb_hash = g_hash_table_new (NULL, NULL);
9568 cfg->domain = domain;
9569 cfg->verbose_level = mini_verbose;
9570 cfg->compile_aot = compile_aot;
9572 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9573 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
9574 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9575 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
9579 ip = (guint8 *)header->code;
9581 cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
9582 cfg->aliasing_info = NULL;
9584 if (cfg->verbose_level > 2)
9585 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
9588 * create MonoInst* which represents arguments and local variables
9590 mono_compile_create_vars (cfg);
9592 if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
9593 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9594 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
9595 /* cfg contains the details of the failure, so let the caller cleanup */
9599 mono_jit_stats.basic_blocks += cfg->num_bblocks;
9600 mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
9602 if ((cfg->num_varinfo > 2000) && !mono_compile_aot) {
9604 * we disable some optimizations if there are too many variables
9605 * because JIT time may become too expensive. The actual number needs
9606 * to be tweaked and eventually the non-linear algorithms should be fixed.
9608 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
9609 cfg->disable_ssa = TRUE;
9612 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
9614 if (cfg->opt & MONO_OPT_BRANCH)
9615 optimize_branches (cfg);
9617 if (cfg->opt & MONO_OPT_SSAPRE) {
9618 remove_critical_edges (cfg);
9621 /* Depth-first ordering on basic blocks */
9622 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
9624 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
9625 if (cfg->num_bblocks != dfn + 1) {
9628 cfg->num_bblocks = dfn + 1;
9630 if (!header->clauses) {
9631 /* remove unreachable code, because the code in them may be
9632 * inconsistent (access to dead variables for example) */
9633 for (bb = cfg->bb_entry; bb;) {
9634 MonoBasicBlock *bbn = bb->next_bb;
9636 if (bbn && bbn->region == -1 && !bbn->dfn) {
9637 if (cfg->verbose_level > 1)
9638 g_print ("found unreachable code in BB%d\n", bbn->block_num);
9639 bb->next_bb = bbn->next_bb;
9640 nullify_basic_block (bbn);
9648 if (cfg->opt & MONO_OPT_LOOP) {
9649 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
9650 mono_compute_natural_loops (cfg);
9653 /* after method_to_ir */
9657 //#define DEBUGSSA "logic_run"
9658 #define DEBUGSSA_CLASS "Tests"
9661 if (!header->num_clauses && !cfg->disable_ssa) {
9662 mono_local_cprop (cfg);
9663 mono_ssa_compute (cfg);
9667 /* fixme: add all optimizations which requires SSA */
9668 if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
9669 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
9670 mono_local_cprop (cfg);
9671 mono_ssa_compute (cfg);
9673 if (cfg->verbose_level >= 2) {
9680 /* after SSA translation */
9684 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
9685 if (cfg->comp_done & MONO_COMP_SSA) {
9686 mono_ssa_cprop (cfg);
9688 mono_local_cprop (cfg);
9692 if (cfg->comp_done & MONO_COMP_SSA) {
9693 //mono_ssa_deadce (cfg);
9695 //mono_ssa_strength_reduction (cfg);
9697 if (cfg->opt & MONO_OPT_SSAPRE) {
9698 mono_perform_ssapre (cfg);
9699 //mono_local_cprop (cfg);
9702 if (cfg->opt & MONO_OPT_DEADCE) {
9703 mono_ssa_deadce (cfg);
9704 deadce_has_run = TRUE;
9707 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
9708 mono_perform_abc_removal (cfg);
9710 mono_ssa_remove (cfg);
9712 if (cfg->opt & MONO_OPT_BRANCH)
9713 optimize_branches (cfg);
9716 /* after SSA removal */
9720 decompose_pass (cfg);
9725 g_assert (cfg->got_var_allocated);
9728 * Allways allocate the GOT var to a register, because keeping it
9729 * in memory will increase the number of live temporaries in some
9730 * code created by inssel.brg, leading to the well known spills+
9731 * branches problem. Testcase: mcs crash in
9732 * System.MonoCustomAttrs:GetCustomAttributes.
9734 regs = mono_arch_get_global_int_regs (cfg);
9736 cfg->got_var->opcode = OP_REGVAR;
9737 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
9738 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
9743 if (cfg->opt & MONO_OPT_LINEARS) {
9746 /* For now, compute aliasing info only if needed for deadce... */
9747 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
9748 cfg->aliasing_info = mono_build_aliasing_information (cfg);
9751 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
9752 cfg->comp_done &= ~MONO_COMP_LIVENESS;
9753 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
9754 mono_analyze_liveness (cfg);
9756 if (cfg->aliasing_info != NULL) {
9757 mono_aliasing_deadce (cfg->aliasing_info);
9758 deadce_has_run = TRUE;
9761 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
9762 regs = mono_arch_get_global_int_regs (cfg);
9764 regs = g_list_delete_link (regs, regs);
9765 mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
9768 if (cfg->aliasing_info != NULL) {
9769 mono_destroy_aliasing_information (cfg->aliasing_info);
9770 cfg->aliasing_info = NULL;
9774 //mono_print_code (cfg);
9778 /* variables are allocated after decompose, since decompose could create temps */
9779 mono_arch_allocate_vars (cfg);
9781 if (cfg->opt & MONO_OPT_CFOLD)
9782 mono_constant_fold (cfg);
9784 mini_select_instructions (cfg);
9787 if (cfg->verbose_level >= 2) {
9788 char *id = mono_method_full_name (cfg->method, FALSE);
9789 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
9793 if (cfg->method->dynamic) {
9794 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)));
9796 /* we access cfg->domain->mp */
9797 mono_domain_lock (cfg->domain);
9798 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)));
9799 mono_domain_unlock (cfg->domain);
9802 jinfo->method = method;
9803 jinfo->code_start = cfg->native_code;
9804 jinfo->code_size = cfg->code_len;
9805 jinfo->used_regs = cfg->used_int_regs;
9806 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
9807 jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
9809 if (header->num_clauses) {
9812 jinfo->num_clauses = header->num_clauses;
9814 for (i = 0; i < header->num_clauses; i++) {
9815 MonoExceptionClause *ec = &header->clauses [i];
9816 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
9817 MonoBasicBlock *tblock;
9820 ei->flags = ec->flags;
9822 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
9823 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
9825 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
9826 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->data.filter_offset);
9828 ei->data.filter = cfg->native_code + tblock->native_offset;
9830 ei->data.catch_class = ec->data.catch_class;
9833 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
9835 ei->try_start = cfg->native_code + tblock->native_offset;
9836 g_assert (tblock->native_offset);
9837 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
9839 ei->try_end = cfg->native_code + tblock->native_offset;
9840 g_assert (tblock->native_offset);
9841 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
9843 ei->handler_start = cfg->native_code + tblock->native_offset;
9847 cfg->jit_info = jinfo;
9848 #if defined(__arm__)
9849 mono_arch_fixup_jinfo (cfg);
9852 mono_domain_lock (cfg->domain);
9853 mono_jit_info_table_add (cfg->domain, jinfo);
9855 if (cfg->method->dynamic)
9856 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
9857 mono_domain_unlock (cfg->domain);
9859 /* collect statistics */
9860 mono_jit_stats.allocated_code_size += cfg->code_len;
9861 code_size_ratio = cfg->code_len;
9862 if (code_size_ratio > mono_jit_stats.biggest_method_size) {
9863 mono_jit_stats.biggest_method_size = code_size_ratio;
9864 mono_jit_stats.biggest_method = method;
9866 code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
9867 if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
9868 mono_jit_stats.max_code_size_ratio = code_size_ratio;
9869 mono_jit_stats.max_ratio_method = method;
9871 mono_jit_stats.native_code_size += cfg->code_len;
9873 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9874 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
9880 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
9883 GHashTable *jit_code_hash;
9884 gpointer code = NULL;
9887 jit_code_hash = target_domain->jit_code_hash;
9889 method = mono_get_inflated_method (method);
9891 #ifdef MONO_USE_AOT_COMPILER
9892 if (!mono_compile_aot && (opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
9894 MonoDomain *domain = mono_domain_get ();
9896 mono_domain_lock (domain);
9898 mono_class_init (method->klass);
9899 if ((info = mono_aot_get_method (domain, method))) {
9900 g_hash_table_insert (domain->jit_code_hash, method, info);
9901 mono_domain_unlock (domain);
9902 mono_runtime_class_init (mono_class_vtable (domain, method->klass));
9903 return info->code_start;
9906 mono_domain_unlock (domain);
9910 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9911 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9913 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
9915 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
9916 g_error ("Method '%s' in assembly '%s' contains native code and mono can't run it. The assembly was probably created by Managed C++.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
9918 if (!piinfo->addr) {
9919 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
9920 piinfo->addr = mono_lookup_internal_call (method);
9922 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
9923 mono_lookup_pinvoke_call (method, NULL, NULL);
9925 nm = mono_marshal_get_native_wrapper (method);
9926 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9928 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE)
9929 //mono_debug_add_wrapper (method, nm);
9930 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
9931 const char *name = method->name;
9934 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
9935 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
9936 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
9938 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
9939 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
9940 nm = mono_marshal_get_delegate_invoke (method);
9941 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9942 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
9943 nm = mono_marshal_get_delegate_begin_invoke (method);
9944 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9945 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
9946 nm = mono_marshal_get_delegate_end_invoke (method);
9947 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9953 cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
9955 switch (cfg->exception_type) {
9956 case MONO_EXCEPTION_NONE: break;
9957 case MONO_EXCEPTION_TYPE_LOAD:
9958 case MONO_EXCEPTION_MISSING_FIELD:
9959 case MONO_EXCEPTION_MISSING_METHOD: {
9960 /* Throw a type load exception if needed */
9961 MonoLoaderError *error = mono_loader_get_last_error ();
9963 mono_destroy_compile (cfg);
9965 MonoException *ex = mono_loader_error_prepare_exception (error);
9966 mono_raise_exception (ex);
9968 g_assert_not_reached ();
9971 case MONO_EXCEPTION_INVALID_PROGRAM: {
9972 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
9973 mono_destroy_compile (cfg);
9974 mono_raise_exception (ex);
9977 case MONO_EXCEPTION_UNVERIFIABLE_IL: {
9978 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
9979 mono_destroy_compile (cfg);
9980 mono_raise_exception (ex);
9983 /* this can only be set if the security manager is active */
9984 case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
9985 MonoAssembly *assembly = mono_image_get_assembly (method->klass->image);
9986 MonoReflectionAssembly *refass = (MonoReflectionAssembly*) mono_assembly_get_object (target_domain, assembly);
9987 MonoReflectionMethod *refmet = mono_method_get_object (target_domain, method, NULL);
9988 MonoSecurityManager* secman = mono_security_manager_get_methods ();
9989 MonoObject *exc = NULL;
9992 args [0] = &cfg->exception_data;
9995 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
9997 mono_destroy_compile (cfg);
10000 mono_raise_exception ((MonoException*)exc);
10003 g_assert_not_reached ();
10006 mono_domain_lock (target_domain);
10008 /* Check if some other thread already did the job. In this case, we can
10009 discard the code this thread generated. */
10011 if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
10012 /* We can't use a domain specific method in another domain */
10013 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
10014 code = info->code_start;
10015 // printf("Discarding code for method %s\n", method->name);
10019 if (code == NULL) {
10020 g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
10021 code = cfg->native_code;
10024 mono_destroy_compile (cfg);
10026 if (target_domain->jump_target_hash) {
10027 MonoJumpInfo patch_info;
10028 GSList *list, *tmp;
10029 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
10031 patch_info.next = NULL;
10032 patch_info.ip.i = 0;
10033 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
10034 patch_info.data.method = method;
10035 g_hash_table_remove (target_domain->jump_target_hash, method);
10037 for (tmp = list; tmp; tmp = tmp->next)
10038 mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
10039 g_slist_free (list);
10042 mono_domain_unlock (target_domain);
10044 mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
10049 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
10051 MonoDomain *target_domain, *domain = mono_domain_get ();
10054 MonoJitICallInfo *callinfo = NULL;
10057 * ICALL wrappers are handled specially, since there is only one copy of them
10058 * shared by all appdomains.
10060 if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
10061 const char *icall_name;
10063 icall_name = method->name + strlen ("__icall_wrapper_");
10064 g_assert (icall_name);
10065 callinfo = mono_find_jit_icall_by_name (icall_name);
10066 g_assert (callinfo);
10068 /* Must be domain neutral since there is only one copy */
10069 opt |= MONO_OPT_SHARED;
10072 if (opt & MONO_OPT_SHARED)
10073 target_domain = mono_get_root_domain ();
10075 target_domain = domain;
10077 mono_domain_lock (target_domain);
10079 if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
10080 /* We can't use a domain specific method in another domain */
10081 if (! ((domain != target_domain) && !info->domain_neutral)) {
10082 mono_domain_unlock (target_domain);
10083 mono_jit_stats.methods_lookups++;
10084 mono_runtime_class_init (mono_class_vtable (domain, method->klass));
10085 return mono_create_ftnptr (target_domain, info->code_start);
10089 mono_domain_unlock (target_domain);
10090 p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
10094 if (!callinfo->wrapper) {
10095 callinfo->wrapper = p;
10096 mono_register_jit_icall_wrapper (callinfo, p);
10097 mono_debug_add_icall_wrapper (method, callinfo);
10099 mono_jit_unlock ();
10106 mono_jit_compile_method (MonoMethod *method)
10108 return mono_jit_compile_method_with_opt (method, default_opt);
10112 invalidated_delegate_trampoline (char *desc)
10114 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
10115 "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
10120 * mono_jit_free_method:
10122 * Free all memory allocated by the JIT for METHOD.
10125 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
10127 MonoJitDynamicMethodInfo *ji;
10128 gboolean destroy = TRUE;
10130 g_assert (method->dynamic);
10132 mono_domain_lock (domain);
10133 ji = mono_dynamic_code_hash_lookup (domain, method);
10134 mono_domain_unlock (domain);
10138 mono_domain_lock (domain);
10139 g_hash_table_remove (domain->dynamic_code_hash, method);
10140 g_hash_table_remove (domain->jit_code_hash, method);
10141 g_hash_table_remove (domain->jump_trampoline_hash, method);
10142 mono_domain_unlock (domain);
10144 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
10145 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
10147 * Instead of freeing the code, change it to call an error routine
10148 * so people can fix their code.
10150 char *type = mono_type_full_name (&method->klass->byval_arg);
10151 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
10154 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
10160 * This needs to be done before freeing code_mp, since the code address is the
10161 * key in the table, so if we the code_mp first, another thread can grab the
10162 * same code address and replace our entry in the table.
10164 mono_jit_info_table_remove (domain, ji->ji);
10167 mono_code_manager_destroy (ji->code_mp);
10173 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
10175 MonoDomain *target_domain;
10178 if (default_opt & MONO_OPT_SHARED)
10179 target_domain = mono_get_root_domain ();
10181 target_domain = domain;
10183 mono_domain_lock (target_domain);
10185 if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
10186 /* We can't use a domain specific method in another domain */
10187 if (! ((domain != target_domain) && !info->domain_neutral)) {
10188 mono_domain_unlock (target_domain);
10189 mono_jit_stats.methods_lookups++;
10190 return info->code_start;
10194 mono_domain_unlock (target_domain);
10200 * mono_jit_runtime_invoke:
10201 * @method: the method to invoke
10202 * @obj: this pointer
10203 * @params: array of parameter values.
10204 * @exc: used to catch exceptions objects
10207 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
10209 MonoMethod *invoke;
10210 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
10211 void* compiled_method;
10213 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
10214 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
10218 method = mono_get_inflated_method (method);
10219 invoke = mono_marshal_get_runtime_invoke (method);
10220 runtime_invoke = mono_jit_compile_method (invoke);
10222 /* We need this here becuase mono_marshal_get_runtime_invoke can be place
10223 * the helper method in System.Object and not the target class
10225 mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
10227 compiled_method = mono_jit_compile_method (method);
10228 return runtime_invoke (obj, params, exc, compiled_method);
10231 #ifdef PLATFORM_WIN32
10232 #define GET_CONTEXT \
10233 struct sigcontext *ctx = (struct sigcontext*)_dummy;
10236 #define GET_CONTEXT \
10237 void *ctx = context;
10238 #elif defined(sun) // Solaris x86
10239 #define GET_CONTEXT \
10240 ucontext_t *uctx = context; \
10241 struct sigcontext *ctx = (struct sigcontext *)&(uctx->uc_mcontext);
10242 #elif defined (MONO_ARCH_USE_SIGACTION)
10243 #define GET_CONTEXT \
10244 void *ctx = context;
10246 #define GET_CONTEXT \
10247 void **_p = (void **)&_dummy; \
10248 struct sigcontext *ctx = (struct sigcontext *)++_p;
10252 #ifdef MONO_ARCH_USE_SIGACTION
10253 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
10255 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
10259 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
10261 MonoException *exc = NULL;
10262 #ifndef MONO_ARCH_USE_SIGACTION
10267 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
10268 if (mono_arch_is_int_overflow (ctx, info))
10269 exc = mono_get_exception_arithmetic ();
10271 exc = mono_get_exception_divide_by_zero ();
10273 exc = mono_get_exception_divide_by_zero ();
10276 mono_arch_handle_exception (ctx, exc, FALSE);
10280 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
10282 MonoException *exc;
10285 exc = mono_get_exception_execution_engine ("SIGILL");
10287 mono_arch_handle_exception (ctx, exc, FALSE);
10290 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10292 #ifndef MONO_ARCH_USE_SIGACTION
10293 #error "Can't use sigaltstack without sigaction"
10299 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
10301 MonoException *exc = NULL;
10304 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10305 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
10309 #ifdef MONO_ARCH_USE_SIGACTION
10310 if (debug_options.collect_pagefault_stats) {
10311 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
10312 mono_raw_buffer_handle_pagefault (info->si_addr);
10315 if (mono_aot_is_pagefault (info->si_addr)) {
10316 mono_aot_handle_pagefault (info->si_addr);
10322 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10323 /* Can't allocate memory using Boehm GC on altstack */
10324 if (jit_tls->stack_size &&
10325 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
10326 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
10327 exc = mono_domain_get ()->stack_overflow_ex;
10329 exc = mono_domain_get ()->null_reference_ex;
10332 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
10334 mono_handle_native_sigsegv (SIGSEGV, ctx);
10337 mono_arch_handle_exception (ctx, exc, FALSE);
10341 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
10346 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
10348 mono_handle_native_sigsegv (SIGABRT, ctx);
10353 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
10355 gboolean running_managed;
10356 MonoException *exc;
10357 MonoThread *thread = mono_thread_current ();
10362 if (thread->thread_dump_requested) {
10363 thread->thread_dump_requested = FALSE;
10365 mono_print_thread_dump (ctx);
10370 * This is an async signal, so the code below must not call anything which
10371 * is not async safe. That includes the pthread locking functions. If we
10372 * know that we interrupted managed code, then locking is safe.
10374 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
10375 running_managed = ji != NULL;
10377 exc = mono_thread_request_interruption (running_managed);
10380 mono_arch_handle_exception (ctx, exc, FALSE);
10384 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
10388 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
10392 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
10396 printf ("Full thread dump:\n");
10398 mono_threads_request_thread_dump ();
10401 * print_thread_dump () skips the current thread, since sending a signal
10402 * to it would invoke the signal handler below the sigquit signal handler,
10403 * and signal handlers don't create an lmf, so the stack walk could not
10406 mono_print_thread_dump (ctx);
10410 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
10412 MonoException *exc;
10415 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
10417 mono_arch_handle_exception (ctx, exc, FALSE);
10421 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
10423 gboolean enabled = mono_trace_is_enabled ();
10425 mono_trace_enable (!enabled);
10428 #ifndef PLATFORM_WIN32
10430 add_signal_handler (int signo, gpointer handler)
10432 struct sigaction sa;
10434 #ifdef MONO_ARCH_USE_SIGACTION
10435 sa.sa_sigaction = handler;
10436 sigemptyset (&sa.sa_mask);
10437 sa.sa_flags = SA_SIGINFO;
10439 sa.sa_handler = handler;
10440 sigemptyset (&sa.sa_mask);
10443 g_assert (sigaction (signo, &sa, NULL) != -1);
10448 mono_runtime_install_handlers (void)
10450 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10451 struct sigaction sa;
10454 #ifdef PLATFORM_WIN32
10456 win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
10457 win32_seh_set_handler(SIGILL, sigill_signal_handler);
10458 win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
10459 if (debug_options.handle_sigint)
10460 win32_seh_set_handler(SIGINT, sigint_signal_handler);
10462 #else /* !PLATFORM_WIN32 */
10464 /* libpthreads has its own implementation of sigaction(),
10465 * but it seems to work well with our current exception
10466 * handlers. If not we must call syscall directly instead
10469 if (debug_options.handle_sigint)
10470 add_signal_handler (SIGINT, sigint_signal_handler);
10472 add_signal_handler (SIGFPE, sigfpe_signal_handler);
10473 add_signal_handler (SIGQUIT, sigquit_signal_handler);
10474 add_signal_handler (SIGILL, sigill_signal_handler);
10475 add_signal_handler (SIGBUS, sigsegv_signal_handler);
10476 if (mono_jit_trace_calls != NULL)
10477 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
10479 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
10480 signal (SIGPIPE, SIG_IGN);
10482 add_signal_handler (SIGABRT, sigabrt_signal_handler);
10484 /* catch SIGSEGV */
10485 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10486 sa.sa_sigaction = sigsegv_signal_handler;
10487 sigemptyset (&sa.sa_mask);
10488 sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
10489 g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
10491 add_signal_handler (SIGSEGV, sigsegv_signal_handler);
10493 #endif /* PLATFORM_WIN32 */
10497 #ifdef HAVE_LINUX_RTC_H
10498 #include <linux/rtc.h>
10499 #include <sys/ioctl.h>
10501 static int rtc_fd = -1;
10504 enable_rtc_timer (gboolean enable)
10507 flags = fcntl (rtc_fd, F_GETFL);
10509 perror ("getflags");
10516 if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
10517 perror ("setflags");
10525 setup_stat_profiler (void)
10528 struct itimerval itval;
10529 static int inited = 0;
10530 #ifdef HAVE_LINUX_RTC_H
10531 const char *rtc_freq;
10532 if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
10536 freq = atoi (rtc_freq);
10539 rtc_fd = open ("/dev/rtc", O_RDONLY);
10540 if (rtc_fd == -1) {
10541 perror ("open /dev/rtc");
10544 add_signal_handler (SIGPROF, sigprof_signal_handler);
10545 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
10546 perror ("set rtc freq");
10549 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
10550 perror ("start rtc");
10553 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
10557 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
10561 enable_rtc_timer (TRUE);
10568 itval.it_interval.tv_usec = 999;
10569 itval.it_interval.tv_sec = 0;
10570 itval.it_value = itval.it_interval;
10571 setitimer (ITIMER_PROF, &itval, NULL);
10575 add_signal_handler (SIGPROF, sigprof_signal_handler);
10579 /* mono_jit_create_remoting_trampoline:
10580 * @method: pointer to the method info
10582 * Creates a trampoline which calls the remoting functions. This
10583 * is used in the vtable of transparent proxies.
10585 * Returns: a pointer to the newly created code
10588 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
10591 guint8 *addr = NULL;
10593 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10594 (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
10595 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
10596 addr = mono_compile_method (nm);
10598 addr = mono_compile_method (method);
10600 return mono_get_addr_from_ftnptr (addr);
10604 mini_parse_debug_options (void)
10606 char *options = getenv ("MONO_DEBUG");
10607 gchar **args, **ptr;
10612 args = g_strsplit (options, ",", -1);
10614 for (ptr = args; ptr && *ptr; ptr++) {
10615 const char *arg = *ptr;
10617 if (!strcmp (arg, "handle-sigint"))
10618 debug_options.handle_sigint = TRUE;
10619 else if (!strcmp (arg, "keep-delegates"))
10620 debug_options.keep_delegates = TRUE;
10621 else if (!strcmp (arg, "collect-pagefault-stats"))
10622 debug_options.collect_pagefault_stats = TRUE;
10624 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
10625 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats'\n");
10632 mini_init (const char *filename)
10634 MonoDomain *domain;
10636 /* Happens when using the embedding interface */
10637 if (!default_opt_set)
10638 default_opt = mono_parse_default_optimizations (NULL);
10640 InitializeCriticalSection (&jit_mutex);
10642 global_codeman = mono_code_manager_new ();
10643 jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10645 mono_arch_cpu_init ();
10647 mono_init_trampolines ();
10649 mono_init_exceptions ();
10651 if (!g_thread_supported ())
10652 g_thread_init (NULL);
10654 if (getenv ("MONO_DEBUG") != NULL)
10655 mini_parse_debug_options ();
10658 * Handle the case when we are called from a thread different from the main thread,
10660 * FIXME: Move this to libgc where it belongs.
10662 * we used to do this only when running on valgrind,
10663 * but it happens also in other setups.
10665 #if defined(HAVE_BOEHM_GC)
10666 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
10670 pthread_attr_t attr;
10671 pthread_getattr_np (pthread_self (), &attr);
10672 pthread_attr_getstack (&attr, &sstart, &size);
10673 pthread_attr_destroy (&attr);
10674 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
10677 * The calculation above doesn't seem to work on ia64, also we need to set
10678 * GC_register_stackbottom as well, but don't know how.
10681 GC_stackbottom = (char*)sstart + size;
10684 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
10685 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
10688 gsize stack_bottom = (gsize)&domain;
10689 stack_bottom += 4095;
10690 stack_bottom &= ~4095;
10691 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
10692 GC_stackbottom = (char*)stack_bottom;
10696 MONO_GC_PRE_INIT ();
10698 mono_jit_tls_id = TlsAlloc ();
10699 setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
10703 if (default_opt & MONO_OPT_AOT)
10706 mono_runtime_install_handlers ();
10707 mono_threads_install_cleanup (mini_thread_cleanup);
10709 #define JIT_TRAMPOLINES_WORK
10710 #ifdef JIT_TRAMPOLINES_WORK
10711 mono_install_compile_method (mono_jit_compile_method);
10712 mono_install_free_method (mono_jit_free_method);
10713 mono_install_trampoline (mono_create_jit_trampoline);
10714 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
10715 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
10717 #define JIT_INVOKE_WORKS
10718 #ifdef JIT_INVOKE_WORKS
10719 mono_install_runtime_invoke (mono_jit_runtime_invoke);
10720 mono_install_handler (mono_arch_get_throw_exception ());
10722 mono_install_stack_walk (mono_jit_walk_stack);
10723 mono_install_init_vtable (mono_aot_init_vtable);
10724 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
10725 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
10727 if (debug_options.collect_pagefault_stats) {
10728 mono_raw_buffer_set_make_unreadable (TRUE);
10729 mono_aot_set_make_unreadable (TRUE);
10732 domain = mono_init_from_assembly (filename, filename);
10733 mono_icall_init ();
10735 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
10736 ves_icall_get_frame_info);
10737 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
10738 ves_icall_get_trace);
10739 mono_add_internal_call ("System.Exception::get_trace",
10740 ves_icall_System_Exception_get_trace);
10741 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
10742 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
10743 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
10744 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
10745 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
10746 mono_runtime_install_handlers);
10749 create_helper_signature ();
10751 #define JIT_CALLS_WORK
10752 #ifdef JIT_CALLS_WORK
10753 /* Needs to be called here since register_jit_icall depends on it */
10754 mono_marshal_init ();
10756 mono_arch_register_lowlevel_calls ();
10757 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
10758 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
10759 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
10760 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
10761 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
10762 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
10763 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
10765 register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
10766 register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
10767 register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE);
10768 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
10769 register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception",
10772 register_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", "object", FALSE);
10773 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
10774 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
10775 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
10776 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
10779 * NOTE, NOTE, NOTE, NOTE:
10780 * when adding emulation for some opcodes, remember to also add a dummy
10781 * rule to the burg files, because we need the arity information to be correct.
10783 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
10784 mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
10785 mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
10786 mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
10787 mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
10788 mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
10789 mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
10790 mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
10793 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
10794 mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
10795 mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
10796 mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
10799 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
10800 mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, TRUE);
10801 mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, TRUE);
10802 mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, TRUE);
10803 mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, TRUE);
10806 #ifdef MONO_ARCH_EMULATE_MUL_DIV
10807 mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, TRUE);
10808 mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, TRUE);
10809 mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
10810 mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, TRUE);
10813 mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
10814 mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
10815 mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
10816 mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
10818 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
10819 mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
10821 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
10822 mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
10824 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
10825 mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
10827 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
10828 mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
10830 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
10831 mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
10833 #ifdef MONO_ARCH_EMULATE_FREM
10834 mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
10837 #if SIZEOF_VOID_P == 4
10838 mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
10841 /* other jit icalls */
10842 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
10843 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
10844 "ptr ptr ptr", FALSE);
10845 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
10846 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
10847 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
10848 register_icall (mono_helper_stelem_ref, "helper_stelem_ref", "void ptr int32 object", FALSE);
10849 register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
10850 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
10851 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
10852 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
10853 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
10854 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
10855 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
10856 register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
10857 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
10858 register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr", FALSE);
10859 register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
10860 register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
10861 register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
10862 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
10865 #define JIT_RUNTIME_WORKS
10866 #ifdef JIT_RUNTIME_WORKS
10867 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
10868 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
10871 mono_thread_attach (domain);
10875 MonoJitStats mono_jit_stats = {0};
10878 print_jit_stats (void)
10880 if (mono_jit_stats.enabled) {
10881 g_print ("Mono Jit statistics\n");
10882 g_print ("Compiled methods: %ld\n", mono_jit_stats.methods_compiled);
10883 g_print ("Methods from AOT: %ld\n", mono_jit_stats.methods_aot);
10884 g_print ("Methods cache lookup: %ld\n", mono_jit_stats.methods_lookups);
10885 g_print ("Method trampolines: %ld\n", mono_jit_stats.method_trampolines);
10886 g_print ("Basic blocks: %ld\n", mono_jit_stats.basic_blocks);
10887 g_print ("Max basic blocks: %ld\n", mono_jit_stats.max_basic_blocks);
10888 g_print ("Allocated vars: %ld\n", mono_jit_stats.allocate_var);
10889 g_print ("Analyze stack repeat: %ld\n", mono_jit_stats.analyze_stack_repeat);
10890 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
10891 g_print ("Native code size: %ld\n", mono_jit_stats.native_code_size);
10892 g_print ("Max code size ratio: %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
10893 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
10894 g_print ("Biggest method: %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
10895 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
10896 g_print ("Code reallocs: %ld\n", mono_jit_stats.code_reallocs);
10897 g_print ("Allocated code size: %ld\n", mono_jit_stats.allocated_code_size);
10898 g_print ("Inlineable methods: %ld\n", mono_jit_stats.inlineable_methods);
10899 g_print ("Inlined methods: %ld\n", mono_jit_stats.inlined_methods);
10901 g_print ("\nCreated object count: %ld\n", mono_stats.new_object_count);
10902 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
10903 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
10904 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
10905 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
10907 g_print ("\nGeneric instances: %ld\n", mono_stats.generic_instance_count);
10908 g_print ("Initialized classes: %ld\n", mono_stats.generic_class_count);
10909 g_print ("Inflated methods: %ld / %ld\n", mono_stats.inflated_method_count_2,
10910 mono_stats.inflated_method_count);
10911 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
10912 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
10914 if (mono_use_security_manager) {
10915 g_print ("\nDecl security check : %ld\n", mono_jit_stats.cas_declsec_check);
10916 g_print ("LinkDemand (user) : %ld\n", mono_jit_stats.cas_linkdemand);
10917 g_print ("LinkDemand (icall) : %ld\n", mono_jit_stats.cas_linkdemand_icall);
10918 g_print ("LinkDemand (pinvoke) : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
10919 g_print ("LinkDemand (aptc) : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
10920 g_print ("Demand (code gen) : %ld\n", mono_jit_stats.cas_demand_generation);
10922 if (debug_options.collect_pagefault_stats) {
10923 g_print ("Metadata pagefaults : %d\n", mono_raw_buffer_get_n_pagefaults ());
10924 g_print ("AOT pagefaults : %d\n", mono_aot_get_n_pagefaults ());
10930 mini_cleanup (MonoDomain *domain)
10932 #ifdef HAVE_LINUX_RTC_H
10934 enable_rtc_timer (FALSE);
10938 * mono_runtime_cleanup() and mono_domain_finalize () need to
10939 * be called early since they need the execution engine still
10940 * fully working (mono_domain_finalize may invoke managed finalizers
10941 * and mono_runtime_cleanup will wait for other threads to finish).
10943 mono_domain_finalize (domain, 2000);
10945 /* This accesses metadata so needs to be called before runtime shutdown */
10946 print_jit_stats ();
10948 mono_runtime_cleanup (domain);
10950 mono_profiler_shutdown ();
10952 mono_debug_cleanup ();
10954 mono_icall_cleanup ();
10956 #ifdef PLATFORM_WIN32
10957 win32_seh_cleanup();
10960 mono_domain_free (domain, TRUE);
10962 mono_code_manager_destroy (global_codeman);
10963 g_hash_table_destroy (jit_icall_name_hash);
10964 if (class_init_hash_addr)
10965 g_hash_table_destroy (class_init_hash_addr);
10966 g_free (emul_opcode_map);
10970 mono_trace_cleanup ();
10972 mono_counters_dump (-1, stdout);
10976 mono_set_defaults (int verbose_level, guint32 opts)
10978 mini_verbose = verbose_level;
10979 default_opt = opts;
10980 default_opt_set = TRUE;
10984 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
10986 GHashTable *assemblies = (GHashTable*)user_data;
10987 MonoImage *image = mono_assembly_get_image (ass);
10988 MonoMethod *method, *invoke;
10991 if (g_hash_table_lookup (assemblies, ass))
10994 g_hash_table_insert (assemblies, ass, ass);
10996 if (mini_verbose > 0)
10997 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
10999 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
11000 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
11001 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
11005 if (mini_verbose > 1) {
11006 char * desc = mono_method_full_name (method, TRUE);
11007 g_print ("Compiling %d %s\n", count, desc);
11010 mono_compile_method (method);
11011 if (strcmp (method->name, "Finalize") == 0) {
11012 invoke = mono_marshal_get_runtime_invoke (method);
11013 mono_compile_method (invoke);
11015 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
11016 invoke = mono_marshal_get_remoting_invoke_with_check (method);
11017 mono_compile_method (invoke);
11021 /* Load and precompile referenced assemblies as well */
11022 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
11023 mono_assembly_load_reference (image, i);
11024 if (image->references [i])
11025 mono_precompile_assembly (image->references [i], assemblies);
11029 void mono_precompile_assemblies ()
11031 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
11033 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
11035 g_hash_table_destroy (assemblies);