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 HAVE_SYS_TIME_H
21 #ifdef PLATFORM_MACOSX
22 #include <mach/mach.h>
23 #include <mach/mach_error.h>
24 #include <mach/exception.h>
25 #include <mach/task.h>
30 #define _WIN32_WINNT 0x0500
33 #ifdef HAVE_VALGRIND_MEMCHECK_H
34 #include <valgrind/memcheck.h>
37 #include <mono/metadata/assembly.h>
38 #include <mono/metadata/loader.h>
39 #include <mono/metadata/tabledefs.h>
40 #include <mono/metadata/class.h>
41 #include <mono/metadata/object.h>
42 #include <mono/metadata/exception.h>
43 #include <mono/metadata/opcodes.h>
44 #include <mono/metadata/mono-endian.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/threads.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/socket-io.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/io-layer/io-layer.h>
53 #include "mono/metadata/profiler.h"
54 #include <mono/metadata/profiler-private.h>
55 #include <mono/metadata/mono-config.h>
56 #include <mono/metadata/environment.h>
57 #include <mono/metadata/mono-debug.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/gc-internal.h>
60 #include <mono/metadata/security-manager.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/metadata/rawbuffer.h>
63 #include <mono/metadata/security-core-clr.h>
64 #include <mono/utils/mono-math.h>
65 #include <mono/utils/mono-compiler.h>
66 #include <mono/utils/mono-counters.h>
67 #include <mono/utils/mono-logger.h>
68 #include <mono/utils/mono-mmap.h>
76 #include "jit-icalls.h"
80 #include "debug-mini.h"
82 #define BRANCH_COST 100
83 #define INLINE_LENGTH_LIMIT 20
84 #define INLINE_FAILURE do {\
85 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
88 #define CHECK_CFG_EXCEPTION do {\
89 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
92 #define METHOD_ACCESS_FAILURE do { \
93 char *method_fname = mono_method_full_name (method, TRUE); \
94 char *cil_method_fname = mono_method_full_name (cil_method, TRUE); \
95 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS; \
96 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname); \
97 g_free (method_fname); \
98 g_free (cil_method_fname); \
99 goto exception_exit; \
101 #define FIELD_ACCESS_FAILURE do { \
102 char *method_fname = mono_method_full_name (method, TRUE); \
103 char *field_fname = mono_field_full_name (field); \
104 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS; \
105 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname); \
106 g_free (method_fname); \
107 g_free (field_fname); \
108 goto exception_exit; \
110 #define GENERIC_SHARING_FAILURE(opcode) do { \
111 if (cfg->generic_sharing_context) { \
112 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) \
113 /*g_print ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", method->klass->name_space, method->klass->name, method->name, method->signature->param_count, mono_opcode_name ((opcode)), __LINE__)*/; \
114 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED; \
115 goto exception_exit; \
119 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
121 static void setup_stat_profiler (void);
122 gboolean mono_arch_print_tree(MonoInst *tree, int arity);
123 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
124 static gpointer mono_jit_compile_method (MonoMethod *method);
125 static gpointer mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method);
126 static gpointer mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method);
127 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
129 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src,
130 const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
132 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
134 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
135 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
136 guint inline_offset, gboolean is_virtual_call);
138 #ifdef MONO_ARCH_SOFT_FLOAT
140 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
143 /* helper methods signature */
144 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
145 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
146 static MonoMethodSignature *helper_sig_domain_get = NULL;
148 static guint32 default_opt = 0;
149 static gboolean default_opt_set = FALSE;
151 guint32 mono_jit_tls_id = -1;
152 MonoTraceSpec *mono_jit_trace_calls = NULL;
153 gboolean mono_break_on_exc = FALSE;
155 gboolean mono_compile_aot = FALSE;
157 MonoMethodDesc *mono_inject_async_exc_method = NULL;
158 int mono_inject_async_exc_pos;
159 MonoMethodDesc *mono_break_at_bb_method = NULL;
160 int mono_break_at_bb_bb_num;
162 static int mini_verbose = 0;
164 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
165 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
166 static CRITICAL_SECTION jit_mutex;
168 static GHashTable *class_init_hash_addr = NULL;
169 static GHashTable *delegate_trampoline_hash_addr = NULL;
171 static MonoCodeManager *global_codeman = NULL;
173 static GHashTable *jit_icall_name_hash = NULL;
175 static MonoDebugOptions debug_options;
177 #ifdef VALGRIND_JIT_REGISTER_MAP
178 static int valgrind_register = 0;
182 * Address of the trampoline code. This is used by the debugger to check
183 * whether a method is a trampoline.
185 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
188 * Table written to by the debugger with a 1-based index into the
189 * mono_breakpoint_info table, which contains changes made to
190 * the JIT instructions by the debugger.
193 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
195 /* Whenever to check for pending exceptions in managed-to-native wrappers */
196 gboolean check_for_pending_exc = TRUE;
199 mono_running_on_valgrind (void)
201 #ifdef HAVE_VALGRIND_MEMCHECK_H
202 if (RUNNING_ON_VALGRIND){
203 #ifdef VALGRIND_JIT_REGISTER_MAP
204 valgrind_register = TRUE;
220 find_tramp (gpointer key, gpointer value, gpointer user_data)
222 FindTrampUserData *ud = (FindTrampUserData*)user_data;
225 ud->method = (MonoMethod*)key;
229 G_GNUC_UNUSED static char*
230 get_method_from_ip (void *ip)
235 MonoDomain *domain = mono_domain_get ();
236 MonoDebugSourceLocation *location;
237 FindTrampUserData user_data;
239 ji = mono_jit_info_table_find (domain, ip);
242 user_data.method = NULL;
243 mono_domain_lock (domain);
244 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
245 mono_domain_unlock (domain);
246 if (user_data.method) {
247 char *mname = mono_method_full_name (user_data.method, TRUE);
248 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
255 method = mono_method_full_name (ji->method, TRUE);
256 /* FIXME: unused ? */
257 location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
259 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);
261 mono_debug_free_source_location (location);
269 * @ip: an instruction pointer address
271 * This method is used from a debugger to get the name of the
272 * method at address @ip. This routine is typically invoked from
273 * a debugger like this:
275 * (gdb) print mono_pmip ($pc)
277 * Returns: the name of the method at address @ip.
282 return get_method_from_ip (ip);
286 * mono_print_method_from_ip
287 * @ip: an instruction pointer address
289 * This method is used from a debugger to get the name of the
290 * method at address @ip.
292 * This prints the name of the method at address @ip in the standard
293 * output. Unlike mono_pmip which returns a string, this routine
294 * prints the value on the standard output.
297 mono_print_method_from_ip (void *ip)
301 MonoDebugSourceLocation *source;
302 MonoDomain *domain = mono_domain_get ();
303 FindTrampUserData user_data;
305 ji = mono_jit_info_table_find (domain, ip);
308 user_data.method = NULL;
309 mono_domain_lock (domain);
310 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
311 mono_domain_unlock (domain);
312 if (user_data.method) {
313 char *mname = mono_method_full_name (user_data.method, TRUE);
314 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
318 g_print ("No method at %p\n", ip);
321 method = mono_method_full_name (ji->method, TRUE);
322 source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
324 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);
327 g_print ("%s:%d\n", source->source_file, source->row);
329 mono_debug_free_source_location (source);
334 * mono_method_same_domain:
336 * Determine whenever two compiled methods are in the same domain, thus
337 * the address of the callee can be embedded in the caller.
339 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
341 if (!caller || !callee)
345 * If the call was made from domain-neutral to domain-specific
346 * code, we can't patch the call site.
348 if (caller->domain_neutral && !callee->domain_neutral)
351 if ((caller->method->klass == mono_defaults.appdomain_class) &&
352 (strstr (caller->method->name, "InvokeInDomain"))) {
353 /* The InvokeInDomain methods change the current appdomain */
361 * mono_global_codeman_reserve:
363 * Allocate code memory from the global code manager.
365 void *mono_global_codeman_reserve (int size)
369 if (!global_codeman) {
370 /* This can happen during startup */
371 global_codeman = mono_code_manager_new ();
372 return mono_code_manager_reserve (global_codeman, size);
376 ptr = mono_code_manager_reserve (global_codeman, size);
383 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
385 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
392 #define MONO_INIT_VARINFO(vi,id) do { \
393 (vi)->range.first_use.pos.bid = 0xffff; \
398 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
399 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
402 * Basic blocks have two numeric identifiers:
403 * dfn: Depth First Number
404 * block_num: unique ID assigned at bblock creation
406 #define NEW_BBLOCK(cfg,new_bb) do { \
407 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
408 MONO_INST_LIST_INIT (&new_bb->ins_list); \
411 #define ADD_BBLOCK(cfg,b) do { \
412 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b); \
413 (b)->block_num = cfg->num_bblocks++; \
414 (b)->real_offset = real_offset; \
417 #define GET_BBLOCK(cfg,tblock,ip) do { \
418 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
420 if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
421 NEW_BBLOCK (cfg, (tblock)); \
422 (tblock)->cil_code = (ip); \
423 ADD_BBLOCK (cfg, (tblock)); \
427 #define CHECK_BBLOCK(target,ip,tblock) do { \
428 if ((target) < (ip) && \
429 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
430 bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
431 if (cfg->verbose_level > 2) \
432 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)); \
436 #define NEW_ICONST(cfg,dest,val) do { \
437 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
438 (dest)->opcode = OP_ICONST; \
439 (dest)->inst_c0 = (val); \
440 (dest)->type = STACK_I4; \
443 #define NEW_PCONST(cfg,dest,val) do { \
444 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
445 (dest)->opcode = OP_PCONST; \
446 (dest)->inst_p0 = (val); \
447 (dest)->type = STACK_PTR; \
451 #ifdef MONO_ARCH_NEED_GOT_VAR
453 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do { \
454 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
455 (dest)->opcode = OP_PATCH_INFO; \
456 (dest)->inst_left = (gpointer)(el1); \
457 (dest)->inst_right = (gpointer)(el2); \
460 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
461 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
462 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
463 if (cfg->compile_aot) { \
464 MonoInst *group, *got_var, *got_loc; \
465 got_loc = mono_get_got_var (cfg); \
466 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
467 NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
468 (dest)->inst_p0 = got_var; \
469 (dest)->inst_p1 = group; \
471 (dest)->inst_p0 = (cons); \
472 (dest)->inst_i1 = (gpointer)(patch_type); \
474 (dest)->type = STACK_PTR; \
477 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
478 MonoInst *group, *got_var, *got_loc; \
479 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
480 (dest)->opcode = OP_GOT_ENTRY; \
481 got_loc = mono_get_got_var (cfg); \
482 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
483 NEW_PATCH_INFO ((cfg), group, NULL, patch_type); \
484 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
485 (dest)->inst_p0 = got_var; \
486 (dest)->inst_p1 = group; \
487 (dest)->type = (stack_type); \
488 (dest)->klass = (stack_class); \
493 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
494 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
495 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST; \
496 (dest)->inst_p0 = (cons); \
497 (dest)->inst_i1 = (gpointer)(patch_type); \
498 (dest)->type = STACK_PTR; \
501 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
502 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
503 (dest)->opcode = OP_AOTCONST; \
504 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
505 (dest)->inst_p1 = (gpointer)(patch_type); \
506 (dest)->type = (stack_type); \
507 (dest)->klass = (stack_class); \
512 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
514 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
516 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
518 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
520 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
522 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
524 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
526 #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, mono_defaults.monotype_class)
528 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
530 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
531 if (cfg->compile_aot) { \
532 NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
534 NEW_PCONST (cfg, args [0], (entry).blob); \
538 #define NEW_DOMAINCONST(cfg,dest) do { \
539 if (cfg->opt & MONO_OPT_SHARED) { \
540 /* avoid depending on undefined C behavior in sequence points */ \
541 MonoInst* __domain_var = mono_get_domainvar (cfg); \
542 NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
544 NEW_PCONST (cfg, dest, (cfg)->domain); \
548 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
550 #define NEW_ARGLOAD(cfg,dest,num) do { \
551 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
552 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
553 (dest)->ssa_op = MONO_SSA_LOAD; \
554 (dest)->inst_i0 = arg_array [(num)]; \
555 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
556 type_to_eval_stack_type ((cfg), param_types [(num)], (dest)); \
557 (dest)->klass = (dest)->inst_i0->klass; \
560 #define NEW_LOCLOAD(cfg,dest,num) do { \
561 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
562 (dest)->ssa_op = MONO_SSA_LOAD; \
563 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
564 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
565 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest)); \
566 (dest)->klass = (dest)->inst_i0->klass; \
569 #define NEW_LOCLOADA(cfg,dest,num) do { \
570 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
571 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
572 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
573 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
574 (dest)->opcode = OP_LDADDR; \
575 (dest)->type = STACK_MP; \
576 (dest)->klass = (dest)->inst_i0->klass; \
577 if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
578 (cfg)->disable_ssa = TRUE; \
581 #define NEW_RETLOADA(cfg,dest) do { \
582 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
583 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
584 (dest)->inst_i0 = (cfg)->ret; \
585 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
586 (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I; \
587 (dest)->type = STACK_MP; \
588 (dest)->klass = (dest)->inst_i0->klass; \
589 (cfg)->disable_ssa = TRUE; \
592 #define NEW_ARGLOADA(cfg,dest,num) do { \
593 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
594 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
595 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
596 (dest)->inst_i0 = arg_array [(num)]; \
597 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
598 (dest)->opcode = OP_LDADDR; \
599 (dest)->type = STACK_MP; \
600 (dest)->klass = (dest)->inst_i0->klass; \
601 (cfg)->disable_ssa = TRUE; \
604 #define NEW_TEMPLOAD(cfg,dest,num) do { \
605 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
606 (dest)->ssa_op = MONO_SSA_LOAD; \
607 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
608 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
609 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest)); \
610 (dest)->klass = (dest)->inst_i0->klass; \
613 #define NEW_TEMPLOADA(cfg,dest,num) do { \
614 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
615 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
616 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
617 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
618 (dest)->opcode = OP_LDADDR; \
619 (dest)->type = STACK_MP; \
620 (dest)->klass = (dest)->inst_i0->klass; \
621 if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
622 (cfg)->disable_ssa = TRUE; \
626 #define NEW_INDLOAD(cfg,dest,addr,vtype) do { \
627 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
628 (dest)->inst_left = addr; \
629 (dest)->opcode = mini_type_to_ldind ((cfg), vtype); \
630 type_to_eval_stack_type ((cfg), vtype, (dest)); \
631 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
634 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do { \
635 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
636 (dest)->inst_i0 = addr; \
637 (dest)->opcode = mini_type_to_stind ((cfg), vtype); \
638 (dest)->inst_i1 = (value); \
639 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
642 #define NEW_TEMPSTORE(cfg,dest,num,inst) do { \
643 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
644 (dest)->ssa_op = MONO_SSA_STORE; \
645 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
646 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
647 (dest)->inst_i1 = (inst); \
648 (dest)->klass = (dest)->inst_i0->klass; \
651 #define NEW_LOCSTORE(cfg,dest,num,inst) do { \
652 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
653 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
654 (dest)->ssa_op = MONO_SSA_STORE; \
655 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
656 (dest)->inst_i1 = (inst); \
657 (dest)->klass = (dest)->inst_i0->klass; \
660 #define NEW_ARGSTORE(cfg,dest,num,inst) do { \
661 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
662 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
663 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
664 (dest)->ssa_op = MONO_SSA_STORE; \
665 (dest)->inst_i0 = arg_array [(num)]; \
666 (dest)->inst_i1 = (inst); \
667 (dest)->klass = (dest)->inst_i0->klass; \
670 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
671 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
672 (dest)->inst_left = (dst); \
673 (dest)->inst_right = (src); \
674 (dest)->cil_code = ip; \
675 (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
676 (dest)->backend.memcpy_args->size = (memcpy_size); \
677 (dest)->backend.memcpy_args->align = (memcpy_align); \
680 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
681 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
682 (dest)->inst_left = (dst); \
683 (dest)->inst_imm = (imm); \
684 (dest)->cil_code = ip; \
685 (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
686 (dest)->backend.memcpy_args->size = (memcpy_size); \
687 (dest)->backend.memcpy_args->align = (memcpy_align); \
690 #define NEW_DUMMY_USE(cfg,dest,load) do { \
691 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
692 (dest)->opcode = OP_DUMMY_USE; \
693 (dest)->inst_left = (load); \
696 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
697 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
698 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
699 (dest)->opcode = OP_DUMMY_STORE; \
700 (dest)->klass = (dest)->inst_i0->klass; \
703 #define ADD_BINOP(op) do { \
704 MONO_INST_NEW (cfg, ins, (op)); \
705 ins->cil_code = ip; \
707 ins->inst_i0 = sp [0]; \
708 ins->inst_i1 = sp [1]; \
710 type_from_op (ins); \
714 #define ADD_UNOP(op) do { \
715 MONO_INST_NEW (cfg, ins, (op)); \
716 ins->cil_code = ip; \
718 ins->inst_i0 = sp [0]; \
720 type_from_op (ins); \
724 #define ADD_BINCOND(next_block) do { \
727 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
728 cmp->inst_i0 = sp [0]; \
729 cmp->inst_i1 = sp [1]; \
730 cmp->cil_code = ins->cil_code; \
731 type_from_op (cmp); \
733 ins->inst_i0 = cmp; \
734 MONO_ADD_INS (bblock, ins); \
735 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
736 GET_BBLOCK (cfg, tblock, target); \
737 link_bblock (cfg, bblock, tblock); \
738 ins->inst_true_bb = tblock; \
739 CHECK_BBLOCK (target, ip, tblock); \
740 if ((next_block)) { \
741 link_bblock (cfg, bblock, (next_block)); \
742 ins->inst_false_bb = (next_block); \
743 start_new_bblock = 1; \
745 GET_BBLOCK (cfg, tblock, ip); \
746 link_bblock (cfg, bblock, tblock); \
747 ins->inst_false_bb = tblock; \
748 start_new_bblock = 2; \
752 /* FIXME: handle float, long ... */
753 #define ADD_UNCOND(istrue) do { \
756 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
757 cmp->inst_i0 = sp [0]; \
758 switch (cmp->inst_i0->type) { \
760 cmp->inst_i1 = zero_int64; break; \
762 cmp->inst_i1 = zero_r8; break; \
765 cmp->inst_i1 = zero_ptr; break; \
767 cmp->inst_i1 = zero_obj; break; \
769 cmp->inst_i1 = zero_int32; \
771 cmp->cil_code = ins->cil_code; \
772 type_from_op (cmp); \
774 ins->inst_i0 = cmp; \
775 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ; \
776 MONO_ADD_INS (bblock, ins); \
777 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
778 GET_BBLOCK (cfg, tblock, target); \
779 link_bblock (cfg, bblock, tblock); \
780 ins->inst_true_bb = tblock; \
781 CHECK_BBLOCK (target, ip, tblock); \
782 GET_BBLOCK (cfg, tblock, ip); \
783 link_bblock (cfg, bblock, tblock); \
784 ins->inst_false_bb = tblock; \
785 start_new_bblock = 2; \
788 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
789 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
790 (dest)->opcode = CEE_LDELEMA; \
791 (dest)->inst_left = (sp) [0]; \
792 (dest)->inst_right = (sp) [1]; \
793 (dest)->type = STACK_MP; \
794 (dest)->klass = (k); \
795 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
798 #define NEW_GROUP(cfg,dest,el1,el2) do { \
799 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
800 (dest)->opcode = OP_GROUP; \
801 (dest)->inst_left = (el1); \
802 (dest)->inst_right = (el2); \
807 compare_bblock (gconstpointer a, gconstpointer b)
809 const MonoBasicBlock *b1 = a;
810 const MonoBasicBlock *b2 = b;
812 return b2->cil_code - b1->cil_code;
817 * link_bblock: Links two basic blocks
819 * links two basic blocks in the control flow graph, the 'from'
820 * argument is the starting block and the 'to' argument is the block
821 * the control flow ends to after 'from'.
824 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
826 MonoBasicBlock **newa;
830 if (from->cil_code) {
832 g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
834 g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
837 g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
839 g_print ("edge from entry to exit\n");
843 for (i = 0; i < from->out_count; ++i) {
844 if (to == from->out_bb [i]) {
850 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
851 for (i = 0; i < from->out_count; ++i) {
852 newa [i] = from->out_bb [i];
860 for (i = 0; i < to->in_count; ++i) {
861 if (from == to->in_bb [i]) {
867 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
868 for (i = 0; i < to->in_count; ++i) {
869 newa [i] = to->in_bb [i];
878 * mono_unlink_bblock:
880 * Unlink two basic blocks.
883 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
889 for (i = 0; i < from->out_count; ++i) {
890 if (to == from->out_bb [i]) {
897 for (i = 0; i < from->out_count; ++i) {
898 if (from->out_bb [i] != to)
899 from->out_bb [pos ++] = from->out_bb [i];
901 g_assert (pos == from->out_count - 1);
906 for (i = 0; i < to->in_count; ++i) {
907 if (from == to->in_bb [i]) {
914 for (i = 0; i < to->in_count; ++i) {
915 if (to->in_bb [i] != from)
916 to->in_bb [pos ++] = to->in_bb [i];
918 g_assert (pos == to->in_count - 1);
924 * mono_find_block_region:
926 * We mark each basic block with a region ID. We use that to avoid BB
927 * optimizations when blocks are in different regions.
930 * A region token that encodes where this region is, and information
931 * about the clause owner for this block.
933 * The region encodes the try/catch/filter clause that owns this block
934 * as well as the type. -1 is a special value that represents a block
935 * that is in none of try/catch/filter.
938 mono_find_block_region (MonoCompile *cfg, int offset)
940 MonoMethod *method = cfg->method;
941 MonoMethodHeader *header = mono_method_get_header (method);
942 MonoExceptionClause *clause;
945 /* first search for handlers and filters */
946 for (i = 0; i < header->num_clauses; ++i) {
947 clause = &header->clauses [i];
948 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
949 (offset < (clause->handler_offset)))
950 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
952 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
953 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
954 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
955 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
956 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
957 else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
958 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
962 /* search the try blocks */
963 for (i = 0; i < header->num_clauses; ++i) {
964 clause = &header->clauses [i];
965 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
966 return ((i + 1) << 8) | clause->flags;
973 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
975 MonoMethod *method = cfg->method;
976 MonoMethodHeader *header = mono_method_get_header (method);
977 MonoExceptionClause *clause;
978 MonoBasicBlock *handler;
982 for (i = 0; i < header->num_clauses; ++i) {
983 clause = &header->clauses [i];
984 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) &&
985 (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
986 if (clause->flags == type) {
987 handler = cfg->cil_offset_to_bb [clause->handler_offset];
989 res = g_list_append (res, handler);
997 mono_find_spvar_for_region (MonoCompile *cfg, int region)
999 return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1003 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1007 var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1011 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1012 /* prevent it from being register allocated */
1013 var->flags |= MONO_INST_INDIRECT;
1015 g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1019 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1021 return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1025 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1029 var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1033 var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1034 /* prevent it from being register allocated */
1035 var->flags |= MONO_INST_INDIRECT;
1037 g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1043 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1047 array [*dfn] = start;
1048 /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1049 for (i = 0; i < start->out_count; ++i) {
1050 if (start->out_bb [i]->dfn)
1053 start->out_bb [i]->dfn = *dfn;
1054 start->out_bb [i]->df_parent = start;
1055 array [*dfn] = start->out_bb [i];
1056 df_visit (start->out_bb [i], dfn, array);
1060 static MonoBasicBlock*
1061 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1063 MonoBasicBlock *best = start;
1066 for (i = 0; i < n_bblocks; ++i) {
1068 MonoBasicBlock *bb = bblocks [i];
1070 if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1079 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1084 if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1088 * FIXME: take into account all the details:
1089 * second may have been the target of more than one bblock
1091 second->out_count = first->out_count;
1092 second->out_bb = first->out_bb;
1094 for (i = 0; i < first->out_count; ++i) {
1095 bb = first->out_bb [i];
1096 for (j = 0; j < bb->in_count; ++j) {
1097 if (bb->in_bb [j] == first)
1098 bb->in_bb [j] = second;
1102 first->out_count = 0;
1103 first->out_bb = NULL;
1104 link_bblock (cfg, first, second);
1106 /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1107 MONO_BB_FOR_EACH_INS (first, inst) {
1108 MonoInst *inst_next;
1110 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1111 g_print ("found %p: %s", inst->next->cil_code, code);
1113 if (inst->cil_code >= second->cil_code)
1116 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1120 if (inst_next->cil_code < second->cil_code)
1123 second->ins_list.next = inst->node.next;
1124 second->ins_list.prev = first->ins_list.prev;
1125 inst->node.next = &first->ins_list;
1126 first->ins_list.prev = &inst->node;
1128 second->next_bb = first->next_bb;
1129 first->next_bb = second;
1132 if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1133 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1139 reverse_branch_op (guint32 opcode)
1141 static const int reverse_map [] = {
1142 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1143 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1145 static const int reverse_fmap [] = {
1146 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1147 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1149 static const int reverse_lmap [] = {
1150 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1151 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1153 static const int reverse_imap [] = {
1154 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1155 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1158 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1159 opcode = reverse_map [opcode - CEE_BEQ];
1160 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1161 opcode = reverse_fmap [opcode - OP_FBEQ];
1162 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1163 opcode = reverse_lmap [opcode - OP_LBEQ];
1164 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1165 opcode = reverse_imap [opcode - OP_IBEQ];
1167 g_assert_not_reached ();
1172 #ifdef MONO_ARCH_SOFT_FLOAT
1174 condbr_to_fp_br (int opcode)
1177 case CEE_BEQ: return OP_FBEQ;
1178 case CEE_BGE: return OP_FBGE;
1179 case CEE_BGT: return OP_FBGT;
1180 case CEE_BLE: return OP_FBLE;
1181 case CEE_BLT: return OP_FBLT;
1182 case CEE_BNE_UN: return OP_FBNE_UN;
1183 case CEE_BGE_UN: return OP_FBGE_UN;
1184 case CEE_BGT_UN: return OP_FBGT_UN;
1185 case CEE_BLE_UN: return OP_FBLE_UN;
1186 case CEE_BLT_UN: return OP_FBLT_UN;
1188 g_assert_not_reached ();
1194 * Returns the type used in the eval stack when @type is loaded.
1195 * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1198 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1202 inst->klass = klass = mono_class_from_mono_type (type);
1204 inst->type = STACK_MP;
1209 switch (type->type) {
1210 case MONO_TYPE_VOID:
1211 inst->type = STACK_INV;
1215 case MONO_TYPE_BOOLEAN:
1218 case MONO_TYPE_CHAR:
1221 inst->type = STACK_I4;
1226 case MONO_TYPE_FNPTR:
1227 inst->type = STACK_PTR;
1229 case MONO_TYPE_CLASS:
1230 case MONO_TYPE_STRING:
1231 case MONO_TYPE_OBJECT:
1232 case MONO_TYPE_SZARRAY:
1233 case MONO_TYPE_ARRAY:
1234 inst->type = STACK_OBJ;
1238 inst->type = STACK_I8;
1242 inst->type = STACK_R8;
1244 case MONO_TYPE_VALUETYPE:
1245 if (type->data.klass->enumtype) {
1246 type = type->data.klass->enum_basetype;
1249 inst->klass = klass;
1250 inst->type = STACK_VTYPE;
1253 case MONO_TYPE_TYPEDBYREF:
1254 inst->klass = mono_defaults.typed_reference_class;
1255 inst->type = STACK_VTYPE;
1257 case MONO_TYPE_GENERICINST:
1258 type = &type->data.generic_class->container_class->byval_arg;
1260 case MONO_TYPE_VAR :
1261 case MONO_TYPE_MVAR :
1262 /* FIXME: all the arguments must be references for now,
1263 * later look inside cfg and see if the arg num is
1264 * really a reference
1266 g_assert (cfg->generic_sharing_context);
1267 inst->type = STACK_OBJ;
1270 g_error ("unknown type 0x%02x in eval stack type", type->type);
1275 * The following tables are used to quickly validate the IL code in type_from_op ().
1278 bin_num_table [STACK_MAX] [STACK_MAX] = {
1279 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1280 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1281 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1282 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1283 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV},
1284 {STACK_INV, STACK_MP, STACK_INV, STACK_MP, STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1285 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1286 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1291 STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1294 /* reduce the size of this table */
1296 bin_int_table [STACK_MAX] [STACK_MAX] = {
1297 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1298 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1299 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1300 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1301 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1302 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1303 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1304 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1308 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1309 /* Inv i L p F & O vt */
1311 {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1312 {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1313 {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1314 {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1315 {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1316 {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1317 {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1320 /* reduce the size of this table */
1322 shift_table [STACK_MAX] [STACK_MAX] = {
1323 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1324 {STACK_INV, STACK_I4, STACK_INV, STACK_I4, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1325 {STACK_INV, STACK_I8, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1326 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1327 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1328 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1329 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1330 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1334 * Tables to map from the non-specific opcode to the matching
1335 * type-specific opcode.
1337 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1338 static const guint16
1339 binops_op_map [STACK_MAX] = {
1340 0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1343 /* handles from CEE_NEG to CEE_CONV_U8 */
1344 static const guint16
1345 unops_op_map [STACK_MAX] = {
1346 0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1349 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1350 static const guint16
1351 ovfops_op_map [STACK_MAX] = {
1352 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
1355 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1356 static const guint16
1357 ovf2ops_op_map [STACK_MAX] = {
1358 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
1361 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1362 static const guint16
1363 ovf3ops_op_map [STACK_MAX] = {
1364 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
1367 /* handles from CEE_CEQ to CEE_CLT_UN */
1368 static const guint16
1369 ceqops_op_map [STACK_MAX] = {
1370 0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1374 * Sets ins->type (the type on the eval stack) according to the
1375 * type of the opcode and the arguments to it.
1376 * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1378 * FIXME: this function sets ins->type unconditionally in some cases, but
1379 * it should set it to invalid for some types (a conv.x on an object)
1382 type_from_op (MonoInst *ins) {
1383 switch (ins->opcode) {
1390 /* FIXME: check unverifiable args for STACK_MP */
1391 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1392 ins->opcode += binops_op_map [ins->type];
1399 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1400 ins->opcode += binops_op_map [ins->type];
1405 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1406 ins->opcode += binops_op_map [ins->type];
1410 /* FIXME: handle some specifics with ins->next->type */
1411 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1412 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))))
1413 ins->opcode = OP_LCOMPARE;
1416 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1417 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1424 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1425 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1429 ins->type = neg_table [ins->inst_i0->type];
1430 ins->opcode += unops_op_map [ins->type];
1433 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1434 ins->type = ins->inst_i0->type;
1436 ins->type = STACK_INV;
1437 ins->opcode += unops_op_map [ins->type];
1443 ins->type = STACK_I4;
1444 ins->opcode += unops_op_map [ins->inst_i0->type];
1447 ins->type = STACK_R8;
1448 switch (ins->inst_i0->type) {
1453 ins->opcode = OP_LCONV_TO_R_UN;
1457 case CEE_CONV_OVF_I1:
1458 case CEE_CONV_OVF_U1:
1459 case CEE_CONV_OVF_I2:
1460 case CEE_CONV_OVF_U2:
1461 case CEE_CONV_OVF_I4:
1462 case CEE_CONV_OVF_U4:
1463 ins->type = STACK_I4;
1464 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1466 case CEE_CONV_OVF_I_UN:
1467 case CEE_CONV_OVF_U_UN:
1468 ins->type = STACK_PTR;
1469 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1471 case CEE_CONV_OVF_I1_UN:
1472 case CEE_CONV_OVF_I2_UN:
1473 case CEE_CONV_OVF_I4_UN:
1474 case CEE_CONV_OVF_U1_UN:
1475 case CEE_CONV_OVF_U2_UN:
1476 case CEE_CONV_OVF_U4_UN:
1477 ins->type = STACK_I4;
1478 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1481 ins->type = STACK_PTR;
1482 switch (ins->inst_i0->type) {
1487 #if SIZEOF_VOID_P == 8
1488 ins->opcode = OP_LCONV_TO_U;
1492 ins->opcode = OP_LCONV_TO_U;
1495 ins->opcode = OP_FCONV_TO_U;
1501 ins->type = STACK_I8;
1502 ins->opcode += unops_op_map [ins->inst_i0->type];
1504 case CEE_CONV_OVF_I8:
1505 case CEE_CONV_OVF_U8:
1506 ins->type = STACK_I8;
1507 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1509 case CEE_CONV_OVF_U8_UN:
1510 case CEE_CONV_OVF_I8_UN:
1511 ins->type = STACK_I8;
1512 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1516 ins->type = STACK_R8;
1517 ins->opcode += unops_op_map [ins->inst_i0->type];
1520 ins->type = STACK_R8;
1524 ins->type = STACK_I4;
1525 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1528 case CEE_CONV_OVF_I:
1529 case CEE_CONV_OVF_U:
1530 ins->type = STACK_PTR;
1531 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1534 case CEE_ADD_OVF_UN:
1536 case CEE_MUL_OVF_UN:
1538 case CEE_SUB_OVF_UN:
1539 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1540 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1541 if (ins->type == STACK_R8)
1542 ins->type = STACK_INV;
1545 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1552 STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1555 /* map ldelem.x to the matching ldind.x opcode */
1557 ldelem_to_ldind [] = {
1571 /* map stelem.x to the matching stind.x opcode */
1573 stelem_to_stind [] = {
1587 param_table [STACK_MAX] [STACK_MAX] = {
1592 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1596 switch (args->type) {
1606 for (i = 0; i < sig->param_count; ++i) {
1607 switch (args [i].type) {
1611 if (!sig->params [i]->byref)
1615 if (sig->params [i]->byref)
1617 switch (sig->params [i]->type) {
1618 case MONO_TYPE_CLASS:
1619 case MONO_TYPE_STRING:
1620 case MONO_TYPE_OBJECT:
1621 case MONO_TYPE_SZARRAY:
1622 case MONO_TYPE_ARRAY:
1629 if (sig->params [i]->byref)
1631 if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1640 /*if (!param_table [args [i].type] [sig->params [i]->type])
1648 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1650 if (cfg->generic_sharing_context && !type->byref) {
1651 /* FIXME: all the arguments must be references for now,
1652 * later look inside cfg and see if the arg num is
1653 * really a reference
1655 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1656 return CEE_LDIND_REF;
1658 return mono_type_to_ldind (type);
1662 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1664 if (cfg->generic_sharing_context && !type->byref) {
1665 /* FIXME: all the arguments must be references for now,
1666 * later look inside cfg and see if the arg num is
1667 * really a reference
1669 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1670 return CEE_STIND_REF;
1672 return mono_type_to_stind (type);
1676 mono_op_imm_to_op (int opcode)
1690 #if SIZEOF_VOID_P == 4
1715 case OP_ISHR_UN_IMM:
1717 case OP_LSHR_UN_IMM:
1721 case OP_IDIV_UN_IMM:
1723 case OP_IREM_UN_IMM:
1728 #if SIZEOF_VOID_P == 4
1734 #if SIZEOF_VOID_P == 4
1751 case OP_COMPARE_IMM:
1753 case OP_ICOMPARE_IMM:
1756 printf ("%s\n", mono_inst_name (opcode));
1757 g_assert_not_reached ();
1762 * When we need a pointer to the current domain many times in a method, we
1763 * call mono_domain_get() once and we store the result in a local variable.
1764 * This function returns the variable that represents the MonoDomain*.
1766 inline static MonoInst *
1767 mono_get_domainvar (MonoCompile *cfg)
1769 if (!cfg->domainvar)
1770 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1771 return cfg->domainvar;
1775 * The got_var contains the address of the Global Offset Table when AOT
1778 inline static MonoInst *
1779 mono_get_got_var (MonoCompile *cfg)
1781 #ifdef MONO_ARCH_NEED_GOT_VAR
1782 if (!cfg->compile_aot)
1784 if (!cfg->got_var) {
1785 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1787 return cfg->got_var;
1794 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1797 int num = cfg->num_varinfo;
1799 if ((num + 1) >= cfg->varinfo_count) {
1800 int orig_count = cfg->varinfo_count;
1801 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1802 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1803 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1804 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1807 /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1808 mono_jit_stats.allocate_var++;
1810 MONO_INST_NEW (cfg, inst, opcode);
1811 inst->inst_c0 = num;
1812 inst->inst_vtype = type;
1813 inst->klass = mono_class_from_mono_type (type);
1814 /* if set to 1 the variable is native */
1815 inst->backend.is_pinvoke = 0;
1817 cfg->varinfo [num] = inst;
1819 MONO_INIT_VARINFO (&cfg->vars [num], num);
1822 if (cfg->verbose_level > 2)
1823 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1828 * Transform a MonoInst into a load from the variable of index var_index.
1831 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1832 memset (dest, 0, sizeof (MonoInst));
1833 dest->ssa_op = MONO_SSA_LOAD;
1834 dest->inst_i0 = cfg->varinfo [var_index];
1835 dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1836 type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1837 dest->klass = dest->inst_i0->klass;
1841 * Create a MonoInst that is a load from the variable of index var_index.
1844 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1846 NEW_TEMPLOAD (cfg,dest,var_index);
1851 * Create a MonoInst that is a store of the given value into the variable of index var_index.
1854 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1856 NEW_TEMPSTORE (cfg, dest, var_index, value);
1861 type_from_stack_type (MonoInst *ins) {
1862 switch (ins->type) {
1863 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1864 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1865 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1866 case STACK_R8: return &mono_defaults.double_class->byval_arg;
1869 * this if used to be commented without any specific reason, but
1870 * it breaks #80235 when commented
1873 return &ins->klass->this_arg;
1875 return &mono_defaults.object_class->this_arg;
1877 /* ins->klass may not be set for ldnull.
1878 * Also, if we have a boxed valuetype, we want an object lass,
1879 * not the valuetype class
1881 if (ins->klass && !ins->klass->valuetype)
1882 return &ins->klass->byval_arg;
1883 return &mono_defaults.object_class->byval_arg;
1884 case STACK_VTYPE: return &ins->klass->byval_arg;
1886 g_error ("stack type %d to montype not handled\n", ins->type);
1892 mono_type_from_stack_type (MonoInst *ins) {
1893 return type_from_stack_type (ins);
1897 array_access_to_klass (int opcode, MonoInst *array_obj)
1901 return mono_defaults.byte_class;
1903 return mono_defaults.uint16_class;
1906 return mono_defaults.int_class;
1909 return mono_defaults.sbyte_class;
1912 return mono_defaults.int16_class;
1915 return mono_defaults.int32_class;
1917 return mono_defaults.uint32_class;
1920 return mono_defaults.int64_class;
1923 return mono_defaults.single_class;
1926 return mono_defaults.double_class;
1927 case CEE_LDELEM_REF:
1928 case CEE_STELEM_REF: {
1929 MonoClass *klass = array_obj->klass;
1930 /* FIXME: add assert */
1931 if (klass && klass->rank)
1932 return klass->element_class;
1933 return mono_defaults.object_class;
1936 g_assert_not_reached ();
1942 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1944 MonoInst *last = mono_inst_list_last (&bb->ins_list);
1946 if (last && ((last->opcode >= CEE_BEQ &&
1947 last->opcode <= CEE_BLT_UN) ||
1948 last->opcode == OP_BR ||
1949 last->opcode == OP_SWITCH)) {
1950 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
1952 MONO_ADD_INS (bb, inst);
1957 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1959 MonoInst *inst, *load;
1961 NEW_TEMPLOAD (cfg, load, src);
1963 NEW_TEMPSTORE (cfg, inst, dest, load);
1964 /* FIXME: handle CEE_STIND_R4 */
1965 if (inst->opcode == CEE_STOBJ) {
1966 NEW_TEMPLOADA (cfg, inst, dest);
1967 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
1969 inst->cil_code = NULL;
1970 mono_add_ins_to_end (bb, inst);
1977 * Merge stack state between two basic blocks according to Ecma 335, Partition III,
1978 * section 1.8.1.1. Store the resulting stack state into stack_2.
1979 * Returns: TRUE, if verification succeeds, FALSE otherwise.
1980 * FIXME: We should store the stack state in a dedicated structure instead of in
1984 merge_stacks (MonoCompile *cfg, MonoStackSlot *state_1, MonoStackSlot *state_2, guint32 size)
1988 if (cfg->dont_verify_stack_merge)
1991 /* FIXME: Implement all checks from the spec */
1993 for (i = 0; i < size; ++i) {
1994 MonoStackSlot *slot1 = &state_1 [i];
1995 MonoStackSlot *slot2 = &state_2 [i];
1997 if (slot1->type != slot2->type)
2000 switch (slot1->type) {
2002 /* FIXME: Perform merge ? */
2003 /* klass == NULL means a native int */
2004 if (slot1->klass && slot2->klass) {
2005 if (slot1->klass != slot2->klass)
2010 /* FIXME: Change this to an assert and fix the JIT to allways fill this */
2011 if (slot1->klass && slot2->klass) {
2012 if (slot1->klass != slot2->klass)
2017 MonoClass *klass1 = slot1->klass;
2018 MonoClass *klass2 = slot2->klass;
2021 /* slot1 is ldnull */
2022 } else if (!klass2) {
2023 /* slot2 is ldnull */
2024 slot2->klass = slot1->klass;
2035 * This function is called to handle items that are left on the evaluation stack
2036 * at basic block boundaries. What happens is that we save the values to local variables
2037 * and we reload them later when first entering the target basic block (with the
2038 * handle_loaded_temps () function).
2039 * It is also used to handle items on the stack in store opcodes, since it is
2040 * possible that the variable to be stored into is already on the stack, in
2041 * which case its old value should be used.
2042 * A single joint point will use the same variables (stored in the array bb->out_stack or
2043 * bb->in_stack, if the basic block is before or after the joint point).
2044 * If the stack merge fails at a join point, cfg->unverifiable is set.
2047 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
2049 MonoBasicBlock *outb;
2050 MonoInst *inst, **locals;
2051 MonoStackSlot *stack_state;
2056 if (cfg->verbose_level > 3)
2057 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2059 stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2060 for (i = 0; i < count; ++i) {
2061 stack_state [i].type = sp [i]->type;
2062 stack_state [i].klass = sp [i]->klass;
2064 /* Check that instructions other than ldnull have ins->klass set */
2065 if (!cfg->dont_verify_stack_merge && (sp [i]->type == STACK_OBJ) && !((sp [i]->opcode == OP_PCONST) && sp [i]->inst_c0 == 0))
2066 g_assert (sp [i]->klass);
2069 /* Perform verification and stack state merge */
2070 for (i = 0; i < bb->out_count; ++i) {
2071 outb = bb->out_bb [i];
2073 /* exception handlers are linked, but they should not be considered for stack args */
2074 if (outb->flags & BB_EXCEPTION_HANDLER)
2076 if (outb->stack_state) {
2079 if (count != outb->in_scount) {
2080 cfg->unverifiable = TRUE;
2083 verified = merge_stacks (cfg, stack_state, outb->stack_state, count);
2085 cfg->unverifiable = TRUE;
2089 if (cfg->verbose_level > 3) {
2092 for (j = 0; j < count; ++j)
2093 printf ("\tStack state of BB%d, slot %d=%d\n", outb->block_num, j, outb->stack_state [j].type);
2096 /* Make a copy of the stack state */
2097 outb->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2098 memcpy (outb->stack_state, stack_state, sizeof (MonoStackSlot) * count);
2102 if (!bb->out_scount) {
2103 bb->out_scount = count;
2104 //g_print ("bblock %d has out:", bb->block_num);
2106 for (i = 0; i < bb->out_count; ++i) {
2107 outb = bb->out_bb [i];
2108 /* exception handlers are linked, but they should not be considered for stack args */
2109 if (outb->flags & BB_EXCEPTION_HANDLER)
2111 //g_print (" %d", outb->block_num);
2112 if (outb->in_stack) {
2114 bb->out_stack = outb->in_stack;
2120 bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2121 for (i = 0; i < count; ++i) {
2123 * try to reuse temps already allocated for this purpouse, if they occupy the same
2124 * stack slot and if they are of the same type.
2125 * This won't cause conflicts since if 'local' is used to
2126 * store one of the values in the in_stack of a bblock, then
2127 * the same variable will be used for the same outgoing stack
2129 * This doesn't work when inlining methods, since the bblocks
2130 * in the inlined methods do not inherit their in_stack from
2131 * the bblock they are inlined to. See bug #58863 for an
2133 * This hack is disabled since it also prevents proper tracking of types.
2136 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2138 if (cfg->inlined_method)
2139 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2141 bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2147 for (i = 0; i < bb->out_count; ++i) {
2148 outb = bb->out_bb [i];
2149 /* exception handlers are linked, but they should not be considered for stack args */
2150 if (outb->flags & BB_EXCEPTION_HANDLER)
2152 if (outb->in_scount) {
2153 if (outb->in_scount != bb->out_scount)
2155 continue; /* check they are the same locals */
2157 outb->in_scount = count;
2158 outb->in_stack = bb->out_stack;
2161 locals = bb->out_stack;
2162 for (i = 0; i < count; ++i) {
2163 /* add store ops at the end of the bb, before the branch */
2164 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2165 if (inst->opcode == CEE_STOBJ) {
2166 NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2167 handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2169 inst->cil_code = sp [i]->cil_code;
2170 mono_add_ins_to_end (bb, inst);
2172 if (cfg->verbose_level > 3)
2173 g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2177 * It is possible that the out bblocks already have in_stack assigned, and
2178 * the in_stacks differ. In this case, we will store to all the different
2185 /* Find a bblock which has a different in_stack */
2187 while (bindex < bb->out_count) {
2188 outb = bb->out_bb [bindex];
2189 /* exception handlers are linked, but they should not be considered for stack args */
2190 if (outb->flags & BB_EXCEPTION_HANDLER) {
2194 if (outb->in_stack != locals) {
2196 * Instead of storing sp [i] to locals [i], we need to store
2197 * locals [i] to <new locals>[i], since the sp [i] tree can't
2198 * be shared between trees.
2200 for (i = 0; i < count; ++i)
2201 mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2202 locals = outb->in_stack;
2214 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2217 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2220 type = mini_get_basic_type_from_generic (gsctx, type);
2221 switch (type->type) {
2222 case MONO_TYPE_VOID:
2223 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2226 case MONO_TYPE_BOOLEAN:
2229 case MONO_TYPE_CHAR:
2232 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2236 case MONO_TYPE_FNPTR:
2237 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2238 case MONO_TYPE_CLASS:
2239 case MONO_TYPE_STRING:
2240 case MONO_TYPE_OBJECT:
2241 case MONO_TYPE_SZARRAY:
2242 case MONO_TYPE_ARRAY:
2243 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2246 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2249 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2250 case MONO_TYPE_VALUETYPE:
2251 if (type->data.klass->enumtype) {
2252 type = type->data.klass->enum_basetype;
2255 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2256 case MONO_TYPE_TYPEDBYREF:
2257 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2258 case MONO_TYPE_GENERICINST:
2259 type = &type->data.generic_class->container_class->byval_arg;
2262 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2268 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2270 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2271 MonoJumpInfoBBTable *table;
2273 table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2275 table->table_size = num_blocks;
2277 ji->ip.label = label;
2278 ji->type = MONO_PATCH_INFO_SWITCH;
2279 ji->data.table = table;
2280 ji->next = cfg->patch_info;
2281 cfg->patch_info = ji;
2285 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2287 if (cfg->compile_aot) {
2288 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2289 jump_info_token->image = image;
2290 jump_info_token->token = token;
2291 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2296 * When we add a tree of instructions, we need to ensure the instructions currently
2297 * on the stack are executed before (like, if we load a value from a local).
2298 * We ensure this by saving the currently loaded values to temps and rewriting the
2299 * instructions to load the values.
2300 * This is not done for opcodes that terminate a basic block (because it's handled already
2301 * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2304 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2306 MonoInst *load, *store, *temp, *ins;
2308 while (stack < sp) {
2310 /* handle also other constants */
2311 if ((ins->opcode != OP_ICONST) &&
2312 /* temps never get written to again, so we can safely avoid duplicating them */
2313 !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2314 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2315 temp->flags |= MONO_INST_IS_TEMP;
2316 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2317 store->cil_code = ins->cil_code;
2318 if (store->opcode == CEE_STOBJ) {
2319 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2320 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2322 MONO_ADD_INS (bblock, store);
2323 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2324 load->cil_code = ins->cil_code;
2332 * target_type_is_incompatible:
2333 * @cfg: MonoCompile context
2335 * Check that the item @arg on the evaluation stack can be stored
2336 * in the target type (can be a local, or field, etc).
2337 * The cfg arg can be used to check if we need verification or just
2340 * Returns: non-0 value if arg can't be stored on a target.
2343 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2345 MonoType *simple_type;
2348 if (target->byref) {
2349 /* FIXME: check that the pointed to types match */
2350 if (arg->type == STACK_MP)
2351 return arg->klass != mono_class_from_mono_type (target);
2352 if (arg->type == STACK_PTR)
2356 simple_type = mono_type_get_underlying_type (target);
2357 switch (simple_type->type) {
2358 case MONO_TYPE_VOID:
2362 case MONO_TYPE_BOOLEAN:
2365 case MONO_TYPE_CHAR:
2368 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2372 /* STACK_MP is needed when setting pinned locals */
2373 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2378 case MONO_TYPE_FNPTR:
2379 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2382 case MONO_TYPE_OBJECT:
2383 if (arg->type != STACK_OBJ)
2386 case MONO_TYPE_STRING:
2387 if (arg->type != STACK_OBJ)
2389 /* ldnull has arg->klass unset */
2390 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2395 case MONO_TYPE_CLASS:
2396 case MONO_TYPE_SZARRAY:
2397 case MONO_TYPE_ARRAY:
2398 if (arg->type != STACK_OBJ)
2400 /* FIXME: check type compatibility */
2404 if (arg->type != STACK_I8)
2409 if (arg->type != STACK_R8)
2412 case MONO_TYPE_VALUETYPE:
2413 if (arg->type != STACK_VTYPE)
2415 klass = mono_class_from_mono_type (simple_type);
2416 if (klass != arg->klass)
2419 case MONO_TYPE_TYPEDBYREF:
2420 if (arg->type != STACK_VTYPE)
2422 klass = mono_class_from_mono_type (simple_type);
2423 if (klass != arg->klass)
2426 case MONO_TYPE_GENERICINST:
2427 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2428 klass = mono_class_from_mono_type (simple_type);
2429 if (klass->enumtype)
2430 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2431 if (arg->type != STACK_VTYPE)
2433 if (klass != arg->klass)
2437 if (arg->type != STACK_OBJ)
2439 /* FIXME: check type compatibility */
2443 case MONO_TYPE_MVAR:
2444 /* FIXME: all the arguments must be references for now,
2445 * later look inside cfg and see if the arg num is
2446 * really a reference
2448 g_assert (cfg->generic_sharing_context);
2449 if (arg->type != STACK_OBJ)
2453 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2459 * Prepare arguments for passing to a function call.
2460 * Return a non-zero value if the arguments can't be passed to the given
2462 * The type checks are not yet complete and some conversions may need
2463 * casts on 32 or 64 bit architectures.
2465 * FIXME: implement this using target_type_is_incompatible ()
2468 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2470 MonoType *simple_type;
2474 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2478 for (i = 0; i < sig->param_count; ++i) {
2479 if (sig->params [i]->byref) {
2480 if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2484 simple_type = sig->params [i];
2485 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2487 switch (simple_type->type) {
2488 case MONO_TYPE_VOID:
2493 case MONO_TYPE_BOOLEAN:
2496 case MONO_TYPE_CHAR:
2499 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2505 case MONO_TYPE_FNPTR:
2506 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2509 case MONO_TYPE_CLASS:
2510 case MONO_TYPE_STRING:
2511 case MONO_TYPE_OBJECT:
2512 case MONO_TYPE_SZARRAY:
2513 case MONO_TYPE_ARRAY:
2514 if (args [i]->type != STACK_OBJ)
2519 if (args [i]->type != STACK_I8)
2524 if (args [i]->type != STACK_R8)
2527 case MONO_TYPE_VALUETYPE:
2528 if (simple_type->data.klass->enumtype) {
2529 simple_type = simple_type->data.klass->enum_basetype;
2532 if (args [i]->type != STACK_VTYPE)
2535 case MONO_TYPE_TYPEDBYREF:
2536 if (args [i]->type != STACK_VTYPE)
2539 case MONO_TYPE_GENERICINST:
2540 simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2544 g_error ("unknown type 0x%02x in check_call_signature",
2552 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object,
2553 const guint8 *ip, gboolean to_end)
2555 MonoInst *temp, *store, *ins = (MonoInst*)call;
2556 MonoType *ret = sig->ret;
2558 if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2560 call->inst.type = STACK_OBJ;
2561 call->inst.opcode = OP_CALL;
2562 temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2564 type_to_eval_stack_type (cfg, ret, ins);
2565 temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2568 temp->flags |= MONO_INST_IS_TEMP;
2570 if (MONO_TYPE_ISSTRUCT (ret)) {
2571 MonoInst *loada, *dummy_store;
2574 * Emit a dummy store to the local holding the result so the
2575 * liveness info remains correct.
2577 NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2579 mono_add_ins_to_end (bblock, dummy_store);
2581 MONO_ADD_INS (bblock, dummy_store);
2583 /* we use this to allocate native sized structs */
2584 temp->backend.is_pinvoke = sig->pinvoke;
2586 NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2587 if (call->inst.opcode == OP_VCALL)
2588 ins->inst_left = loada;
2590 ins->inst_right = loada; /* a virtual or indirect call */
2593 mono_add_ins_to_end (bblock, ins);
2595 MONO_ADD_INS (bblock, ins);
2597 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2598 store->cil_code = ip;
2600 #ifdef MONO_ARCH_SOFT_FLOAT
2601 if (store->opcode == CEE_STIND_R4) {
2602 /*FIXME implement proper support for to_end*/
2604 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2605 handle_store_float (cfg, bblock, store, ins, ip);
2609 mono_add_ins_to_end (bblock, store);
2611 MONO_ADD_INS (bblock, store);
2613 return temp->inst_c0;
2616 mono_add_ins_to_end (bblock, ins);
2618 MONO_ADD_INS (bblock, ins);
2623 inline static MonoCallInst *
2624 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2625 MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2630 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2632 #ifdef MONO_ARCH_SOFT_FLOAT
2633 /* we need to convert the r4 value to an int value */
2636 for (i = 0; i < sig->param_count; ++i) {
2637 if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2638 MonoInst *iargs [1];
2640 iargs [0] = args [i + sig->hasthis];
2642 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2643 NEW_TEMPLOAD (cfg, arg, temp);
2644 args [i + sig->hasthis] = arg;
2650 call->inst.cil_code = ip;
2652 call->signature = sig;
2653 call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2654 type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2656 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2660 mono_add_ins_to_end (bblock, arg);
2662 MONO_ADD_INS (bblock, arg);
2667 inline static MonoCallInst*
2668 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2669 MonoInst **args, MonoInst *addr, const guint8 *ip)
2671 MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2673 call->inst.inst_i0 = addr;
2679 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2680 MonoInst **args, MonoInst *addr, const guint8 *ip)
2682 MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2684 return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2687 static MonoCallInst*
2688 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2689 MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2691 gboolean virtual = this != NULL;
2694 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2696 if (this && sig->hasthis &&
2697 (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2698 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2699 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2701 call->method = method;
2703 call->inst.flags |= MONO_INST_HAS_METHOD;
2704 call->inst.inst_left = this;
2706 if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2707 /* Needed by the code generated in inssel.brg */
2708 mono_get_got_var (cfg);
2713 static MonoCallInst*
2714 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2715 MonoInst **args, const guint8 *ip, MonoInst *this)
2717 return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2721 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2722 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2724 MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2726 return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2730 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2731 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2732 gboolean ret_object, gboolean to_end)
2734 MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2736 return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2740 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2741 MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2747 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2750 return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2754 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2756 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2759 g_warning ("unregistered JIT ICall");
2760 g_assert_not_reached ();
2763 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2767 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2769 MonoInst *ins, *temp = NULL, *store, *load;
2770 MonoInstList *head, *list;
2774 //g_print ("emulating: ");
2775 //mono_print_tree_nl (tree);
2776 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2777 ins = (MonoInst*)call;
2778 MONO_INST_LIST_INIT (&ins->node);
2780 call->inst.cil_code = tree->cil_code;
2782 call->signature = info->sig;
2784 call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2786 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2787 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2788 temp->flags |= MONO_INST_IS_TEMP;
2789 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2790 MONO_INST_LIST_INIT (&store->node);
2791 /* FIXME: handle CEE_STIND_R4 */
2792 store->cil_code = tree->cil_code;
2797 nargs = info->sig->param_count + info->sig->hasthis;
2800 MONO_INST_LIST_ADD_TAIL (&store->node,
2802 list = &call->out_args;
2804 list = &store->node;
2807 if (cfg->prev_ins) {
2809 * This assumes that that in a tree, emulate_opcode is called for a
2810 * node before it is called for its children. dec_foreach needs to
2811 * take this into account.
2813 head = &cfg->prev_ins->node;
2815 head = &cfg->cbb->ins_list;
2818 MONO_INST_LIST_SPLICE_INIT (list, head);
2820 call->fptr = mono_icall_get_wrapper (info);
2822 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2823 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2829 * This entry point could be used later for arbitrary method
2833 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2834 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2837 if (method->klass == mono_defaults.string_class) {
2838 /* managed string allocation support */
2839 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2840 MonoInst *iargs [2];
2841 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2842 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2845 NEW_VTABLECONST (cfg, iargs [0], vtable);
2846 iargs [1] = args [0];
2847 *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2854 static MonoMethodSignature *
2855 mono_get_array_new_va_signature (int arity)
2857 static GHashTable *sighash = NULL;
2858 MonoMethodSignature *res;
2863 sighash = g_hash_table_new (NULL, NULL);
2865 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2870 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2873 #ifdef MONO_ARCH_VARARG_ICALLS
2874 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2875 res->call_convention = MONO_CALL_VARARG;
2878 #ifdef PLATFORM_WIN32
2879 res->call_convention = MONO_CALL_C;
2882 res->params [0] = &mono_defaults.int_class->byval_arg;
2883 for (i = 0; i < arity; i++)
2884 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2886 res->ret = &mono_defaults.int_class->byval_arg;
2888 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2894 #ifdef MONO_ARCH_SOFT_FLOAT
2896 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
2898 MonoInst *iargs [2];
2902 mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
2906 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
2908 MonoInst *iargs [1];
2911 return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
2914 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2915 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) { \
2917 NEW_LOCLOADA (cfg, (ins), (idx)); \
2918 temp = handle_load_float (cfg, bblock, (ins), (ip)); \
2919 NEW_TEMPLOAD (cfg, (ins), temp); \
2922 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2923 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) { \
2925 NEW_LOCLOADA (cfg, (ins), (idx)); \
2926 handle_store_float (cfg, bblock, (ins), *sp, (ip)); \
2927 MONO_INST_NEW (cfg, (ins), OP_NOP); \
2930 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2931 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2933 NEW_ARGLOADA (cfg, (ins), (idx)); \
2934 temp = handle_load_float (cfg, bblock, (ins), (ip)); \
2935 NEW_TEMPLOAD (cfg, (ins), temp); \
2938 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2939 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2941 NEW_ARGLOADA (cfg, (ins), (idx)); \
2942 handle_store_float (cfg, bblock, (ins), *sp, (ip)); \
2943 MONO_INST_NEW (cfg, (ins), OP_NOP); \
2947 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2948 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2949 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
2950 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
2954 get_memcpy_method (void)
2956 static MonoMethod *memcpy_method = NULL;
2957 if (!memcpy_method) {
2958 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2960 g_error ("Old corlib found. Install a new one");
2962 return memcpy_method;
2966 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
2967 MonoInst *iargs [3];
2970 MonoMethod *memcpy_method;
2974 * This check breaks with spilled vars... need to handle it during verification anyway.
2975 * g_assert (klass && klass == src->klass && klass == dest->klass);
2979 n = mono_class_native_size (klass, &align);
2981 n = mono_class_value_size (klass, &align);
2983 #if HAVE_WRITE_BARRIERS
2984 /* if native is true there should be no references in the struct */
2985 if (write_barrier && klass->has_references && !native) {
2988 NEW_PCONST (cfg, iargs [2], klass);
2990 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
2995 /* FIXME: add write barrier handling */
2996 if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
2998 if (dest->opcode == OP_LDADDR) {
2999 /* Keep liveness info correct */
3000 NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3001 MONO_ADD_INS (bblock, inst);
3003 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3004 MONO_ADD_INS (bblock, inst);
3009 NEW_ICONST (cfg, iargs [2], n);
3011 memcpy_method = get_memcpy_method ();
3012 mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3016 get_memset_method (void)
3018 static MonoMethod *memset_method = NULL;
3019 if (!memset_method) {
3020 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3022 g_error ("Old corlib found. Install a new one");
3024 return memset_method;
3028 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3030 MonoInst *iargs [3];
3031 MonoInst *ins, *zero_int32;
3034 MonoMethod *memset_method;
3036 NEW_ICONST (cfg, zero_int32, 0);
3038 mono_class_init (klass);
3039 n = mono_class_value_size (klass, &align);
3040 MONO_INST_NEW (cfg, ins, 0);
3042 ins->inst_left = dest;
3043 ins->inst_right = zero_int32;
3045 ins->opcode = CEE_STIND_I1;
3046 MONO_ADD_INS (bblock, ins);
3047 } else if ((n == 2) && (align >= 2)) {
3048 ins->opcode = CEE_STIND_I2;
3049 MONO_ADD_INS (bblock, ins);
3050 } else if ((n == 2) && (align >= 4)) {
3051 ins->opcode = CEE_STIND_I4;
3052 MONO_ADD_INS (bblock, ins);
3053 } else if (n <= sizeof (gpointer) * 5) {
3054 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3055 MONO_ADD_INS (bblock, ins);
3057 memset_method = get_memset_method ();
3058 handle_loaded_temps (cfg, bblock, stack_start, sp);
3060 NEW_ICONST (cfg, iargs [1], 0);
3061 NEW_ICONST (cfg, iargs [2], n);
3062 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3067 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3069 MonoInst *iargs [2];
3072 if (cfg->opt & MONO_OPT_SHARED) {
3073 NEW_DOMAINCONST (cfg, iargs [0]);
3074 NEW_CLASSCONST (cfg, iargs [1], klass);
3076 alloc_ftn = mono_object_new;
3077 } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3078 /* This happens often in argument checking code, eg. throw new FooException... */
3079 /* Avoid relocations by calling a helper function specialized to mscorlib */
3080 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3081 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3083 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3084 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3087 if (managed_alloc) {
3088 NEW_VTABLECONST (cfg, iargs [0], vtable);
3089 return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3091 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3093 guint32 lw = vtable->klass->instance_size;
3094 lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3095 NEW_ICONST (cfg, iargs [0], lw);
3096 NEW_VTABLECONST (cfg, iargs [1], vtable);
3099 NEW_VTABLECONST (cfg, iargs [0], vtable);
3102 return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3106 * Handles unbox of a Nullable<T>, returning a temp variable
3107 * where the result is stored
3110 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
3112 MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3113 return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3120 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3122 MonoInst *dest, *vtoffset, *add, *vstore;
3125 if (mono_class_is_nullable (klass)) {
3126 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3127 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3128 NEW_TEMPLOAD (cfg, dest, temp);
3133 temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3134 NEW_TEMPLOAD (cfg, dest, temp);
3135 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3136 MONO_INST_NEW (cfg, add, OP_PADD);
3137 add->inst_left = dest;
3138 add->inst_right = vtoffset;
3141 MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3142 vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3143 vstore->cil_code = ip;
3144 vstore->inst_left = add;
3145 vstore->inst_right = val;
3147 #ifdef MONO_ARCH_SOFT_FLOAT
3148 if (vstore->opcode == CEE_STIND_R4) {
3149 handle_store_float (cfg, bblock, add, val, ip);
3152 if (vstore->opcode == CEE_STOBJ) {
3153 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3155 MONO_ADD_INS (bblock, vstore);
3157 NEW_TEMPLOAD (cfg, dest, temp);
3162 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3164 gpointer *trampoline;
3165 MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3168 temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3170 /* Inline the contents of mono_delegate_ctor */
3172 /* Set target field */
3173 /* Optimize away setting of NULL target */
3174 if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3175 NEW_TEMPLOAD (cfg, obj, temp);
3176 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3177 MONO_INST_NEW (cfg, ins, OP_PADD);
3179 ins->inst_left = obj;
3180 ins->inst_right = offset_ins;
3182 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3183 store->cil_code = ip;
3184 store->inst_left = ins;
3185 store->inst_right = target;
3186 mono_bblock_add_inst (bblock, store);
3189 /* Set method field */
3190 NEW_TEMPLOAD (cfg, obj, temp);
3191 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3192 MONO_INST_NEW (cfg, ins, OP_PADD);
3194 ins->inst_left = obj;
3195 ins->inst_right = offset_ins;
3197 NEW_METHODCONST (cfg, method_ins, method);
3199 MONO_INST_NEW (cfg, store, CEE_STIND_I);
3200 store->cil_code = ip;
3201 store->inst_left = ins;
3202 store->inst_right = method_ins;
3203 mono_bblock_add_inst (bblock, store);
3205 /* Set invoke_impl field */
3206 NEW_TEMPLOAD (cfg, obj, temp);
3207 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3208 MONO_INST_NEW (cfg, ins, OP_PADD);
3210 ins->inst_left = obj;
3211 ins->inst_right = offset_ins;
3213 trampoline = mono_create_delegate_trampoline (klass);
3214 NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3216 MONO_INST_NEW (cfg, store, CEE_STIND_I);
3217 store->cil_code = ip;
3218 store->inst_left = ins;
3219 store->inst_right = tramp_ins;
3220 mono_bblock_add_inst (bblock, store);
3222 /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3224 NEW_TEMPLOAD (cfg, obj, temp);
3230 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3232 MonoMethodSignature *esig;
3233 char icall_name [256];
3235 MonoJitICallInfo *info;
3237 /* Need to register the icall so it gets an icall wrapper */
3238 sprintf (icall_name, "ves_array_new_va_%d", rank);
3241 info = mono_find_jit_icall_by_name (icall_name);
3243 esig = mono_get_array_new_va_signature (rank);
3244 name = g_strdup (icall_name);
3245 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3247 g_hash_table_insert (jit_icall_name_hash, name, name);
3251 cfg->flags |= MONO_CFG_HAS_VARARGS;
3253 /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3254 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3258 mono_emit_load_got_addr (MonoCompile *cfg)
3260 MonoInst *load, *store, *dummy_use;
3263 if (!cfg->got_var || cfg->got_var_allocated)
3266 MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3267 NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3269 /* Add it to the start of the first bblock */
3270 MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3272 cfg->got_var_allocated = TRUE;
3275 * Add a dummy use to keep the got_var alive, since real uses might
3276 * only be generated in the decompose or instruction selection phases.
3277 * Add it to end_bblock, so the variable's lifetime covers the whole
3280 NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3281 NEW_DUMMY_USE (cfg, dummy_use, load);
3282 MONO_ADD_INS (cfg->bb_exit, dummy_use);
3285 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3288 mini_class_is_system_array (MonoClass *klass)
3290 if (klass->parent == mono_defaults.array_class)
3297 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3299 MonoMethodHeader *header = mono_method_get_header (method);
3300 MonoMethodSignature *signature = mono_method_signature (method);
3304 if (cfg->generic_sharing_context)
3307 #ifdef MONO_ARCH_HAVE_LMF_OPS
3308 if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3309 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3310 !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3314 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3315 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3316 (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3317 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3318 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3319 (method->klass->marshalbyref) ||
3320 !header || header->num_clauses ||
3321 /* fixme: why cant we inline valuetype returns? */
3322 MONO_TYPE_ISSTRUCT (signature->ret))
3325 #ifdef MONO_ARCH_SOFT_FLOAT
3326 /* this complicates things, fix later */
3327 if (signature->ret->type == MONO_TYPE_R4)
3330 /* its not worth to inline methods with valuetype arguments?? */
3331 for (i = 0; i < signature->param_count; i++) {
3332 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3335 #ifdef MONO_ARCH_SOFT_FLOAT
3336 /* this complicates things, fix later */
3337 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3343 * if we can initialize the class of the method right away, we do,
3344 * otherwise we don't allow inlining if the class needs initialization,
3345 * since it would mean inserting a call to mono_runtime_class_init()
3346 * inside the inlined code
3348 if (!(cfg->opt & MONO_OPT_SHARED)) {
3349 vtable = mono_class_vtable (cfg->domain, method->klass);
3350 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3351 if (cfg->run_cctors) {
3352 /* This makes so that inline cannot trigger */
3353 /* .cctors: too many apps depend on them */
3354 /* running with a specific order... */
3355 if (! vtable->initialized)
3357 mono_runtime_class_init (vtable);
3360 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
3364 * If we're compiling for shared code
3365 * the cctor will need to be run at aot method load time, for example,
3366 * or at the end of the compilation of the inlining method.
3368 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3371 //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3374 * CAS - do not inline methods with declarative security
3375 * Note: this has to be before any possible return TRUE;
3377 if (mono_method_has_declsec (method))
3380 /* also consider num_locals? */
3381 if (getenv ("MONO_INLINELIMIT")) {
3382 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
3385 } else if (header->code_size < INLINE_LENGTH_LIMIT)
3392 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3394 if (vtable->initialized && !cfg->compile_aot)
3397 if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3400 if (!mono_class_needs_cctor_run (vtable->klass, method))
3403 if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3404 /* The initialization is already done before the method is called */
3411 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3415 MonoMethod *addr_method;
3418 rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3421 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3422 addr->inst_left = sp [0];
3423 addr->inst_right = sp [1];
3424 addr->cil_code = ip;
3425 addr->type = STACK_MP;
3426 addr->klass = cmethod->klass->element_class;
3430 if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3431 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3432 /* OP_LDELEMA2D depends on OP_LMUL */
3435 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3436 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3437 addr->inst_left = sp [0];
3438 addr->inst_right = indexes;
3439 addr->cil_code = ip;
3440 addr->type = STACK_MP;
3441 addr->klass = cmethod->klass->element_class;
3446 element_size = mono_class_array_element_size (cmethod->klass->element_class);
3447 addr_method = mono_marshal_get_array_address (rank, element_size);
3448 temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3449 NEW_TEMPLOAD (cfg, addr, temp);
3454 static MonoJitICallInfo **emul_opcode_map = NULL;
3457 mono_find_jit_opcode_emulation (int opcode)
3459 g_assert (opcode >= 0 && opcode <= OP_LAST);
3460 if (emul_opcode_map)
3461 return emul_opcode_map [opcode];
3467 is_unsigned_regsize_type (MonoType *type)
3469 switch (type->type) {
3473 #if SIZEOF_VOID_P == 8
3474 /*case MONO_TYPE_U8: this requires different opcodes in inssel.brg */
3483 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3485 MonoInst *ins = NULL;
3487 static MonoClass *runtime_helpers_class = NULL;
3488 if (! runtime_helpers_class)
3489 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3490 "System.Runtime.CompilerServices", "RuntimeHelpers");
3492 if (cmethod->klass == mono_defaults.string_class) {
3493 if (strcmp (cmethod->name, "get_Chars") == 0) {
3494 MONO_INST_NEW (cfg, ins, OP_GETCHR);
3495 ins->inst_i0 = args [0];
3496 ins->inst_i1 = args [1];
3498 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3499 MONO_INST_NEW (cfg, ins, OP_STRLEN);
3500 ins->inst_i0 = args [0];
3502 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3504 MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3505 get_addr->inst_i0 = args [0];
3506 get_addr->inst_i1 = args [1];
3507 MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3508 ins->inst_i0 = get_addr;
3509 ins->inst_i1 = args [2];
3513 } else if (cmethod->klass == mono_defaults.object_class) {
3514 if (strcmp (cmethod->name, "GetType") == 0) {
3515 MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3516 ins->inst_i0 = args [0];
3518 /* The OP_GETHASHCODE rule depends on OP_MUL */
3519 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3520 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3521 MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3522 ins->inst_i0 = args [0];
3525 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3526 MONO_INST_NEW (cfg, ins, OP_NOP);
3530 } else if (cmethod->klass == mono_defaults.array_class) {
3531 if (cmethod->name [0] != 'g')
3534 if (strcmp (cmethod->name, "get_Rank") == 0) {
3535 MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3536 ins->inst_i0 = args [0];
3538 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3539 MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3540 ins->inst_i0 = args [0];
3544 } else if (cmethod->klass == runtime_helpers_class) {
3545 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3546 NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3550 } else if (cmethod->klass == mono_defaults.thread_class) {
3551 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3553 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3554 MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3557 } else if (mini_class_is_system_array (cmethod->klass) &&
3558 strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3560 MonoInst *ldelem, *store, *load;
3561 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3563 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3568 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3569 ldelem->flags |= MONO_INST_NORANGECHECK;
3570 MONO_INST_NEW (cfg, store, n);
3571 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3572 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3573 load->inst_left = ldelem;
3574 store->inst_left = args [2];
3575 store->inst_right = load;
3577 } else if (cmethod->klass == mono_defaults.math_class) {
3578 if (strcmp (cmethod->name, "Min") == 0) {
3579 if (is_unsigned_regsize_type (fsig->params [0])) {
3580 MONO_INST_NEW (cfg, ins, OP_MIN);
3581 ins->inst_i0 = args [0];
3582 ins->inst_i1 = args [1];
3585 } else if (strcmp (cmethod->name, "Max") == 0) {
3586 if (is_unsigned_regsize_type (fsig->params [0])) {
3587 MONO_INST_NEW (cfg, ins, OP_MAX);
3588 ins->inst_i0 = args [0];
3589 ins->inst_i1 = args [1];
3593 } else if (cmethod->klass->image == mono_defaults.corlib &&
3594 (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3595 (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3598 #if SIZEOF_VOID_P == 8
3599 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3600 /* 64 bit reads are already atomic */
3601 MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3602 ins->inst_i0 = args [0];
3606 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3607 if (strcmp (cmethod->name, "Increment") == 0) {
3608 MonoInst *ins_iconst;
3611 if (fsig->params [0]->type == MONO_TYPE_I4)
3612 opcode = OP_ATOMIC_ADD_NEW_I4;
3613 else if (fsig->params [0]->type == MONO_TYPE_I8)
3614 opcode = OP_ATOMIC_ADD_NEW_I8;
3616 g_assert_not_reached ();
3618 #if SIZEOF_VOID_P == 4
3619 if (opcode == OP_ATOMIC_ADD_NEW_I8)
3623 MONO_INST_NEW (cfg, ins, opcode);
3624 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3625 ins_iconst->inst_c0 = 1;
3627 ins->inst_i0 = args [0];
3628 ins->inst_i1 = ins_iconst;
3629 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3630 MonoInst *ins_iconst;
3633 if (fsig->params [0]->type == MONO_TYPE_I4)
3634 opcode = OP_ATOMIC_ADD_NEW_I4;
3635 else if (fsig->params [0]->type == MONO_TYPE_I8)
3636 opcode = OP_ATOMIC_ADD_NEW_I8;
3638 g_assert_not_reached ();
3640 #if SIZEOF_VOID_P == 4
3641 if (opcode == OP_ATOMIC_ADD_NEW_I8)
3645 MONO_INST_NEW (cfg, ins, opcode);
3646 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3647 ins_iconst->inst_c0 = -1;
3649 ins->inst_i0 = args [0];
3650 ins->inst_i1 = ins_iconst;
3651 } else if (strcmp (cmethod->name, "Add") == 0) {
3654 if (fsig->params [0]->type == MONO_TYPE_I4)
3655 opcode = OP_ATOMIC_ADD_NEW_I4;
3656 else if (fsig->params [0]->type == MONO_TYPE_I8)
3657 opcode = OP_ATOMIC_ADD_NEW_I8;
3659 g_assert_not_reached ();
3661 #if SIZEOF_VOID_P == 4
3662 if (opcode == OP_ATOMIC_ADD_NEW_I8)
3666 MONO_INST_NEW (cfg, ins, opcode);
3668 ins->inst_i0 = args [0];
3669 ins->inst_i1 = args [1];
3671 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3673 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3674 if (strcmp (cmethod->name, "Exchange") == 0) {
3677 if (fsig->params [0]->type == MONO_TYPE_I4)
3678 opcode = OP_ATOMIC_EXCHANGE_I4;
3679 #if SIZEOF_VOID_P == 8
3680 else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3681 (fsig->params [0]->type == MONO_TYPE_I) ||
3682 (fsig->params [0]->type == MONO_TYPE_OBJECT))
3683 opcode = OP_ATOMIC_EXCHANGE_I8;
3685 else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3686 (fsig->params [0]->type == MONO_TYPE_OBJECT))
3687 opcode = OP_ATOMIC_EXCHANGE_I4;
3692 #if SIZEOF_VOID_P == 4
3693 if (opcode == OP_ATOMIC_EXCHANGE_I8)
3697 MONO_INST_NEW (cfg, ins, opcode);
3699 ins->inst_i0 = args [0];
3700 ins->inst_i1 = args [1];
3702 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3706 } else if (cmethod->klass->image == mono_defaults.corlib) {
3707 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3708 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3709 MONO_INST_NEW (cfg, ins, OP_BREAK);
3712 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3713 && strcmp (cmethod->klass->name, "Environment") == 0) {
3714 #ifdef PLATFORM_WIN32
3715 NEW_ICONST (cfg, ins, 1);
3717 NEW_ICONST (cfg, ins, 0);
3723 return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3727 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3729 MonoInst *store, *temp;
3732 g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3734 if (!sig->hasthis && sig->param_count == 0)
3738 if (sp [0]->opcode == OP_ICONST) {
3741 temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3743 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3744 /* FIXME: handle CEE_STIND_R4 */
3745 store->cil_code = sp [0]->cil_code;
3746 MONO_ADD_INS (bblock, store);
3751 for (i = 0; i < sig->param_count; ++i) {
3752 if (sp [0]->opcode == OP_ICONST) {
3755 temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3757 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3758 store->cil_code = sp [0]->cil_code;
3759 /* FIXME: handle CEE_STIND_R4 */
3760 if (store->opcode == CEE_STOBJ) {
3761 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3762 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3763 #ifdef MONO_ARCH_SOFT_FLOAT
3764 } else if (store->opcode == CEE_STIND_R4) {
3765 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3766 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3769 MONO_ADD_INS (bblock, store);
3775 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3776 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3778 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3780 mono_inline_called_method_name_limit = NULL;
3781 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3782 char *called_method_name = mono_method_full_name (called_method, TRUE);
3785 if (mono_inline_called_method_name_limit == NULL) {
3786 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3787 if (limit_string != NULL) {
3788 mono_inline_called_method_name_limit = limit_string;
3790 mono_inline_called_method_name_limit = (char *) "";
3794 strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3795 g_free (called_method_name);
3797 //return (strncmp_result <= 0);
3798 return (strncmp_result == 0);
3802 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3804 mono_inline_caller_method_name_limit = NULL;
3805 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3806 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3809 if (mono_inline_caller_method_name_limit == NULL) {
3810 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3811 if (limit_string != NULL) {
3812 mono_inline_caller_method_name_limit = limit_string;
3814 mono_inline_caller_method_name_limit = (char *) "";
3818 strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3819 g_free (caller_method_name);
3821 //return (strncmp_result <= 0);
3822 return (strncmp_result == 0);
3827 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3828 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3830 MonoInst *ins, *rvar = NULL;
3831 MonoMethodHeader *cheader;
3832 MonoBasicBlock *ebblock, *sbblock;
3833 int i, costs, new_locals_offset;
3834 MonoMethod *prev_inlined_method;
3835 MonoBasicBlock **prev_cil_offset_to_bb;
3836 unsigned char* prev_cil_start;
3837 guint32 prev_cil_offset_to_bb_len;
3839 g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3841 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3842 if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3845 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3846 if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3850 if (bblock->out_of_line && !inline_allways)
3853 if (cfg->verbose_level > 2)
3854 g_print ("INLINE START %p %s -> %s\n", cmethod, mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3856 if (!cmethod->inline_info) {
3857 mono_jit_stats.inlineable_methods++;
3858 cmethod->inline_info = 1;
3860 /* allocate space to store the return value */
3861 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3862 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3865 /* allocate local variables */
3866 cheader = mono_method_get_header (cmethod);
3867 new_locals_offset = cfg->num_varinfo;
3868 for (i = 0; i < cheader->num_locals; ++i)
3869 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3871 /* allocate starte and end blocks */
3872 NEW_BBLOCK (cfg, sbblock);
3873 sbblock->block_num = cfg->num_bblocks++;
3874 sbblock->real_offset = real_offset;
3876 NEW_BBLOCK (cfg, ebblock);
3877 ebblock->block_num = cfg->num_bblocks++;
3878 ebblock->real_offset = real_offset;
3880 prev_inlined_method = cfg->inlined_method;
3881 cfg->inlined_method = cmethod;
3882 prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
3883 prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
3884 prev_cil_start = cfg->cil_start;
3886 costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3888 cfg->inlined_method = prev_inlined_method;
3889 cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
3890 cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
3891 cfg->cil_start = prev_cil_start;
3893 if ((costs >= 0 && costs < 60) || inline_allways) {
3894 if (cfg->verbose_level > 2)
3895 g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3897 mono_jit_stats.inlined_methods++;
3899 /* always add some code to avoid block split failures */
3900 MONO_INST_NEW (cfg, ins, OP_NOP);
3901 MONO_ADD_INS (bblock, ins);
3904 bblock->next_bb = sbblock;
3905 link_bblock (cfg, bblock, sbblock);
3908 NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3909 #ifdef MONO_ARCH_SOFT_FLOAT
3910 if (ins->opcode == CEE_LDIND_R4) {
3912 NEW_TEMPLOADA (cfg, ins, rvar->inst_c0);
3913 temp = handle_load_float (cfg, bblock, ins, ip);
3914 NEW_TEMPLOAD (cfg, ins, temp);
3922 if (cfg->verbose_level > 2)
3923 g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
3924 cfg->exception_type = MONO_EXCEPTION_NONE;
3930 * Some of these comments may well be out-of-date.
3931 * Design decisions: we do a single pass over the IL code (and we do bblock
3932 * splitting/merging in the few cases when it's required: a back jump to an IL
3933 * address that was not already seen as bblock starting point).
3934 * Code is validated as we go (full verification is still better left to metadata/verify.c).
3935 * Complex operations are decomposed in simpler ones right away. We need to let the
3936 * arch-specific code peek and poke inside this process somehow (except when the
3937 * optimizations can take advantage of the full semantic info of coarse opcodes).
3938 * All the opcodes of the form opcode.s are 'normalized' to opcode.
3939 * MonoInst->opcode initially is the IL opcode or some simplification of that
3940 * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific
3941 * opcode with value bigger than OP_LAST.
3942 * At this point the IR can be handed over to an interpreter, a dumb code generator
3943 * or to the optimizing code generator that will translate it to SSA form.
3945 * Profiling directed optimizations.
3946 * We may compile by default with few or no optimizations and instrument the code
3947 * or the user may indicate what methods to optimize the most either in a config file
3948 * or through repeated runs where the compiler applies offline the optimizations to
3949 * each method and then decides if it was worth it.
3953 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
3954 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
3955 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
3956 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
3957 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
3958 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
3959 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
3960 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
3962 /* offset from br.s -> br like opcodes */
3963 #define BIG_BRANCH_OFFSET 13
3965 static inline gboolean
3966 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
3968 MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
3970 return b == NULL || b == bb;
3974 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
3976 unsigned char *ip = start;
3977 unsigned char *target;
3980 MonoBasicBlock *bblock;
3981 const MonoOpcode *opcode;
3984 cli_addr = ip - start;
3985 i = mono_opcode_value ((const guint8 **)&ip, end);
3988 opcode = &mono_opcodes [i];
3989 switch (opcode->argument) {
3990 case MonoInlineNone:
3993 case MonoInlineString:
3994 case MonoInlineType:
3995 case MonoInlineField:
3996 case MonoInlineMethod:
3999 case MonoShortInlineR:
4006 case MonoShortInlineVar:
4007 case MonoShortInlineI:
4010 case MonoShortInlineBrTarget:
4011 target = start + cli_addr + 2 + (signed char)ip [1];
4012 GET_BBLOCK (cfg, bblock, target);
4015 GET_BBLOCK (cfg, bblock, ip);
4017 case MonoInlineBrTarget:
4018 target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4019 GET_BBLOCK (cfg, bblock, target);
4022 GET_BBLOCK (cfg, bblock, ip);
4024 case MonoInlineSwitch: {
4025 guint32 n = read32 (ip + 1);
4028 cli_addr += 5 + 4 * n;
4029 target = start + cli_addr;
4030 GET_BBLOCK (cfg, bblock, target);
4032 for (j = 0; j < n; ++j) {
4033 target = start + cli_addr + (gint32)read32 (ip);
4034 GET_BBLOCK (cfg, bblock, target);
4044 g_assert_not_reached ();
4047 if (i == CEE_THROW) {
4048 unsigned char *bb_start = ip - 1;
4050 /* Find the start of the bblock containing the throw */
4052 while ((bb_start >= start) && !bblock) {
4053 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4057 bblock->out_of_line = 1;
4067 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4069 MonoInst *store, *temp, *load;
4071 if (ip_in_bb (cfg, bblock, ip_next) &&
4072 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4075 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4076 temp->flags |= MONO_INST_IS_TEMP;
4077 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4078 /* FIXME: handle CEE_STIND_R4 */
4079 store->cil_code = ins->cil_code;
4080 MONO_ADD_INS (bblock, store);
4081 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4082 load->cil_code = ins->cil_code;
4086 static inline MonoMethod *
4087 mini_get_method (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4091 if (m->wrapper_type != MONO_WRAPPER_NONE)
4092 return mono_method_get_wrapper_data (m, token);
4094 method = mono_get_method_full (m->klass->image, token, klass, context);
4099 static inline MonoClass*
4100 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4104 if (method->wrapper_type != MONO_WRAPPER_NONE)
4105 klass = mono_method_get_wrapper_data (method, token);
4107 klass = mono_class_get_full (method->klass->image, token, context);
4109 mono_class_init (klass);
4114 * Returns TRUE if the JIT should abort inlining because "callee"
4115 * is influenced by security attributes.
4118 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4122 if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4126 result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4127 if (result == MONO_JIT_SECURITY_OK)
4130 if (result == MONO_JIT_LINKDEMAND_ECMA) {
4131 /* Generate code to throw a SecurityException before the actual call/link */
4132 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4135 NEW_ICONST (cfg, args [0], 4);
4136 NEW_METHODCONST (cfg, args [1], caller);
4137 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4138 } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4139 /* don't hide previous results */
4140 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4141 cfg->exception_data = result;
4149 method_access_exception (void)
4151 static MonoMethod *method = NULL;
4154 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4155 method = mono_class_get_method_from_name (secman->securitymanager,
4156 "MethodAccessException", 2);
4163 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4164 MonoBasicBlock *bblock, unsigned char *ip)
4166 MonoMethod *thrower = method_access_exception ();
4169 NEW_METHODCONST (cfg, args [0], caller);
4170 NEW_METHODCONST (cfg, args [1], callee);
4171 mono_emit_method_call_spilled (cfg, bblock, thrower,
4172 mono_method_signature (thrower), args, ip, NULL);
4176 verification_exception (void)
4178 static MonoMethod *method = NULL;
4181 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4182 method = mono_class_get_method_from_name (secman->securitymanager,
4183 "VerificationException", 0);
4190 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4192 MonoMethod *thrower = verification_exception ();
4194 mono_emit_method_call_spilled (cfg, bblock, thrower,
4195 mono_method_signature (thrower),
4200 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4201 MonoBasicBlock *bblock, unsigned char *ip)
4203 MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4204 MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4205 gboolean is_safe = TRUE;
4207 if (!(caller_level >= callee_level ||
4208 caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4209 callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4214 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4218 method_is_safe (MonoMethod *method)
4221 if (strcmp (method->name, "unsafeMethod") == 0)
4228 * Check that the IL instructions at ip are the array initialization
4229 * sequence and return the pointer to the data and the size.
4232 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4235 * newarr[System.Int32]
4237 * ldtoken field valuetype ...
4238 * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4240 if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4241 MonoClass *klass = newarr->inst_newa_class;
4242 guint32 field_token = read32 (ip + 2);
4243 guint32 field_index = field_token & 0xffffff;
4244 guint32 token = read32 (ip + 7);
4246 const char *data_ptr;
4248 MonoMethod *cmethod;
4249 MonoClass *dummy_class;
4250 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4256 if (newarr->inst_newa_len->opcode != OP_ICONST)
4258 cmethod = mini_get_method (method, token, NULL, NULL);
4261 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4263 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4264 case MONO_TYPE_BOOLEAN:
4268 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4269 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4270 case MONO_TYPE_CHAR:
4280 return NULL; /* stupid ARM FP swapped format */
4289 size *= newarr->inst_newa_len->inst_c0;
4290 if (size > mono_type_size (field->type, &dummy_align))
4293 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4294 field_index = read32 (ip + 2) & 0xffffff;
4295 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4296 data_ptr = mono_image_rva_map (method->klass->image, rva);
4297 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4298 /* for aot code we do the lookup on load */
4299 if (aot && data_ptr)
4300 return GUINT_TO_POINTER (rva);
4307 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4309 char *method_fname = mono_method_full_name (method, TRUE);
4310 char *method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4311 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4312 cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4313 g_free (method_fname);
4314 g_free (method_code);
4318 * Generates this->vtable->runtime_generic_context
4321 get_runtime_generic_context_from_this (MonoCompile *cfg, MonoInst *this, unsigned char *ip)
4323 MonoInst *vtable, *rgc_ptr_addr, *rgc_ptr_offset, *rgc_ptr;
4325 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4326 vtable->cil_code = ip;
4327 vtable->inst_left = this;
4328 vtable->type = STACK_PTR;
4330 NEW_ICONST (cfg, rgc_ptr_offset, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
4332 MONO_INST_NEW (cfg, rgc_ptr_addr, OP_PADD);
4333 rgc_ptr_addr->cil_code = ip;
4334 rgc_ptr_addr->inst_left = vtable;
4335 rgc_ptr_addr->inst_right = rgc_ptr_offset;
4336 rgc_ptr_addr->type = STACK_PTR;
4338 MONO_INST_NEW (cfg, rgc_ptr, CEE_LDIND_I);
4339 rgc_ptr->cil_code = ip;
4340 rgc_ptr->inst_left = rgc_ptr_addr;
4341 rgc_ptr->type = STACK_PTR;
4347 get_runtime_generic_context_field_from_offset (MonoCompile *cfg, MonoInst *rgc_ptr, int offset, unsigned char *ip)
4349 MonoInst *field_offset, *field_addr, *field;
4351 NEW_ICONST (cfg, field_offset, offset);
4353 MONO_INST_NEW (cfg, field_addr, OP_PADD);
4354 field_addr->cil_code = ip;
4355 field_addr->inst_left = rgc_ptr;
4356 field_addr->inst_right = field_offset;
4357 field_addr->type = STACK_PTR;
4359 MONO_INST_NEW (cfg, field, CEE_LDIND_I);
4360 field->cil_code = ip;
4361 field->inst_left = field_addr;
4362 field->type = STACK_PTR;
4368 * Generates ((MonoRuntimeGenericSuperInfo*)rgc)[-depth].XXX where XXX
4369 * is specified by rgctx_type.
4372 get_runtime_generic_context_super_ptr (MonoCompile *cfg, MonoInst *rgc_ptr, int depth, int rgctx_type, unsigned char *ip)
4374 int field_offset_const;
4376 g_assert (depth >= 1);
4378 switch (rgctx_type) {
4379 case MINI_RGCTX_STATIC_DATA :
4380 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, static_data);
4382 case MINI_RGCTX_KLASS :
4383 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, klass);
4385 case MINI_RGCTX_VTABLE:
4386 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, vtable);
4389 g_assert_not_reached ();
4392 return get_runtime_generic_context_field_from_offset (cfg, rgc_ptr,
4393 -depth * sizeof (MonoRuntimeGenericSuperInfo) + field_offset_const, ip);
4397 * Generic rgc->arg_infos [arg_num].XXX where XXX is specified by
4401 get_runtime_generic_context_arg_ptr (MonoCompile *cfg, MonoInst *rgc_ptr, int arg_num, int rgctx_type, unsigned char *ip)
4403 int arg_info_offset, arg_info_field_offset;
4405 g_assert (arg_num >= 0);
4407 arg_info_offset = G_STRUCT_OFFSET (MonoRuntimeGenericContext, arg_infos) +
4408 arg_num * sizeof (MonoRuntimeGenericArgInfo);
4410 switch (rgctx_type) {
4411 case MINI_RGCTX_STATIC_DATA :
4412 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, static_data);
4414 case MINI_RGCTX_KLASS:
4415 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, klass);
4417 case MINI_RGCTX_VTABLE :
4418 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, vtable);
4421 g_assert_not_reached ();
4424 return get_runtime_generic_context_field_from_offset (cfg, rgc_ptr, arg_info_offset + arg_info_field_offset, ip);
4428 get_runtime_generic_context_other_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4429 MonoInst *rgc_ptr, guint32 token, int rgctx_type, unsigned char *ip)
4435 g_assert (method->wrapper_type == MONO_WRAPPER_NONE);
4437 NEW_CLASSCONST (cfg, args [0], method->klass);
4439 NEW_ICONST (cfg, args [2], token);
4440 NEW_ICONST (cfg, args [3], rgctx_type);
4442 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_get_rgctx_other_ptr, args, ip);
4443 NEW_TEMPLOAD (cfg, result, temp);
4449 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4450 MonoClass *klass, guint32 type_token, MonoGenericContext *generic_context, MonoInst *rgctx,
4451 int rgctx_type, unsigned char *ip)
4454 int relation = mono_class_generic_class_relation (klass, method->klass, generic_context, &arg_num);
4457 case MINI_GENERIC_CLASS_RELATION_SELF: {
4458 int depth = klass->idepth;
4459 return get_runtime_generic_context_super_ptr (cfg, rgctx, depth, rgctx_type, ip);
4461 case MINI_GENERIC_CLASS_RELATION_ARGUMENT:
4462 return get_runtime_generic_context_arg_ptr (cfg, rgctx, arg_num, rgctx_type, ip);
4463 case MINI_GENERIC_CLASS_RELATION_OTHER:
4464 return get_runtime_generic_context_other_ptr (cfg, method, bblock, rgctx, type_token, rgctx_type, ip);
4466 g_assert_not_reached ();
4472 * mono_method_to_ir: translates IL into basic blocks containing trees
4475 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
4476 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
4477 guint inline_offset, gboolean is_virtual_call)
4479 MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4480 MonoInst *ins, **sp, **stack_start;
4481 MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4482 MonoMethod *cmethod;
4483 MonoInst **arg_array;
4484 MonoMethodHeader *header;
4486 guint32 token, ins_flag;
4488 MonoClass *constrained_call = NULL;
4489 unsigned char *ip, *end, *target, *err_pos;
4490 static double r8_0 = 0.0;
4491 MonoMethodSignature *sig;
4492 MonoGenericContext *generic_context = NULL;
4493 MonoGenericContainer *generic_container = NULL;
4494 MonoType **param_types;
4495 GList *bb_recheck = NULL, *tmp;
4496 int i, n, start_new_bblock, ialign;
4497 int num_calls = 0, inline_costs = 0;
4498 int breakpoint_id = 0;
4500 guint real_offset, num_args;
4501 MonoBoolean security, pinvoke;
4502 MonoSecurityManager* secman = NULL;
4503 MonoDeclSecurityActions actions;
4504 GSList *class_inits = NULL;
4505 gboolean dont_verify, dont_verify_stloc;
4507 /* serialization and xdomain stuff may need access to private fields and methods */
4508 dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4509 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4510 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4511 dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4512 dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4513 dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4515 /* turn off visibility checks for smcs */
4516 dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4518 /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4519 dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4520 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4521 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4523 /* Not turned on yet */
4524 cfg->dont_verify_stack_merge = TRUE;
4526 image = method->klass->image;
4527 header = mono_method_get_header (method);
4528 generic_container = method->generic_container;
4529 sig = mono_method_signature (method);
4530 num_args = sig->hasthis + sig->param_count;
4531 ip = (unsigned char*)header->code;
4532 cfg->cil_start = ip;
4533 end = ip + header->code_size;
4534 mono_jit_stats.cil_code_size += header->code_size;
4536 if (sig->is_inflated)
4537 generic_context = mono_method_get_context (method);
4538 else if (generic_container)
4539 generic_context = &generic_container->context;
4541 if (!cfg->generic_sharing_context)
4542 g_assert (!sig->has_type_parameters);
4544 if (cfg->method == method)
4547 real_offset = inline_offset;
4549 cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4550 cfg->cil_offset_to_bb_len = header->code_size;
4552 if (cfg->verbose_level > 2)
4553 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4555 dont_inline = g_list_prepend (dont_inline, method);
4556 if (cfg->method == method) {
4558 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4559 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4562 NEW_BBLOCK (cfg, start_bblock);
4563 cfg->bb_entry = start_bblock;
4564 start_bblock->cil_code = NULL;
4565 start_bblock->cil_length = 0;
4566 start_bblock->block_num = cfg->num_bblocks++;
4569 NEW_BBLOCK (cfg, end_bblock);
4570 cfg->bb_exit = end_bblock;
4571 end_bblock->cil_code = NULL;
4572 end_bblock->cil_length = 0;
4573 end_bblock->block_num = cfg->num_bblocks++;
4574 g_assert (cfg->num_bblocks == 2);
4576 arg_array = alloca (sizeof (MonoInst *) * num_args);
4577 for (i = num_args - 1; i >= 0; i--)
4578 arg_array [i] = cfg->varinfo [i];
4580 if (header->num_clauses) {
4581 cfg->spvars = g_hash_table_new (NULL, NULL);
4582 cfg->exvars = g_hash_table_new (NULL, NULL);
4584 /* handle exception clauses */
4585 for (i = 0; i < header->num_clauses; ++i) {
4586 MonoBasicBlock *try_bb;
4587 MonoExceptionClause *clause = &header->clauses [i];
4588 GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
4589 try_bb->real_offset = clause->try_offset;
4590 GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
4591 tblock->real_offset = clause->handler_offset;
4592 tblock->flags |= BB_EXCEPTION_HANDLER;
4594 link_bblock (cfg, try_bb, tblock);
4596 if (*(ip + clause->handler_offset) == CEE_POP)
4597 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
4599 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
4600 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
4601 clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
4602 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4603 MONO_ADD_INS (tblock, ins);
4605 /* todo: is a fault block unsafe to optimize? */
4606 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
4607 tblock->flags |= BB_EXCEPTION_UNSAFE;
4611 /*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);
4613 g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
4615 /* catch and filter blocks get the exception object on the stack */
4616 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
4617 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4618 MonoInst *load, *dummy_use;
4620 /* mostly like handle_stack_args (), but just sets the input args */
4621 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
4622 tblock->in_scount = 1;
4623 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4624 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4625 tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4626 tblock->stack_state [0].type = STACK_OBJ;
4628 tblock->stack_state [0].klass = mono_defaults.object_class;
4631 * Add a dummy use for the exvar so its liveness info will be
4634 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
4635 NEW_DUMMY_USE (cfg, dummy_use, load);
4636 MONO_ADD_INS (tblock, dummy_use);
4638 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4639 GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
4640 tblock->real_offset = clause->data.filter_offset;
4641 tblock->in_scount = 1;
4642 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4643 tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4644 tblock->stack_state [0].type = STACK_OBJ;
4646 tblock->stack_state [0].klass = mono_defaults.object_class;
4648 /* The filter block shares the exvar with the handler block */
4649 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4650 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4651 MONO_ADD_INS (tblock, ins);
4656 arg_array = alloca (sizeof (MonoInst *) * num_args);
4657 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
4660 /* FIRST CODE BLOCK */
4661 NEW_BBLOCK (cfg, bblock);
4662 bblock->cil_code = ip;
4664 ADD_BBLOCK (cfg, bblock);
4666 if (cfg->method == method) {
4667 breakpoint_id = mono_debugger_method_has_breakpoint (method);
4668 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
4669 MONO_INST_NEW (cfg, ins, OP_BREAK);
4670 MONO_ADD_INS (bblock, ins);
4674 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
4675 secman = mono_security_manager_get_methods ();
4677 security = (secman && mono_method_has_declsec (method));
4678 /* at this point having security doesn't mean we have any code to generate */
4679 if (security && (cfg->method == method)) {
4680 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
4681 * And we do not want to enter the next section (with allocation) if we
4682 * have nothing to generate */
4683 security = mono_declsec_get_demands (method, &actions);
4686 /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
4687 pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
4689 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4690 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4691 MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
4693 /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
4694 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4698 mono_custom_attrs_free (custom);
4701 custom = mono_custom_attrs_from_class (wrapped->klass);
4702 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4706 mono_custom_attrs_free (custom);
4709 /* not a P/Invoke after all */
4714 if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
4715 /* we use a separate basic block for the initialization code */
4716 NEW_BBLOCK (cfg, init_localsbb);
4717 cfg->bb_init = init_localsbb;
4718 init_localsbb->real_offset = real_offset;
4719 start_bblock->next_bb = init_localsbb;
4720 init_localsbb->next_bb = bblock;
4721 link_bblock (cfg, start_bblock, init_localsbb);
4722 link_bblock (cfg, init_localsbb, bblock);
4723 init_localsbb->block_num = cfg->num_bblocks++;
4725 start_bblock->next_bb = bblock;
4726 link_bblock (cfg, start_bblock, bblock);
4729 /* at this point we know, if security is TRUE, that some code needs to be generated */
4730 if (security && (cfg->method == method)) {
4733 mono_jit_stats.cas_demand_generation++;
4735 if (actions.demand.blob) {
4736 /* Add code for SecurityAction.Demand */
4737 NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
4738 NEW_ICONST (cfg, args [1], actions.demand.size);
4739 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4740 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4742 if (actions.noncasdemand.blob) {
4743 /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
4744 /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
4745 NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
4746 NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
4747 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4748 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4750 if (actions.demandchoice.blob) {
4751 /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
4752 NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
4753 NEW_ICONST (cfg, args [1], actions.demandchoice.size);
4754 /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
4755 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
4759 /* we must Demand SecurityPermission.Unmanaged before p/invoking */
4761 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
4764 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
4765 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4766 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4767 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4768 if (!(method->klass && method->klass->image &&
4769 mono_security_core_clr_is_platform_image (method->klass->image))) {
4770 emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
4774 if (!method_is_safe (method))
4775 emit_throw_verification_exception (cfg, bblock, ip);
4778 if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
4783 if (cfg->method == method)
4784 mono_debug_init_method (cfg, bblock, breakpoint_id);
4786 param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
4788 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
4789 for (n = 0; n < sig->param_count; ++n)
4790 param_types [n + sig->hasthis] = sig->params [n];
4791 for (n = 0; n < header->num_locals; ++n) {
4792 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
4797 /* do this somewhere outside - not here */
4798 NEW_ICONST (cfg, zero_int32, 0);
4799 NEW_ICONST (cfg, zero_int64, 0);
4800 zero_int64->type = STACK_I8;
4801 NEW_PCONST (cfg, zero_ptr, 0);
4802 NEW_PCONST (cfg, zero_obj, 0);
4803 zero_obj->type = STACK_OBJ;
4805 MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
4806 zero_r8->type = STACK_R8;
4807 zero_r8->inst_p0 = &r8_0;
4809 /* add a check for this != NULL to inlined methods */
4810 if (is_virtual_call) {
4811 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
4812 NEW_ARGLOAD (cfg, ins->inst_left, 0);
4814 MONO_ADD_INS (bblock, ins);
4817 /* we use a spare stack slot in SWITCH and NEWOBJ and others */
4818 stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
4821 start_new_bblock = 0;
4824 if (cfg->method == method)
4825 real_offset = ip - header->code;
4827 real_offset = inline_offset;
4829 if (start_new_bblock) {
4830 bblock->cil_length = ip - bblock->cil_code;
4831 if (start_new_bblock == 2) {
4832 g_assert (ip == tblock->cil_code);
4834 GET_BBLOCK (cfg, tblock, ip);
4836 bblock->next_bb = tblock;
4838 start_new_bblock = 0;
4839 for (i = 0; i < bblock->in_scount; ++i) {
4840 if (cfg->verbose_level > 3)
4841 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
4842 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
4845 g_slist_free (class_inits);
4848 if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
4849 link_bblock (cfg, bblock, tblock);
4850 if (sp != stack_start) {
4851 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4853 CHECK_UNVERIFIABLE (cfg);
4855 bblock->next_bb = tblock;
4857 for (i = 0; i < bblock->in_scount; ++i) {
4858 if (cfg->verbose_level > 3)
4859 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
4860 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
4863 g_slist_free (class_inits);
4868 bblock->real_offset = real_offset;
4870 if ((cfg->method == method) && cfg->coverage_info) {
4871 MonoInst *store, *one;
4872 guint32 cil_offset = ip - header->code;
4873 cfg->coverage_info->data [cil_offset].cil_code = ip;
4875 /* TODO: Use an increment here */
4876 NEW_ICONST (cfg, one, 1);
4879 NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
4882 MONO_INST_NEW (cfg, store, CEE_STIND_I);
4883 store->cil_code = ip;
4884 store->inst_left = ins;
4885 store->inst_right = one;
4887 MONO_ADD_INS (bblock, store);
4890 if (cfg->verbose_level > 3)
4891 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
4895 MONO_INST_NEW (cfg, ins, OP_NOP);
4896 ins->cil_code = ip++;
4897 MONO_ADD_INS (bblock, ins);
4900 MONO_INST_NEW (cfg, ins, OP_BREAK);
4901 ins->cil_code = ip++;
4902 MONO_ADD_INS (bblock, ins);
4908 CHECK_STACK_OVF (1);
4909 n = (*ip)-CEE_LDARG_0;
4911 NEW_ARGLOAD (cfg, ins, n);
4912 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
4913 ins->cil_code = ip++;
4920 CHECK_STACK_OVF (1);
4921 n = (*ip)-CEE_LDLOC_0;
4923 NEW_LOCLOAD (cfg, ins, n);
4924 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
4925 ins->cil_code = ip++;
4933 n = (*ip)-CEE_STLOC_0;
4936 handle_loaded_temps (cfg, bblock, stack_start, sp);
4937 NEW_LOCSTORE (cfg, ins, n, *sp);
4939 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
4941 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
4942 if (ins->opcode == CEE_STOBJ) {
4943 NEW_LOCLOADA (cfg, ins, n);
4944 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4946 MONO_ADD_INS (bblock, ins);
4952 CHECK_STACK_OVF (1);
4954 NEW_ARGLOAD (cfg, ins, ip [1]);
4955 LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
4962 CHECK_STACK_OVF (1);
4964 NEW_ARGLOADA (cfg, ins, ip [1]);
4974 NEW_ARGSTORE (cfg, ins, ip [1], *sp);
4975 handle_loaded_temps (cfg, bblock, stack_start, sp);
4977 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
4979 STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
4980 if (ins->opcode == CEE_STOBJ) {
4981 NEW_ARGLOADA (cfg, ins, ip [1]);
4982 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4984 MONO_ADD_INS (bblock, ins);
4989 CHECK_STACK_OVF (1);
4990 CHECK_LOCAL (ip [1]);
4991 NEW_LOCLOAD (cfg, ins, ip [1]);
4992 LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
4999 CHECK_STACK_OVF (1);
5000 CHECK_LOCAL (ip [1]);
5001 NEW_LOCLOADA (cfg, ins, ip [1]);
5010 handle_loaded_temps (cfg, bblock, stack_start, sp);
5011 CHECK_LOCAL (ip [1]);
5012 NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5014 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5016 STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5017 if (ins->opcode == CEE_STOBJ) {
5018 NEW_LOCLOADA (cfg, ins, ip [1]);
5019 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5021 MONO_ADD_INS (bblock, ins);
5026 CHECK_STACK_OVF (1);
5027 NEW_PCONST (cfg, ins, NULL);
5029 ins->type = STACK_OBJ;
5034 CHECK_STACK_OVF (1);
5035 NEW_ICONST (cfg, ins, -1);
5049 CHECK_STACK_OVF (1);
5050 NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5057 CHECK_STACK_OVF (1);
5059 NEW_ICONST (cfg, ins, *((signed char*)ip));
5066 CHECK_STACK_OVF (1);
5067 NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5074 CHECK_STACK_OVF (1);
5075 MONO_INST_NEW (cfg, ins, OP_I8CONST);
5077 ins->type = STACK_I8;
5079 ins->inst_l = (gint64)read64 (ip);
5085 /* we should really allocate this only late in the compilation process */
5086 mono_domain_lock (cfg->domain);
5087 f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5088 mono_domain_unlock (cfg->domain);
5090 CHECK_STACK_OVF (1);
5091 MONO_INST_NEW (cfg, ins, OP_R4CONST);
5092 ins->type = STACK_R8;
5103 mono_domain_lock (cfg->domain);
5104 d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5105 mono_domain_unlock (cfg->domain);
5107 CHECK_STACK_OVF (1);
5108 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5109 ins->type = STACK_R8;
5119 MonoInst *temp, *store;
5121 CHECK_STACK_OVF (1);
5126 * small optimization: if the loaded value was from a local already,
5127 * just load it twice.
5129 if (ins->ssa_op == MONO_SSA_LOAD &&
5130 (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5132 MONO_INST_NEW (cfg, temp, 0);
5134 temp->cil_code = ip;
5137 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5138 temp->flags |= MONO_INST_IS_TEMP;
5139 temp->cil_code = ip;
5140 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5141 store->cil_code = ip;
5142 /* FIXME: handle CEE_STIND_R4 */
5143 if (store->opcode == CEE_STOBJ) {
5144 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5145 handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5147 MONO_ADD_INS (bblock, store);
5149 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5152 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5162 MONO_INST_NEW (cfg, ins, CEE_POP);
5163 MONO_ADD_INS (bblock, ins);
5164 ins->cil_code = ip++;
5170 if (stack_start != sp)
5172 MONO_INST_NEW (cfg, ins, OP_JMP);
5173 token = read32 (ip + 1);
5174 /* FIXME: check the signature matches */
5175 cmethod = mini_get_method (method, token, NULL, generic_context);
5180 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5181 GENERIC_SHARING_FAILURE (CEE_JMP);
5183 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5184 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5186 CHECK_CFG_EXCEPTION;
5189 ins->inst_p0 = cmethod;
5190 MONO_ADD_INS (bblock, ins);
5192 start_new_bblock = 1;
5196 case CEE_CALLVIRT: {
5197 MonoInst *addr = NULL;
5198 MonoMethodSignature *fsig = NULL;
5199 int temp, array_rank = 0;
5200 int virtual = *ip == CEE_CALLVIRT;
5204 token = read32 (ip + 1);
5206 if (*ip == CEE_CALLI) {
5211 if (method->wrapper_type != MONO_WRAPPER_NONE)
5212 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5214 fsig = mono_metadata_parse_signature (image, token);
5216 n = fsig->param_count + fsig->hasthis;
5218 MonoMethod *cil_method;
5220 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5221 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
5222 cil_method = cmethod;
5223 } else if (constrained_call) {
5224 cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5225 cil_method = cmethod;
5227 cmethod = mini_get_method (method, token, NULL, generic_context);
5228 cil_method = cmethod;
5233 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cil_method))
5234 METHOD_ACCESS_FAILURE;
5236 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5237 ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5239 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5240 /* MS.NET seems to silently convert this to a callvirt */
5243 if (!cmethod->klass->inited){
5244 if (!mono_class_init (cmethod->klass))
5248 if (mono_method_signature (cmethod)->pinvoke) {
5249 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5250 fsig = mono_method_signature (wrapper);
5251 } else if (constrained_call) {
5252 fsig = mono_method_signature (cmethod);
5254 fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5257 mono_save_token_info (cfg, image, token, cmethod);
5259 n = fsig->param_count + fsig->hasthis;
5261 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5262 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5264 CHECK_CFG_EXCEPTION;
5267 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5268 mini_class_is_system_array (cmethod->klass)) {
5269 array_rank = cmethod->klass->rank;
5272 if (cmethod->string_ctor)
5273 g_assert_not_reached ();
5277 if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5280 if (cfg->generic_sharing_context && cmethod && mono_method_check_context_used (cmethod))
5281 GENERIC_SHARING_FAILURE (*ip);
5285 //g_assert (!virtual || fsig->hasthis);
5289 if (constrained_call) {
5291 * We have the `constrained.' prefix opcode.
5293 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5296 * The type parameter is instantiated as a valuetype,
5297 * but that type doesn't override the method we're
5298 * calling, so we need to box `this'.
5299 * sp [0] is a pointer to the data: we need the value
5300 * in handle_box (), so load it here.
5302 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5303 type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5304 load->cil_code = ip;
5305 load->inst_left = sp [0];
5306 sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5307 } else if (!constrained_call->valuetype) {
5311 * The type parameter is instantiated as a reference
5312 * type. We have a managed pointer on the stack, so
5313 * we need to dereference it here.
5316 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5318 ins->inst_i0 = sp [0];
5319 ins->type = STACK_OBJ;
5320 ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5322 } else if (cmethod->klass->valuetype)
5324 constrained_call = NULL;
5327 if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5330 if (cmethod && virtual &&
5331 (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
5332 !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) &&
5333 cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5334 mono_method_signature (cmethod)->generic_param_count) {
5335 MonoInst *this_temp, *this_arg_temp, *store;
5336 MonoInst *iargs [4];
5338 g_assert (mono_method_signature (cmethod)->is_inflated);
5339 /* Prevent inlining of methods that contain indirect calls */
5342 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5343 this_temp->cil_code = ip;
5344 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5346 store->cil_code = ip;
5347 MONO_ADD_INS (bblock, store);
5349 /* FIXME: This should be a managed pointer */
5350 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5351 this_arg_temp->cil_code = ip;
5353 /* Because of the PCONST below */
5354 cfg->disable_aot = TRUE;
5355 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5356 NEW_METHODCONST (cfg, iargs [1], cmethod);
5357 NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5358 NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5359 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
5361 NEW_TEMPLOAD (cfg, addr, temp);
5362 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5364 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5365 NEW_TEMPLOAD (cfg, *sp, temp);
5374 if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
5375 (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5378 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5380 /* FIXME: This assumes the two methods has the same number and type of arguments */
5382 * We implement tail calls by storing the actual arguments into the
5383 * argument variables, then emitting a OP_JMP. Since the actual arguments
5384 * can refer to the arg variables, we have to spill them.
5386 handle_loaded_temps (cfg, bblock, sp, sp + n);
5387 for (i = 0; i < n; ++i) {
5388 /* Prevent argument from being register allocated */
5389 arg_array [i]->flags |= MONO_INST_VOLATILE;
5391 /* Check if argument is the same */
5393 * FIXME: This loses liveness info, so it can only be done if the
5394 * argument is not register allocated.
5396 NEW_ARGLOAD (cfg, ins, i);
5397 if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5400 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5402 /* FIXME: handle CEE_STIND_R4 */
5403 if (ins->opcode == CEE_STOBJ) {
5404 NEW_ARGLOADA (cfg, ins, i);
5405 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5408 MONO_ADD_INS (bblock, ins);
5410 MONO_INST_NEW (cfg, ins, OP_JMP);
5412 ins->inst_p0 = cmethod;
5413 ins->inst_p1 = arg_array [0];
5414 MONO_ADD_INS (bblock, ins);
5415 link_bblock (cfg, bblock, end_bblock);
5416 start_new_bblock = 1;
5417 /* skip CEE_RET as well */
5422 if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
5425 if (MONO_TYPE_IS_VOID (fsig->ret)) {
5426 MONO_ADD_INS (bblock, ins);
5428 type_to_eval_stack_type (cfg, fsig->ret, ins);
5438 handle_loaded_temps (cfg, bblock, stack_start, sp);
5440 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5441 (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) &&
5442 mono_method_check_inlining (cfg, cmethod) &&
5443 !g_list_find (dont_inline, cmethod)) {
5445 MonoBasicBlock *ebblock;
5446 gboolean allways = FALSE;
5448 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5449 (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5450 /* Prevent inlining of methods that call wrappers */
5452 cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5456 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
5460 GET_BBLOCK (cfg, bblock, ip);
5461 ebblock->next_bb = bblock;
5462 link_bblock (cfg, ebblock, bblock);
5464 if (!MONO_TYPE_IS_VOID (fsig->ret))
5467 /* indicates start of a new block, and triggers a load of all
5468 stack arguments at bb boundarie */
5471 inline_costs += costs;
5477 inline_costs += 10 * num_calls++;
5479 /* tail recursion elimination */
5480 if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
5481 gboolean has_vtargs = FALSE;
5484 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5486 /* keep it simple */
5487 for (i = fsig->param_count - 1; i >= 0; i--) {
5488 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i]))
5493 for (i = 0; i < n; ++i) {
5494 /* FIXME: handle CEE_STIND_R4 */
5495 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5497 MONO_ADD_INS (bblock, ins);
5499 MONO_INST_NEW (cfg, ins, OP_BR);
5501 MONO_ADD_INS (bblock, ins);
5502 tblock = start_bblock->out_bb [0];
5503 link_bblock (cfg, bblock, tblock);
5504 ins->inst_target_bb = tblock;
5505 start_new_bblock = 1;
5507 /* skip the CEE_RET, too */
5508 if (ip_in_bb (cfg, bblock, ip + 5))
5517 if (ip_in_bb (cfg, bblock, ip + 5)
5518 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
5519 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
5520 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
5521 /* No need to spill */
5526 if (*ip == CEE_CALLI) {
5527 /* Prevent inlining of methods with indirect calls */
5530 ins = (MonoInst*)mono_emit_calli (cfg, bblock, fsig, sp, addr, ip);
5533 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5534 NEW_TEMPLOAD (cfg, *sp, temp);
5538 } else if (array_rank) {
5541 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */
5542 if (sp [fsig->param_count]->type == STACK_OBJ) {
5543 MonoInst *iargs [2];
5544 MonoInst *array, *to_store, *store;
5546 handle_loaded_temps (cfg, bblock, stack_start, sp);
5548 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5549 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
5550 store->cil_code = ip;
5551 MONO_ADD_INS (bblock, store);
5552 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
5554 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
5555 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
5556 /* FIXME: handle CEE_STIND_R4 */
5557 store->cil_code = ip;
5558 MONO_ADD_INS (bblock, store);
5559 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
5562 * We first save the args for the call so that the args are copied to the stack
5563 * and a new instruction tree for them is created. If we don't do this,
5564 * the same MonoInst is added to two different trees and this is not
5567 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
5569 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
5570 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
5573 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
5574 NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
5576 /* FIXME: handle CEE_STIND_R4 */
5577 if (ins->opcode == CEE_STOBJ) {
5578 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
5580 MONO_ADD_INS (bblock, ins);
5583 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
5584 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5585 NEW_INDLOAD (cfg, ins, addr, fsig->ret);
5589 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
5590 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5593 g_assert_not_reached ();
5597 /* Prevent inlining of methods which call other methods */
5599 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
5601 NEW_TEMPLOAD (cfg, *sp, temp);
5604 } else if (no_spill) {
5605 ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
5608 if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
5610 NEW_TEMPLOAD (cfg, load, temp);
5612 #ifdef MONO_ARCH_SOFT_FLOAT
5613 if (load->opcode == CEE_LDIND_R4) {
5614 NEW_TEMPLOADA (cfg, load, temp);
5615 temp = handle_load_float (cfg, bblock, load, ip);
5616 NEW_TEMPLOAD (cfg, load, temp);
5629 if (cfg->method != method) {
5630 /* return from inlined method */
5635 //g_assert (returnvar != -1);
5636 NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
5637 store->cil_code = sp [0]->cil_code;
5638 /* FIXME: handle CEE_STIND_R4 */
5639 if (store->opcode == CEE_STOBJ) {
5640 g_assert_not_reached ();
5641 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5642 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5643 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
5644 #ifdef MONO_ARCH_SOFT_FLOAT
5645 } else if (store->opcode == CEE_STIND_R4) {
5646 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5647 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
5650 MONO_ADD_INS (bblock, store);
5654 g_assert (!return_var);
5657 MONO_INST_NEW (cfg, ins, OP_NOP);
5658 ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
5659 if (ins->opcode == CEE_STOBJ) {
5660 NEW_RETLOADA (cfg, ins);
5661 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5662 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5664 ins->opcode = OP_SETRET;
5666 ins->inst_i0 = *sp;;
5667 ins->inst_i1 = NULL;
5668 MONO_ADD_INS (bblock, ins);
5672 if (sp != stack_start)
5674 MONO_INST_NEW (cfg, ins, OP_BR);
5675 ins->cil_code = ip++;
5676 ins->inst_target_bb = end_bblock;
5677 MONO_ADD_INS (bblock, ins);
5678 link_bblock (cfg, bblock, end_bblock);
5679 start_new_bblock = 1;
5683 MONO_INST_NEW (cfg, ins, OP_BR);
5684 ins->cil_code = ip++;
5685 MONO_ADD_INS (bblock, ins);
5686 target = ip + 1 + (signed char)(*ip);
5688 GET_BBLOCK (cfg, tblock, target);
5689 link_bblock (cfg, bblock, tblock);
5690 CHECK_BBLOCK (target, ip, tblock);
5691 ins->inst_target_bb = tblock;
5692 if (sp != stack_start) {
5693 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5695 CHECK_UNVERIFIABLE (cfg);
5697 start_new_bblock = 1;
5698 inline_costs += BRANCH_COST;
5704 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
5706 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
5707 ins->cil_code = ip++;
5708 target = ip + 1 + *(signed char*)ip;
5710 ADD_UNCOND (ins->opcode == CEE_BRTRUE);
5711 if (sp != stack_start) {
5712 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5714 CHECK_UNVERIFIABLE (cfg);
5716 inline_costs += BRANCH_COST;
5730 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
5731 ins->cil_code = ip++;
5732 target = ip + 1 + *(signed char*)ip;
5734 #ifdef MONO_ARCH_SOFT_FLOAT
5735 if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
5736 ins->opcode = condbr_to_fp_br (ins->opcode);
5738 ins->inst_left = sp [0];
5739 ins->inst_right = sp [1];
5740 ins->type = STACK_I4;
5741 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
5742 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
5750 if (sp != stack_start) {
5751 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5753 CHECK_UNVERIFIABLE (cfg);
5755 inline_costs += BRANCH_COST;
5759 MONO_INST_NEW (cfg, ins, OP_BR);
5760 ins->cil_code = ip++;
5761 MONO_ADD_INS (bblock, ins);
5762 target = ip + 4 + (gint32)read32(ip);
5764 GET_BBLOCK (cfg, tblock, target);
5765 link_bblock (cfg, bblock, tblock);
5766 CHECK_BBLOCK (target, ip, tblock);
5767 ins->inst_target_bb = tblock;
5768 if (sp != stack_start) {
5769 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5771 CHECK_UNVERIFIABLE (cfg);
5773 start_new_bblock = 1;
5774 inline_costs += BRANCH_COST;
5780 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
5782 MONO_INST_NEW (cfg, ins, *ip);
5783 ins->cil_code = ip++;
5784 target = ip + 4 + (gint32)read32(ip);
5786 ADD_UNCOND(ins->opcode == CEE_BRTRUE);
5787 if (sp != stack_start) {
5788 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5790 CHECK_UNVERIFIABLE (cfg);
5792 inline_costs += BRANCH_COST;
5806 MONO_INST_NEW (cfg, ins, *ip);
5807 ins->cil_code = ip++;
5808 target = ip + 4 + (gint32)read32(ip);
5810 #ifdef MONO_ARCH_SOFT_FLOAT
5811 if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
5812 ins->opcode = condbr_to_fp_br (ins->opcode);
5814 ins->inst_left = sp [0];
5815 ins->inst_right = sp [1];
5816 ins->type = STACK_I4;
5817 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
5818 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
5826 if (sp != stack_start) {
5827 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5829 CHECK_UNVERIFIABLE (cfg);
5831 inline_costs += BRANCH_COST;
5836 n = read32 (ip + 1);
5837 MONO_INST_NEW (cfg, ins, OP_SWITCH);
5839 ins->inst_left = *sp;
5840 if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR))
5844 CHECK_OPSIZE (n * sizeof (guint32));
5845 target = ip + n * sizeof (guint32);
5846 MONO_ADD_INS (bblock, ins);
5847 GET_BBLOCK (cfg, tblock, target);
5848 link_bblock (cfg, bblock, tblock);
5849 ins->klass = GUINT_TO_POINTER (n);
5850 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
5851 ins->inst_many_bb [n] = tblock;
5853 for (i = 0; i < n; ++i) {
5854 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
5855 link_bblock (cfg, bblock, tblock);
5856 ins->inst_many_bb [i] = tblock;
5859 if (sp != stack_start) {
5860 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5862 CHECK_UNVERIFIABLE (cfg);
5864 /* Needed by the code generated in inssel.brg */
5865 mono_get_got_var (cfg);
5866 inline_costs += (BRANCH_COST * 2);
5880 MONO_INST_NEW (cfg, ins, *ip);
5885 ins->type = ldind_type [*ip - CEE_LDIND_I1];
5886 ins->flags |= ins_flag;
5888 if (ins->type == STACK_OBJ)
5889 ins->klass = mono_defaults.object_class;
5890 #ifdef MONO_ARCH_SOFT_FLOAT
5891 if (*ip == CEE_LDIND_R4) {
5894 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
5895 NEW_TEMPLOAD (cfg, *sp, temp);
5909 #ifdef MONO_ARCH_SOFT_FLOAT
5910 if (*ip == CEE_STIND_R4) {
5912 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
5917 #if HAVE_WRITE_BARRIERS
5918 if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
5919 /* insert call to write barrier */
5920 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
5922 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
5927 MONO_INST_NEW (cfg, ins, *ip);
5928 ins->cil_code = ip++;
5930 handle_loaded_temps (cfg, bblock, stack_start, sp);
5931 MONO_ADD_INS (bblock, ins);
5932 ins->inst_i0 = sp [0];
5933 ins->inst_i1 = sp [1];
5934 ins->flags |= ins_flag;
5942 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
5943 /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
5944 if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
5945 switch (ins->opcode) {
5947 ins->opcode = OP_IMUL_IMM;
5948 ins->inst_imm = ins->inst_right->inst_c0;
5951 ins->opcode = OP_LMUL_IMM;
5952 ins->inst_imm = ins->inst_right->inst_c0;
5955 g_assert_not_reached ();
5960 if (mono_find_jit_opcode_emulation (ins->opcode)) {
5962 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5980 /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
5981 * later apply the speedup to the left shift as well
5984 if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8)
5985 && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
5986 ins->opcode = OP_LONG_SHRUN_32;
5987 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
5991 if (mono_find_jit_opcode_emulation (ins->opcode)) {
5993 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6007 case CEE_CONV_OVF_I8:
6008 case CEE_CONV_OVF_U8:
6012 if (mono_find_jit_opcode_emulation (ins->opcode)) {
6014 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6018 case CEE_CONV_OVF_I4:
6019 case CEE_CONV_OVF_I1:
6020 case CEE_CONV_OVF_I2:
6021 case CEE_CONV_OVF_I:
6022 case CEE_CONV_OVF_U:
6025 if (sp [-1]->type == STACK_R8) {
6026 ADD_UNOP (CEE_CONV_OVF_I8);
6034 case CEE_CONV_OVF_U1:
6035 case CEE_CONV_OVF_U2:
6036 case CEE_CONV_OVF_U4:
6039 if (sp [-1]->type == STACK_R8) {
6040 ADD_UNOP (CEE_CONV_OVF_U8);
6048 case CEE_CONV_OVF_I1_UN:
6049 case CEE_CONV_OVF_I2_UN:
6050 case CEE_CONV_OVF_I4_UN:
6051 case CEE_CONV_OVF_I8_UN:
6052 case CEE_CONV_OVF_U1_UN:
6053 case CEE_CONV_OVF_U2_UN:
6054 case CEE_CONV_OVF_U4_UN:
6055 case CEE_CONV_OVF_U8_UN:
6056 case CEE_CONV_OVF_I_UN:
6057 case CEE_CONV_OVF_U_UN:
6065 token = read32 (ip + 1);
6066 klass = mini_get_class (method, token, generic_context);
6067 CHECK_TYPELOAD (klass);
6069 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6070 MonoInst *store, *load;
6071 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6072 load->cil_code = ip;
6073 load->inst_i0 = sp [1];
6074 load->type = STACK_OBJ;
6075 load->klass = klass;
6076 load->flags |= ins_flag;
6077 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6078 store->cil_code = ip;
6079 handle_loaded_temps (cfg, bblock, stack_start, sp);
6080 MONO_ADD_INS (bblock, store);
6081 store->inst_i0 = sp [0];
6082 store->inst_i1 = load;
6083 store->flags |= ins_flag;
6087 n = mono_class_value_size (klass, &align);
6088 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6090 NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6091 MONO_ADD_INS (bblock, copy);
6093 MonoMethod *memcpy_method = get_memcpy_method ();
6094 MonoInst *iargs [3];
6097 NEW_ICONST (cfg, iargs [2], n);
6098 iargs [2]->cil_code = ip;
6100 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6107 MonoInst *iargs [3];
6115 token = read32 (ip + 1);
6116 klass = mini_get_class (method, token, generic_context);
6117 CHECK_TYPELOAD (klass);
6118 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6119 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6121 ins->inst_i0 = sp [0];
6122 ins->type = STACK_OBJ;
6124 ins->flags |= ins_flag;
6131 /* Optimize the common ldobj+stloc combination */
6141 loc_index = ip [5] - CEE_STLOC_0;
6148 if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6149 CHECK_LOCAL (loc_index);
6150 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6152 /* FIXME: handle CEE_STIND_R4 */
6153 if (ins->opcode == CEE_STOBJ) {
6154 handle_loaded_temps (cfg, bblock, stack_start, sp);
6156 g_assert (ins->opcode == CEE_STOBJ);
6157 NEW_LOCLOADA (cfg, ins, loc_index);
6158 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6165 n = mono_class_value_size (klass, &align);
6166 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6167 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6168 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6170 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6171 MONO_ADD_INS (bblock, copy);
6173 MonoMethod *memcpy_method = get_memcpy_method ();
6175 NEW_ICONST (cfg, iargs [2], n);
6176 iargs [2]->cil_code = ip;
6178 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6180 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6188 CHECK_STACK_OVF (1);
6190 n = read32 (ip + 1);
6192 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6193 /* FIXME: moving GC */
6194 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6196 ins->type = STACK_OBJ;
6197 ins->klass = mono_defaults.string_class;
6200 else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6202 MonoInst *iargs [1];
6204 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));
6205 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6206 NEW_TEMPLOAD (cfg, *sp, temp);
6210 if (cfg->opt & MONO_OPT_SHARED) {
6212 MonoInst *iargs [3];
6213 MonoInst* domain_var;
6215 if (cfg->compile_aot) {
6216 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6217 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6219 /* avoid depending on undefined C behavior in sequence points */
6220 domain_var = mono_get_domainvar (cfg);
6221 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6222 NEW_IMAGECONST (cfg, iargs [1], image);
6223 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6224 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6225 NEW_TEMPLOAD (cfg, *sp, temp);
6226 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6228 if (bblock->out_of_line) {
6229 MonoInst *iargs [2];
6232 if (cfg->compile_aot && cfg->method->klass->image == mono_defaults.corlib) {
6234 * Avoid relocations by using a version of helper_ldstr
6235 * specialized to mscorlib.
6237 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6238 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6240 /* Avoid creating the string object */
6241 NEW_IMAGECONST (cfg, iargs [0], image);
6242 NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6243 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6245 NEW_TEMPLOAD (cfg, *sp, temp);
6248 if (cfg->compile_aot) {
6249 NEW_LDSTRCONST (cfg, ins, image, n);
6253 NEW_PCONST (cfg, ins, NULL);
6255 ins->type = STACK_OBJ;
6256 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6257 ins->klass = mono_defaults.string_class;
6267 MonoInst *iargs [2];
6268 MonoMethodSignature *fsig;
6272 token = read32 (ip + 1);
6273 cmethod = mini_get_method (method, token, NULL, generic_context);
6276 fsig = mono_method_get_signature (cmethod, image, token);
6278 mono_save_token_info (cfg, image, token, cmethod);
6280 if (!mono_class_init (cmethod->klass))
6283 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
6284 GENERIC_SHARING_FAILURE (CEE_NEWOBJ);
6286 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6287 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6289 CHECK_CFG_EXCEPTION;
6290 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6291 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6294 n = fsig->param_count;
6297 /* move the args to allow room for 'this' in the first position */
6303 handle_loaded_temps (cfg, bblock, stack_start, sp);
6305 if (mini_class_is_system_array (cmethod->klass)) {
6306 NEW_METHODCONST (cfg, *sp, cmethod);
6307 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
6308 } else if (cmethod->string_ctor) {
6309 /* we simply pass a null pointer */
6310 NEW_PCONST (cfg, *sp, NULL);
6311 /* now call the string ctor */
6312 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
6314 MonoInst* callvirt_this_arg = NULL;
6316 if (cmethod->klass->valuetype) {
6317 iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
6318 temp = iargs [0]->inst_c0;
6320 NEW_TEMPLOADA (cfg, *sp, temp);
6322 handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
6324 NEW_TEMPLOADA (cfg, *sp, temp);
6327 * The code generated by mini_emit_virtual_call () expects
6328 * iargs [0] to be a boxed instance, but luckily the vcall
6329 * will be transformed into a normal call there.
6332 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
6333 if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
6334 guint8 *tramp = mono_create_class_init_trampoline (vtable);
6335 mono_emit_native_call (cfg, bblock, tramp,
6336 helper_sig_class_init_trampoline,
6337 NULL, ip, FALSE, FALSE);
6338 if (cfg->verbose_level > 2)
6339 g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
6340 class_inits = g_slist_prepend (class_inits, vtable);
6342 temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
6343 NEW_TEMPLOAD (cfg, *sp, temp);
6346 /* Avoid virtual calls to ctors if possible */
6347 if (cmethod->klass->marshalbyref)
6348 callvirt_this_arg = sp [0];
6350 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
6351 mono_method_check_inlining (cfg, cmethod) &&
6352 !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
6353 !g_list_find (dont_inline, cmethod)) {
6355 MonoBasicBlock *ebblock;
6356 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
6361 GET_BBLOCK (cfg, bblock, ip);
6362 ebblock->next_bb = bblock;
6363 link_bblock (cfg, ebblock, bblock);
6365 NEW_TEMPLOAD (cfg, *sp, temp);
6368 /* indicates start of a new block, and triggers a load
6369 of all stack arguments at bb boundarie */
6372 inline_costs += costs;
6376 /* Prevent inlining of methods which call other methods */
6378 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6381 /* Prevent inlining of methods which call other methods */
6383 /* now call the actual ctor */
6384 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6388 NEW_TEMPLOAD (cfg, *sp, temp);
6399 token = read32 (ip + 1);
6400 klass = mini_get_class (method, token, generic_context);
6401 CHECK_TYPELOAD (klass);
6402 if (sp [0]->type != STACK_OBJ)
6405 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6406 GENERIC_SHARING_FAILURE (CEE_ISINST);
6408 /* Needed by the code generated in inssel.brg */
6409 mono_get_got_var (cfg);
6411 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6413 MonoMethod *mono_isinst;
6414 MonoInst *iargs [1];
6415 MonoBasicBlock *ebblock;
6419 mono_isinst = mono_marshal_get_isinst (klass);
6422 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock,
6423 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6425 g_assert (costs > 0);
6430 GET_BBLOCK (cfg, bblock, ip);
6431 ebblock->next_bb = bblock;
6432 link_bblock (cfg, ebblock, bblock);
6434 temp = iargs [0]->inst_i0->inst_c0;
6435 NEW_TEMPLOAD (cfg, *sp, temp);
6439 inline_costs += costs;
6441 MONO_INST_NEW (cfg, ins, *ip);
6442 ins->type = STACK_OBJ;
6443 ins->inst_left = *sp;
6444 ins->inst_newa_class = klass;
6447 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6451 case CEE_UNBOX_ANY: {
6452 MonoInst *add, *vtoffset;
6453 MonoInst *iargs [3];
6459 token = read32 (ip + 1);
6460 klass = mini_get_class (method, token, generic_context);
6461 CHECK_TYPELOAD (klass);
6463 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6464 GENERIC_SHARING_FAILURE (CEE_UNBOX_ANY);
6466 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6468 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6469 MonoMethod *mono_castclass;
6470 MonoInst *iargs [1];
6471 MonoBasicBlock *ebblock;
6475 mono_castclass = mono_marshal_get_castclass (klass);
6478 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
6479 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6481 g_assert (costs > 0);
6486 GET_BBLOCK (cfg, bblock, ip);
6487 ebblock->next_bb = bblock;
6488 link_bblock (cfg, ebblock, bblock);
6490 temp = iargs [0]->inst_i0->inst_c0;
6491 NEW_TEMPLOAD (cfg, *sp, temp);
6495 inline_costs += costs;
6497 MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
6498 ins->type = STACK_OBJ;
6499 ins->inst_left = *sp;
6501 ins->inst_newa_class = klass;
6509 if (mono_class_is_nullable (klass)) {
6510 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6511 NEW_TEMPLOAD (cfg, *sp, v);
6517 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6518 ins->type = STACK_OBJ;
6519 ins->inst_left = *sp;
6521 ins->inst_newa_class = klass;
6524 MONO_INST_NEW (cfg, add, OP_PADD);
6525 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6526 add->inst_left = ins;
6527 add->inst_right = vtoffset;
6528 add->type = STACK_MP;
6529 add->klass = mono_defaults.object_class;
6533 n = mono_class_value_size (klass, &align);
6534 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6535 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6536 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6538 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6539 MONO_ADD_INS (bblock, copy);
6541 MonoMethod *memcpy_method = get_memcpy_method ();
6543 NEW_ICONST (cfg, iargs [2], n);
6544 iargs [2]->cil_code = ip;
6546 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6548 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6554 MonoInst *add, *vtoffset;
6559 token = read32 (ip + 1);
6560 klass = mini_get_class (method, token, generic_context);
6561 CHECK_TYPELOAD (klass);
6563 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6564 GENERIC_SHARING_FAILURE (CEE_UNBOX);
6566 if (mono_class_is_nullable (klass)) {
6567 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6568 NEW_TEMPLOAD (cfg, *sp, v);
6574 /* Needed by the code generated in inssel.brg */
6575 mono_get_got_var (cfg);
6577 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6578 ins->type = STACK_OBJ;
6579 ins->inst_left = *sp;
6581 ins->inst_newa_class = klass;
6584 MONO_INST_NEW (cfg, add, OP_PADD);
6585 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6586 add->inst_left = ins;
6587 add->inst_right = vtoffset;
6588 add->type = STACK_MP;
6599 token = read32 (ip + 1);
6600 klass = mini_get_class (method, token, generic_context);
6601 CHECK_TYPELOAD (klass);
6602 if (sp [0]->type != STACK_OBJ)
6605 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6606 GENERIC_SHARING_FAILURE (CEE_CASTCLASS);
6608 /* Needed by the code generated in inssel.brg */
6609 mono_get_got_var (cfg);
6611 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6613 MonoMethod *mono_castclass;
6614 MonoInst *iargs [1];
6615 MonoBasicBlock *ebblock;
6619 mono_castclass = mono_marshal_get_castclass (klass);
6622 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
6623 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6625 g_assert (costs > 0);
6630 GET_BBLOCK (cfg, bblock, ip);
6631 ebblock->next_bb = bblock;
6632 link_bblock (cfg, ebblock, bblock);
6634 temp = iargs [0]->inst_i0->inst_c0;
6635 NEW_TEMPLOAD (cfg, *sp, temp);
6639 inline_costs += costs;
6641 MONO_INST_NEW (cfg, ins, *ip);
6642 ins->type = STACK_OBJ;
6643 ins->inst_left = *sp;
6645 ins->inst_newa_class = klass;
6647 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6653 MONO_INST_NEW (cfg, ins, OP_THROW);
6655 ins->inst_left = *sp;
6656 ins->cil_code = ip++;
6657 bblock->out_of_line = TRUE;
6658 MONO_ADD_INS (bblock, ins);
6659 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
6660 ins->cil_code = ip - 1;
6661 MONO_ADD_INS (bblock, ins);
6664 link_bblock (cfg, bblock, end_bblock);
6665 start_new_bblock = 1;
6670 MonoInst *offset_ins;
6671 MonoClassField *field;
6672 MonoBasicBlock *ebblock;
6676 if (*ip == CEE_STFLD) {
6683 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
6685 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
6688 token = read32 (ip + 1);
6689 if (method->wrapper_type != MONO_WRAPPER_NONE) {
6690 field = mono_method_get_wrapper_data (method, token);
6691 klass = field->parent;
6693 field = mono_field_from_token (image, token, &klass, generic_context);
6697 mono_class_init (klass);
6698 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
6699 FIELD_ACCESS_FAILURE;
6701 foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
6702 /* FIXME: mark instructions for use in SSA */
6703 if (*ip == CEE_STFLD) {
6704 if (target_type_is_incompatible (cfg, field->type, sp [1]))
6706 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
6707 MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type);
6708 MonoInst *iargs [5];
6711 NEW_CLASSCONST (cfg, iargs [1], klass);
6712 NEW_FIELDCONST (cfg, iargs [2], field);
6713 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) :
6717 if (cfg->opt & MONO_OPT_INLINE) {
6718 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock,
6719 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6720 g_assert (costs > 0);
6725 GET_BBLOCK (cfg, bblock, ip);
6726 ebblock->next_bb = bblock;
6727 link_bblock (cfg, ebblock, bblock);
6729 /* indicates start of a new block, and triggers a load
6730 of all stack arguments at bb boundarie */
6733 inline_costs += costs;
6736 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
6738 #if HAVE_WRITE_BARRIERS
6739 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF) {
6740 /* insert call to write barrier */
6741 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6742 MonoInst *iargs [2];
6743 NEW_ICONST (cfg, offset_ins, foffset);
6744 MONO_INST_NEW (cfg, ins, OP_PADD);
6746 ins->inst_left = *sp;
6747 ins->inst_right = offset_ins;
6748 ins->type = STACK_MP;
6749 ins->klass = mono_defaults.object_class;
6752 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
6754 #ifdef MONO_ARCH_SOFT_FLOAT
6755 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
6756 NEW_ICONST (cfg, offset_ins, foffset);
6757 MONO_INST_NEW (cfg, ins, OP_PADD);
6759 ins->inst_left = *sp;
6760 ins->inst_right = offset_ins;
6761 ins->type = STACK_MP;
6762 ins->klass = mono_defaults.object_class;
6763 handle_store_float (cfg, bblock, ins, sp [1], ip);
6767 NEW_ICONST (cfg, offset_ins, foffset);
6768 MONO_INST_NEW (cfg, ins, OP_PADD);
6770 ins->inst_left = *sp;
6771 ins->inst_right = offset_ins;
6772 ins->type = STACK_MP;
6774 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
6775 store->cil_code = ip;
6776 store->inst_left = ins;
6777 store->inst_right = sp [1];
6778 handle_loaded_temps (cfg, bblock, stack_start, sp);
6779 store->flags |= ins_flag;
6781 if (store->opcode == CEE_STOBJ) {
6782 handle_stobj (cfg, bblock, ins, sp [1], ip,
6783 mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
6785 MONO_ADD_INS (bblock, store);
6788 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
6789 MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type);
6790 MonoInst *iargs [4];
6794 NEW_CLASSCONST (cfg, iargs [1], klass);
6795 NEW_FIELDCONST (cfg, iargs [2], field);
6796 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
6797 if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
6798 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock,
6799 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6800 g_assert (costs > 0);
6805 GET_BBLOCK (cfg, bblock, ip);
6806 ebblock->next_bb = bblock;
6807 link_bblock (cfg, ebblock, bblock);
6809 temp = iargs [0]->inst_i0->inst_c0;
6811 NEW_TEMPLOAD (cfg, *sp, temp);
6814 /* indicates start of a new block, and triggers a load of
6815 all stack arguments at bb boundarie */
6818 inline_costs += costs;
6821 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
6822 NEW_TEMPLOAD (cfg, *sp, temp);
6826 NEW_ICONST (cfg, offset_ins, foffset);
6827 MONO_INST_NEW (cfg, ins, OP_PADD);
6829 ins->inst_left = *sp;
6830 ins->inst_right = offset_ins;
6831 ins->type = STACK_MP;
6833 if (*ip == CEE_LDFLDA) {
6834 ins->klass = mono_class_from_mono_type (field->type);
6838 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
6839 type_to_eval_stack_type (cfg, field->type, load);
6840 load->cil_code = ip;
6841 load->inst_left = ins;
6842 load->flags |= ins_flag;
6844 #ifdef MONO_ARCH_SOFT_FLOAT
6845 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
6847 temp = handle_load_float (cfg, bblock, ins, ip);
6848 NEW_TEMPLOAD (cfg, *sp, temp);
6862 MonoClassField *field;
6863 gpointer addr = NULL;
6864 gboolean shared_access = FALSE;
6868 token = read32 (ip + 1);
6869 if (method->wrapper_type != MONO_WRAPPER_NONE) {
6870 field = mono_method_get_wrapper_data (method, token);
6871 klass = field->parent;
6874 field = mono_field_from_token (image, token, &klass, generic_context);
6877 mono_class_init (klass);
6878 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
6879 FIELD_ACCESS_FAILURE;
6882 * We can only support shared generic static
6883 * field access on architectures where the
6884 * trampoline code has been extended to handle
6885 * the generic class init.
6887 #ifndef MONO_ARCH_VTABLE_REG
6888 GENERIC_SHARING_FAILURE (*ip);
6891 if (cfg->generic_sharing_context) {
6892 int context_used = mono_class_check_context_used (klass);
6894 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD ||
6896 GENERIC_SHARING_FAILURE (*ip);
6899 relation = mono_class_generic_class_relation (klass, method->klass, generic_context, NULL);
6901 if (!(method->flags & METHOD_ATTRIBUTE_STATIC) /*&& relation != MINI_GENERIC_CLASS_RELATION_OTHER*/)
6902 shared_access = TRUE;
6904 GENERIC_SHARING_FAILURE (*ip);
6908 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
6910 if ((*ip) == CEE_STSFLD)
6911 handle_loaded_temps (cfg, bblock, stack_start, sp);
6913 /* The special_static_fields field is init'd in mono_class_vtable, so it needs
6914 * to be called here.
6916 if (!(cfg->opt & MONO_OPT_SHARED))
6917 mono_class_vtable (cfg->domain, klass);
6918 mono_domain_lock (cfg->domain);
6919 if (cfg->domain->special_static_fields)
6920 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
6921 mono_domain_unlock (cfg->domain);
6923 if (shared_access) {
6924 MonoInst *this, *rgctx, *static_data;
6927 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
6928 method->klass->name_space, method->klass->name, method->name,
6929 depth, field->offset);
6932 if (mono_class_needs_cctor_run (klass, method)) {
6933 MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
6935 MonoInst *this, *vtable;
6937 NEW_ARGLOAD (cfg, this, 0);
6939 if (relation == MINI_GENERIC_CLASS_RELATION_SELF) {
6940 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
6941 vtable->cil_code = ip;
6942 vtable->inst_left = this;
6943 vtable->type = STACK_PTR;
6944 vtable->klass = klass;
6946 MonoInst *rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
6948 vtable = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6949 token, generic_context, rgctx, MINI_RGCTX_VTABLE, ip);
6952 call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
6953 call->inst.opcode = OP_TRAMPCALL_VTABLE;
6954 call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
6956 call->inst.inst_left = vtable;
6958 mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
6962 * The pointer we're computing here is
6964 * super_info.static_data + field->offset
6967 NEW_ARGLOAD (cfg, this, 0);
6968 rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
6969 static_data = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6970 token, generic_context, rgctx, MINI_RGCTX_STATIC_DATA, ip);
6972 if (field->offset == 0) {
6975 MonoInst *field_offset;
6977 NEW_ICONST (cfg, field_offset, field->offset);
6979 MONO_INST_NEW (cfg, ins, OP_PADD);
6981 ins->inst_left = static_data;
6982 ins->inst_right = field_offset;
6983 ins->type = STACK_PTR;
6986 } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
6988 MonoInst *iargs [2];
6989 MonoInst *domain_var;
6991 g_assert (field->parent);
6992 /* avoid depending on undefined C behavior in sequence points */
6993 domain_var = mono_get_domainvar (cfg);
6994 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6995 NEW_FIELDCONST (cfg, iargs [1], field);
6996 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
6997 NEW_TEMPLOAD (cfg, ins, temp);
7000 vtable = mono_class_vtable (cfg->domain, klass);
7002 if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7003 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7004 mono_emit_native_call (cfg, bblock, tramp,
7005 helper_sig_class_init_trampoline,
7006 NULL, ip, FALSE, FALSE);
7007 if (cfg->verbose_level > 2)
7008 g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7009 class_inits = g_slist_prepend (class_inits, vtable);
7011 if (cfg->run_cctors) {
7012 /* This makes so that inline cannot trigger */
7013 /* .cctors: too many apps depend on them */
7014 /* running with a specific order... */
7015 if (! vtable->initialized)
7017 mono_runtime_class_init (vtable);
7020 addr = (char*)vtable->data + field->offset;
7022 if (cfg->compile_aot)
7023 NEW_SFLDACONST (cfg, ins, field);
7025 NEW_PCONST (cfg, ins, addr);
7029 * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr))
7030 * This could be later optimized to do just a couple of
7031 * memory dereferences with constant offsets.
7034 MonoInst *iargs [1];
7035 NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7036 temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7037 NEW_TEMPLOAD (cfg, ins, temp);
7041 /* FIXME: mark instructions for use in SSA */
7042 if (*ip == CEE_LDSFLDA) {
7043 ins->klass = mono_class_from_mono_type (field->type);
7045 } else if (*ip == CEE_STSFLD) {
7049 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7050 store->cil_code = ip;
7051 store->inst_left = ins;
7052 store->inst_right = sp [0];
7053 store->flags |= ins_flag;
7056 #ifdef MONO_ARCH_SOFT_FLOAT
7057 if (store->opcode == CEE_STIND_R4)
7058 handle_store_float (cfg, bblock, ins, sp [0], ip);
7061 if (store->opcode == CEE_STOBJ) {
7062 handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7064 MONO_ADD_INS (bblock, store);
7066 gboolean is_const = FALSE;
7067 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
7068 if (!shared_access && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) &&
7069 vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7070 gpointer addr = (char*)vtable->data + field->offset;
7071 int ro_type = field->type->type;
7072 if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7073 ro_type = field->type->data.klass->enum_basetype->type;
7075 /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7078 case MONO_TYPE_BOOLEAN:
7080 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7084 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7087 case MONO_TYPE_CHAR:
7089 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7093 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7098 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7102 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7105 #ifndef HAVE_MOVING_COLLECTOR
7108 case MONO_TYPE_STRING:
7109 case MONO_TYPE_OBJECT:
7110 case MONO_TYPE_CLASS:
7111 case MONO_TYPE_SZARRAY:
7113 case MONO_TYPE_FNPTR:
7114 case MONO_TYPE_ARRAY:
7115 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7116 type_to_eval_stack_type (cfg, field->type, *sp);
7122 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7123 sp [0]->type = STACK_I8;
7124 sp [0]->inst_l = *((gint64 *)addr);
7129 case MONO_TYPE_VALUETYPE:
7138 CHECK_STACK_OVF (1);
7139 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7140 type_to_eval_stack_type (cfg, field->type, load);
7141 load->cil_code = ip;
7142 load->inst_left = ins;
7143 load->flags |= ins_flag;
7144 #ifdef MONO_ARCH_SOFT_FLOAT
7145 if (load->opcode == CEE_LDIND_R4) {
7147 temp = handle_load_float (cfg, bblock, ins, ip);
7148 NEW_TEMPLOAD (cfg, load, temp);
7162 token = read32 (ip + 1);
7163 klass = mini_get_class (method, token, generic_context);
7164 CHECK_TYPELOAD (klass);
7165 n = mini_type_to_stind (cfg, &klass->byval_arg);
7166 /* FIXME: handle CEE_STIND_R4 */
7167 if (n == CEE_STOBJ) {
7168 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7170 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7172 MONO_INST_NEW (cfg, store, n);
7173 store->cil_code = ip;
7174 store->inst_left = sp [0];
7175 store->inst_right = sp [1];
7176 store->flags |= ins_flag;
7177 MONO_ADD_INS (bblock, store);
7190 token = read32 (ip + 1);
7191 klass = mini_get_class (method, token, generic_context);
7192 CHECK_TYPELOAD (klass);
7194 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7195 GENERIC_SHARING_FAILURE (CEE_BOX);
7197 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7202 if (klass == mono_defaults.void_class)
7204 if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7206 /* frequent check in generic code: box (struct), brtrue */
7207 if (!mono_class_is_nullable (klass) &&
7208 ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7209 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7210 MONO_INST_NEW (cfg, ins, CEE_POP);
7211 MONO_ADD_INS (bblock, ins);
7215 MONO_INST_NEW (cfg, ins, OP_BR);
7217 MONO_ADD_INS (bblock, ins);
7218 if (*ip == CEE_BRTRUE_S) {
7221 target = ip + 1 + (signed char)(*ip);
7226 target = ip + 4 + (gint)(read32 (ip));
7229 GET_BBLOCK (cfg, tblock, target);
7230 link_bblock (cfg, bblock, tblock);
7231 CHECK_BBLOCK (target, ip, tblock);
7232 ins->inst_target_bb = tblock;
7233 GET_BBLOCK (cfg, tblock, ip);
7234 link_bblock (cfg, bblock, tblock);
7235 if (sp != stack_start) {
7236 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7238 CHECK_UNVERIFIABLE (cfg);
7240 start_new_bblock = 1;
7243 *sp++ = handle_box (cfg, bblock, val, ip, klass);
7249 gboolean shared_access = FALSE;
7255 token = read32 (ip + 1);
7257 /* allocate the domainvar - becaus this is used in decompose_foreach */
7258 if (cfg->opt & MONO_OPT_SHARED) {
7259 mono_get_domainvar (cfg);
7260 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7261 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7265 mono_get_got_var (cfg);
7267 klass = mini_get_class (method, token, generic_context);
7268 CHECK_TYPELOAD (klass);
7270 if (cfg->generic_sharing_context) {
7271 int context_used = mono_class_check_context_used (klass);
7273 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD || klass->valuetype)
7274 GENERIC_SHARING_FAILURE (CEE_NEWARR);
7277 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7278 shared_access = TRUE;
7280 GENERIC_SHARING_FAILURE (CEE_NEWARR);
7284 if (shared_access) {
7285 MonoInst *this, *rgctx;
7290 NEW_DOMAINCONST (cfg, args [0]);
7293 NEW_ARGLOAD (cfg, this, 0);
7294 rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
7295 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7296 token, generic_context, rgctx, MINI_RGCTX_KLASS, ip);
7301 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7302 NEW_TEMPLOAD (cfg, ins, temp);
7304 MONO_INST_NEW (cfg, ins, *ip);
7306 ins->inst_newa_class = klass;
7307 ins->inst_newa_len = *sp;
7308 ins->type = STACK_OBJ;
7309 ins->klass = mono_array_class_get (klass, 1);
7315 * we store the object so calls to create the array are not interleaved
7316 * with the arguments of other calls.
7319 MonoInst *store, *temp, *load;
7320 const char *data_ptr;
7323 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7324 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7325 store->cil_code = ins->cil_code;
7326 MONO_ADD_INS (bblock, store);
7328 * we inline/optimize the initialization sequence if possible.
7329 * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
7330 * for small sizes open code the memcpy
7331 * ensure the rva field is big enough
7333 if ((cfg->opt & MONO_OPT_INTRINS) && ip + 6 < end && ip_in_bb (cfg, bblock, ip + 6) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, ins, &data_size))) {
7334 MonoMethod *memcpy_method = get_memcpy_method ();
7335 MonoInst *data_offset, *add;
7336 MonoInst *iargs [3];
7337 NEW_ICONST (cfg, iargs [2], data_size);
7338 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7339 load->cil_code = ins->cil_code;
7340 NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
7341 MONO_INST_NEW (cfg, add, OP_PADD);
7342 add->inst_left = load;
7343 add->inst_right = data_offset;
7346 if (cfg->compile_aot) {
7347 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
7349 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
7351 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7354 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7355 load->cil_code = ins->cil_code;
7364 if (sp [0]->type != STACK_OBJ)
7366 MONO_INST_NEW (cfg, ins, *ip);
7367 ins->cil_code = ip++;
7368 ins->inst_left = *sp;
7369 ins->type = STACK_PTR;
7376 if (sp [0]->type != STACK_OBJ)
7379 klass = mini_get_class (method, read32 (ip + 1), generic_context);
7380 CHECK_TYPELOAD (klass);
7381 /* we need to make sure that this array is exactly the type it needs
7382 * to be for correctness. the wrappers are lax with their usage
7383 * so we need to ignore them here
7385 if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
7388 /* Needed by the code generated in inssel.brg */
7389 mono_get_got_var (cfg);
7391 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
7392 check->cil_code = ip;
7393 check->klass = klass;
7394 check->inst_left = sp [0];
7395 check->type = STACK_OBJ;
7396 check->klass = klass;
7400 mono_class_init (klass);
7401 NEW_LDELEMA (cfg, ins, sp, klass);
7406 case CEE_LDELEM_ANY: {
7410 if (sp [0]->type != STACK_OBJ)
7413 token = read32 (ip + 1);
7414 klass = mini_get_class (method, token, generic_context);
7415 CHECK_TYPELOAD (klass);
7416 mono_class_init (klass);
7417 NEW_LDELEMA (cfg, load, sp, klass);
7418 load->cil_code = ip;
7419 MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
7421 ins->inst_left = load;
7423 type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
7437 case CEE_LDELEM_REF: {
7441 * ldind.x (ldelema (array, index))
7442 * ldelema does the bounds check
7446 if (sp [0]->type != STACK_OBJ)
7448 klass = array_access_to_klass (*ip, sp [0]);
7449 NEW_LDELEMA (cfg, load, sp, klass);
7450 load->cil_code = ip;
7451 #ifdef MONO_ARCH_SOFT_FLOAT
7452 if (*ip == CEE_LDELEM_R4) {
7454 temp = handle_load_float (cfg, bblock, load, ip);
7455 NEW_TEMPLOAD (cfg, *sp, temp);
7461 MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
7463 ins->inst_left = load;
7465 ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
7476 case CEE_STELEM_R8: {
7480 * stind.x (ldelema (array, index), val)
7481 * ldelema does the bounds check
7485 if (sp [0]->type != STACK_OBJ)
7487 klass = array_access_to_klass (*ip, sp [0]);
7488 NEW_LDELEMA (cfg, load, sp, klass);
7489 load->cil_code = ip;
7490 #ifdef MONO_ARCH_SOFT_FLOAT
7491 if (*ip == CEE_STELEM_R4) {
7492 handle_store_float (cfg, bblock, load, sp [2], ip);
7497 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7499 ins->inst_left = load;
7500 ins->inst_right = sp [2];
7502 handle_loaded_temps (cfg, bblock, stack_start, sp);
7503 MONO_ADD_INS (bblock, ins);
7507 case CEE_STELEM_ANY: {
7511 * stind.x (ldelema (array, index), val)
7512 * ldelema does the bounds check
7516 if (sp [0]->type != STACK_OBJ)
7519 token = read32 (ip + 1);
7520 klass = mini_get_class (method, token, generic_context);
7521 CHECK_TYPELOAD (klass);
7522 mono_class_init (klass);
7523 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7524 /* storing a NULL doesn't need any of the complex checks in stelemref */
7525 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7527 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7528 load->cil_code = ip;
7529 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7531 ins->inst_left = load;
7532 ins->inst_right = sp [2];
7533 MONO_ADD_INS (bblock, ins);
7535 MonoMethod* helper = mono_marshal_get_stelemref ();
7536 MonoInst *iargs [3];
7537 handle_loaded_temps (cfg, bblock, stack_start, sp);
7543 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7546 NEW_LDELEMA (cfg, load, sp, klass);
7547 load->cil_code = ip;
7549 n = mini_type_to_stind (cfg, &klass->byval_arg);
7550 /* FIXME: CEE_STIND_R4 */
7552 handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
7554 MONO_INST_NEW (cfg, ins, n);
7556 ins->inst_left = load;
7557 ins->inst_right = sp [2];
7558 handle_loaded_temps (cfg, bblock, stack_start, sp);
7559 MONO_ADD_INS (bblock, ins);
7566 case CEE_STELEM_REF: {
7567 MonoInst *iargs [3];
7568 MonoMethod* helper = mono_marshal_get_stelemref ();
7572 if (sp [0]->type != STACK_OBJ)
7574 if (sp [2]->type != STACK_OBJ)
7577 handle_loaded_temps (cfg, bblock, stack_start, sp);
7579 /* storing a NULL doesn't need any of the complex checks in stelemref */
7580 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7582 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7583 load->cil_code = ip;
7584 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7586 ins->inst_left = load;
7587 ins->inst_right = sp [2];
7588 MONO_ADD_INS (bblock, ins);
7594 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7601 case CEE_CKFINITE: {
7602 MonoInst *store, *temp;
7605 /* this instr. can throw exceptions as side effect,
7606 * so we cant eliminate dead code which contains CKFINITE opdodes.
7607 * Spilling to memory makes sure that we always perform
7611 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
7613 ins->inst_left = sp [-1];
7614 temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
7616 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7617 store->cil_code = ip;
7618 MONO_ADD_INS (bblock, store);
7620 NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
7627 MONO_INST_NEW (cfg, ins, *ip);
7630 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
7631 CHECK_TYPELOAD (klass);
7632 mono_class_init (klass);
7633 ins->type = STACK_MP;
7634 ins->inst_left = *sp;
7636 ins->inst_newa_class = klass;
7641 case CEE_MKREFANY: {
7642 MonoInst *loc, *klassconst;
7645 MONO_INST_NEW (cfg, ins, *ip);
7648 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
7649 CHECK_TYPELOAD (klass);
7650 mono_class_init (klass);
7653 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7654 GENERIC_SHARING_FAILURE (CEE_MKREFANY);
7656 loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
7657 NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
7659 NEW_PCONST (cfg, klassconst, klass);
7660 NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
7662 MONO_ADD_INS (bblock, ins);
7664 NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
7671 MonoClass *handle_class;
7673 CHECK_STACK_OVF (1);
7676 n = read32 (ip + 1);
7678 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7679 handle = mono_method_get_wrapper_data (method, n);
7680 handle_class = mono_method_get_wrapper_data (method, n + 1);
7681 if (handle_class == mono_defaults.typehandle_class)
7682 handle = &((MonoClass*)handle)->byval_arg;
7685 handle = mono_ldtoken (image, n, &handle_class, generic_context);
7686 if (cfg->generic_sharing_context &&
7687 mono_class_check_context_used (handle_class))
7688 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
7692 mono_class_init (handle_class);
7694 if (cfg->opt & MONO_OPT_SHARED) {
7696 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
7698 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
7700 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
7702 NEW_IMAGECONST (cfg, iargs [0], image);
7703 NEW_ICONST (cfg, iargs [1], n);
7704 NEW_PCONST (cfg, iargs [2], generic_context);
7705 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
7706 NEW_TEMPLOAD (cfg, res, temp);
7707 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7708 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
7709 MONO_ADD_INS (bblock, store);
7710 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7712 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
7713 (cmethod->klass == mono_defaults.monotype_class->parent) &&
7714 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && ip_in_bb (cfg, bblock, ip + 5)) {
7715 MonoClass *tclass = mono_class_from_mono_type (handle);
7716 mono_class_init (tclass);
7717 if (cfg->compile_aot)
7718 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
7720 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
7721 ins->type = STACK_OBJ;
7722 ins->klass = cmethod->klass;
7725 MonoInst *store, *addr, *vtvar;
7727 if (cfg->compile_aot)
7728 NEW_LDTOKENCONST (cfg, ins, image, n);
7730 NEW_PCONST (cfg, ins, handle);
7731 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
7732 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7733 NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
7734 MONO_ADD_INS (bblock, store);
7735 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7751 case CEE_ADD_OVF_UN:
7753 case CEE_MUL_OVF_UN:
7755 case CEE_SUB_OVF_UN:
7758 if (mono_find_jit_opcode_emulation (ins->opcode)) {
7760 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
7764 case CEE_ENDFINALLY:
7765 MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
7766 MONO_ADD_INS (bblock, ins);
7767 ins->cil_code = ip++;
7768 start_new_bblock = 1;
7771 * Control will leave the method so empty the stack, otherwise
7772 * the next basic block will start with a nonempty stack.
7774 while (sp != stack_start) {
7775 MONO_INST_NEW (cfg, ins, CEE_POP);
7779 MONO_ADD_INS (bblock, ins);
7786 if (*ip == CEE_LEAVE) {
7788 target = ip + 5 + (gint32)read32(ip + 1);
7791 target = ip + 2 + (signed char)(ip [1]);
7794 /* empty the stack */
7795 while (sp != stack_start) {
7796 MONO_INST_NEW (cfg, ins, CEE_POP);
7800 MONO_ADD_INS (bblock, ins);
7804 * If this leave statement is in a catch block, check for a
7805 * pending exception, and rethrow it if necessary.
7807 for (i = 0; i < header->num_clauses; ++i) {
7808 MonoExceptionClause *clause = &header->clauses [i];
7811 * Use <= in the final comparison to handle clauses with multiple
7812 * leave statements, like in bug #78024.
7813 * The ordering of the exception clauses guarantees that we find the
7816 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)) {
7820 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
7821 load->cil_code = ip;
7823 temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
7824 NEW_TEMPLOAD (cfg, *sp, temp);
7826 MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
7827 ins->inst_left = *sp;
7828 ins->inst_right = load;
7830 MONO_ADD_INS (bblock, ins);
7834 if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
7836 for (tmp = handlers; tmp; tmp = tmp->next) {
7838 link_bblock (cfg, bblock, tblock);
7839 MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
7841 ins->inst_target_bb = tblock;
7842 MONO_ADD_INS (bblock, ins);
7844 g_list_free (handlers);
7847 MONO_INST_NEW (cfg, ins, OP_BR);
7849 MONO_ADD_INS (bblock, ins);
7850 GET_BBLOCK (cfg, tblock, target);
7851 link_bblock (cfg, bblock, tblock);
7852 CHECK_BBLOCK (target, ip, tblock);
7853 ins->inst_target_bb = tblock;
7854 start_new_bblock = 1;
7856 if (*ip == CEE_LEAVE)
7865 MONO_INST_NEW (cfg, ins, *ip);
7867 handle_loaded_temps (cfg, bblock, stack_start, sp);
7868 MONO_ADD_INS (bblock, ins);
7869 ins->cil_code = ip++;
7870 ins->inst_i0 = sp [0];
7871 ins->inst_i1 = sp [1];
7879 /* trampoline mono specific opcodes */
7880 case MONO_CUSTOM_PREFIX: {
7882 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
7887 case CEE_MONO_ICALL: {
7890 MonoJitICallInfo *info;
7892 token = read32 (ip + 2);
7893 func = mono_method_get_wrapper_data (method, token);
7894 info = mono_find_jit_icall_by_addr (func);
7896 g_error ("An attempt has been made to perform an icall to address %p, "
7897 "but the address has not been registered as an icall\n", info);
7898 g_assert_not_reached ();
7901 CHECK_STACK (info->sig->param_count);
7902 sp -= info->sig->param_count;
7904 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
7905 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
7906 NEW_TEMPLOAD (cfg, *sp, temp);
7911 inline_costs += 10 * num_calls++;
7915 case CEE_MONO_LDPTR:
7916 CHECK_STACK_OVF (1);
7918 token = read32 (ip + 2);
7919 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
7923 inline_costs += 10 * num_calls++;
7924 /* Can't embed random pointers into AOT code */
7925 cfg->disable_aot = 1;
7927 case CEE_MONO_VTADDR:
7930 MONO_INST_NEW (cfg, ins, OP_VTADDR);
7932 ins->type = STACK_MP;
7933 ins->inst_left = *sp;
7937 case CEE_MONO_NEWOBJ: {
7938 MonoInst *iargs [2];
7940 CHECK_STACK_OVF (1);
7942 token = read32 (ip + 2);
7943 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7944 mono_class_init (klass);
7945 NEW_DOMAINCONST (cfg, iargs [0]);
7946 NEW_CLASSCONST (cfg, iargs [1], klass);
7947 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
7948 NEW_TEMPLOAD (cfg, *sp, temp);
7951 inline_costs += 10 * num_calls++;
7954 case CEE_MONO_OBJADDR:
7957 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
7959 ins->type = STACK_MP;
7960 ins->inst_left = *sp;
7964 case CEE_MONO_LDNATIVEOBJ:
7967 token = read32 (ip + 2);
7968 klass = mono_method_get_wrapper_data (method, token);
7969 g_assert (klass->valuetype);
7970 mono_class_init (klass);
7971 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
7975 case CEE_MONO_RETOBJ:
7976 g_assert (cfg->ret);
7977 g_assert (mono_method_signature (method)->pinvoke);
7982 token = read32 (ip + 2);
7983 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7985 NEW_RETLOADA (cfg, ins);
7986 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
7988 if (sp != stack_start)
7991 MONO_INST_NEW (cfg, ins, OP_BR);
7993 ins->inst_target_bb = end_bblock;
7994 MONO_ADD_INS (bblock, ins);
7995 link_bblock (cfg, bblock, end_bblock);
7996 start_new_bblock = 1;
7999 case CEE_MONO_CISINST:
8000 case CEE_MONO_CCASTCLASS: {
8005 token = read32 (ip + 2);
8006 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8007 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8008 ins->type = STACK_I4;
8009 ins->inst_left = *sp;
8010 ins->inst_newa_class = klass;
8012 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8016 case CEE_MONO_SAVE_LMF:
8017 case CEE_MONO_RESTORE_LMF:
8018 #ifdef MONO_ARCH_HAVE_LMF_OPS
8019 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8020 MONO_ADD_INS (bblock, ins);
8021 cfg->need_lmf_area = TRUE;
8025 case CEE_MONO_CLASSCONST:
8026 CHECK_STACK_OVF (1);
8028 token = read32 (ip + 2);
8029 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8033 inline_costs += 10 * num_calls++;
8035 case CEE_MONO_NOT_TAKEN:
8036 bblock->out_of_line = TRUE;
8040 CHECK_STACK_OVF (1);
8042 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8043 ins->inst_offset = (gint32)read32 (ip + 2);
8045 ins->type = STACK_PTR;
8050 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8059 /* somewhat similar to LDTOKEN */
8060 MonoInst *addr, *vtvar;
8061 CHECK_STACK_OVF (1);
8062 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL);
8064 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8065 addr->cil_code = ip;
8066 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8068 ins->inst_left = addr;
8069 MONO_ADD_INS (bblock, ins);
8070 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8084 * The following transforms:
8085 * CEE_CEQ into OP_CEQ
8086 * CEE_CGT into OP_CGT
8087 * CEE_CGT_UN into OP_CGT_UN
8088 * CEE_CLT into OP_CLT
8089 * CEE_CLT_UN into OP_CLT_UN
8091 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
8093 MONO_INST_NEW (cfg, ins, cmp->opcode);
8095 cmp->inst_i0 = sp [0];
8096 cmp->inst_i1 = sp [1];
8101 ins->type = STACK_I4;
8103 #if MONO_ARCH_SOFT_FLOAT
8104 if (sp [0]->type == STACK_R8) {
8105 cmp->type = STACK_I4;
8106 *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8111 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8112 cmp->opcode = OP_LCOMPARE;
8114 cmp->opcode = OP_COMPARE;
8116 /* spill it to reduce the expression complexity
8117 * and workaround bug 54209
8119 if (cmp->inst_left->type == STACK_I8) {
8121 *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8128 MonoMethod *cil_method, *ctor_method;
8131 CHECK_STACK_OVF (1);
8133 n = read32 (ip + 2);
8134 cmethod = mini_get_method (method, n, NULL, generic_context);
8137 mono_class_init (cmethod->klass);
8139 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8140 GENERIC_SHARING_FAILURE (CEE_LDFTN);
8142 cil_method = cmethod;
8143 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8144 METHOD_ACCESS_FAILURE;
8145 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8146 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8148 CHECK_CFG_EXCEPTION;
8149 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8150 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8154 * Optimize the common case of ldftn+delegate creation
8156 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8157 /* FIXME: SGEN support */
8158 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, bblock, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ctor_method = mini_get_method (method, read32 (ip + 7), NULL, generic_context)) && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
8159 MonoInst *target_ins;
8162 if (cfg->verbose_level > 3)
8163 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8164 target_ins = sp [-1];
8166 *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8173 handle_loaded_temps (cfg, bblock, stack_start, sp);
8175 NEW_METHODCONST (cfg, argconst, cmethod);
8176 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
8177 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
8179 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
8180 NEW_TEMPLOAD (cfg, *sp, temp);
8184 inline_costs += 10 * num_calls++;
8187 case CEE_LDVIRTFTN: {
8193 n = read32 (ip + 2);
8194 cmethod = mini_get_method (method, n, NULL, generic_context);
8197 mono_class_init (cmethod->klass);
8199 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8200 GENERIC_SHARING_FAILURE (CEE_LDVIRTFTN);
8202 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8203 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8205 CHECK_CFG_EXCEPTION;
8206 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8207 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8210 handle_loaded_temps (cfg, bblock, stack_start, sp);
8214 NEW_METHODCONST (cfg, args [1], cmethod);
8215 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
8216 NEW_TEMPLOAD (cfg, *sp, temp);
8220 inline_costs += 10 * num_calls++;
8224 CHECK_STACK_OVF (1);
8226 n = read16 (ip + 2);
8228 NEW_ARGLOAD (cfg, ins, n);
8229 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
8235 CHECK_STACK_OVF (1);
8237 n = read16 (ip + 2);
8239 NEW_ARGLOADA (cfg, ins, n);
8247 handle_loaded_temps (cfg, bblock, stack_start, sp);
8249 n = read16 (ip + 2);
8251 NEW_ARGSTORE (cfg, ins, n, *sp);
8253 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
8255 STARG_SOFT_FLOAT (cfg, ins, n, ip);
8256 if (ins->opcode == CEE_STOBJ) {
8257 NEW_ARGLOADA (cfg, ins, n);
8258 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8260 MONO_ADD_INS (bblock, ins);
8264 CHECK_STACK_OVF (1);
8266 n = read16 (ip + 2);
8268 NEW_LOCLOAD (cfg, ins, n);
8269 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
8275 CHECK_STACK_OVF (1);
8277 n = read16 (ip + 2);
8279 NEW_LOCLOADA (cfg, ins, n);
8288 n = read16 (ip + 2);
8290 handle_loaded_temps (cfg, bblock, stack_start, sp);
8291 NEW_LOCSTORE (cfg, ins, n, *sp);
8292 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8295 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
8296 if (ins->opcode == CEE_STOBJ) {
8297 NEW_LOCLOADA (cfg, ins, n);
8298 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8300 MONO_ADD_INS (bblock, ins);
8307 if (sp != stack_start)
8309 if (cfg->method != method)
8311 * Inlining this into a loop in a parent could lead to
8312 * stack overflows which is different behavior than the
8313 * non-inlined case, thus disable inlining in this case.
8315 goto inline_failure;
8316 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8317 ins->inst_left = *sp;
8319 ins->type = STACK_PTR;
8321 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8322 if (header->init_locals)
8323 ins->flags |= MONO_INST_INIT;
8327 /* FIXME: set init flag if locals init is set in this method */
8329 case CEE_ENDFILTER: {
8330 MonoExceptionClause *clause, *nearest;
8331 int cc, nearest_num;
8335 if ((sp != stack_start) || (sp [0]->type != STACK_I4))
8337 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
8338 ins->inst_left = *sp;
8340 MONO_ADD_INS (bblock, ins);
8341 start_new_bblock = 1;
8346 for (cc = 0; cc < header->num_clauses; ++cc) {
8347 clause = &header->clauses [cc];
8348 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
8349 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
8350 (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
8356 if ((ip - header->code) != nearest->handler_offset)
8361 case CEE_UNALIGNED_:
8362 ins_flag |= MONO_INST_UNALIGNED;
8363 /* FIXME: record alignment? we can assume 1 for now */
8368 ins_flag |= MONO_INST_VOLATILE;
8372 ins_flag |= MONO_INST_TAILCALL;
8373 cfg->flags |= MONO_CFG_HAS_TAIL;
8374 /* Can't inline tail calls at this time */
8375 inline_costs += 100000;
8382 token = read32 (ip + 2);
8383 klass = mini_get_class (method, token, generic_context);
8384 CHECK_TYPELOAD (klass);
8386 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
8387 GENERIC_SHARING_FAILURE (CEE_INITOBJ);
8389 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
8390 MonoInst *store, *load;
8391 NEW_PCONST (cfg, load, NULL);
8392 load->cil_code = ip;
8393 load->type = STACK_OBJ;
8394 load->klass = klass;
8395 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
8396 store->cil_code = ip;
8397 handle_loaded_temps (cfg, bblock, stack_start, sp);
8398 MONO_ADD_INS (bblock, store);
8399 store->inst_i0 = sp [0];
8400 store->inst_i1 = load;
8402 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
8407 case CEE_CONSTRAINED_:
8408 /* FIXME: implement */
8410 token = read32 (ip + 2);
8411 constrained_call = mono_class_get_full (image, token, generic_context);
8412 CHECK_TYPELOAD (constrained_call);
8417 MonoInst *iargs [3];
8420 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
8422 NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
8423 MONO_ADD_INS (bblock, copy);
8430 handle_loaded_temps (cfg, bblock, stack_start, sp);
8431 if (ip [1] == CEE_CPBLK) {
8432 MonoMethod *memcpy_method = get_memcpy_method ();
8433 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
8435 MonoMethod *memset_method = get_memset_method ();
8436 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
8445 ins_flag |= MONO_INST_NOTYPECHECK;
8447 ins_flag |= MONO_INST_NORANGECHECK;
8448 /* we ignore the no-nullcheck for now since we
8449 * really do it explicitly only when doing callvirt->call
8455 int handler_offset = -1;
8457 for (i = 0; i < header->num_clauses; ++i) {
8458 MonoExceptionClause *clause = &header->clauses [i];
8459 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
8460 handler_offset = clause->handler_offset;
8463 bblock->flags |= BB_EXCEPTION_UNSAFE;
8465 g_assert (handler_offset != -1);
8467 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
8468 load->cil_code = ip;
8469 MONO_INST_NEW (cfg, ins, OP_RETHROW);
8470 ins->inst_left = load;
8472 MONO_ADD_INS (bblock, ins);
8474 link_bblock (cfg, bblock, end_bblock);
8475 start_new_bblock = 1;
8480 GENERIC_SHARING_FAILURE (CEE_SIZEOF);
8482 CHECK_STACK_OVF (1);
8484 token = read32 (ip + 2);
8485 /* FIXXME: handle generics. */
8486 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
8487 MonoType *type = mono_type_create_from_typespec (image, token);
8488 token = mono_type_size (type, &ialign);
8490 MonoClass *klass = mono_class_get_full (image, token, generic_context);
8491 CHECK_TYPELOAD (klass);
8492 mono_class_init (klass);
8493 token = mono_class_value_size (klass, &align);
8495 NEW_ICONST (cfg, ins, token);
8500 case CEE_REFANYTYPE:
8502 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
8504 ins->type = STACK_MP;
8505 ins->inst_left = *sp;
8506 ins->type = STACK_VTYPE;
8507 ins->klass = mono_defaults.typehandle_class;
8516 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
8521 g_error ("opcode 0x%02x not handled", *ip);
8524 if (start_new_bblock != 1)
8527 bblock->cil_length = ip - bblock->cil_code;
8528 bblock->next_bb = end_bblock;
8530 if (cfg->method == method && cfg->domainvar) {
8532 MonoInst *get_domain;
8534 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
8537 MONO_INST_NEW_CALL (cfg, call, OP_CALL);
8538 call->signature = helper_sig_domain_get;
8539 call->inst.type = STACK_PTR;
8540 call->fptr = mono_domain_get;
8541 get_domain = (MonoInst*)call;
8544 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
8545 MONO_ADD_INS (init_localsbb, store);
8548 if (cfg->method == method && cfg->got_var)
8549 mono_emit_load_got_addr (cfg);
8551 if (header->init_locals) {
8553 for (i = 0; i < header->num_locals; ++i) {
8554 MonoType *ptype = header->locals [i];
8555 int t = ptype->type;
8556 if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
8557 t = ptype->data.klass->enum_basetype->type;
8559 NEW_PCONST (cfg, ins, NULL);
8560 NEW_LOCSTORE (cfg, store, i, ins);
8561 MONO_ADD_INS (init_localsbb, store);
8562 } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
8563 NEW_ICONST (cfg, ins, 0);
8564 NEW_LOCSTORE (cfg, store, i, ins);
8565 MONO_ADD_INS (init_localsbb, store);
8566 } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
8567 MONO_INST_NEW (cfg, ins, OP_I8CONST);
8568 ins->type = STACK_I8;
8570 NEW_LOCSTORE (cfg, store, i, ins);
8571 MONO_ADD_INS (init_localsbb, store);
8572 } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
8573 #ifdef MONO_ARCH_SOFT_FLOAT
8574 /* FIXME: handle init of R4 */
8576 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8577 ins->type = STACK_R8;
8578 ins->inst_p0 = (void*)&r8_0;
8579 NEW_LOCSTORE (cfg, store, i, ins);
8580 MONO_ADD_INS (init_localsbb, store);
8582 } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
8583 ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
8584 NEW_LOCLOADA (cfg, ins, i);
8585 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
8587 NEW_PCONST (cfg, ins, NULL);
8588 NEW_LOCSTORE (cfg, store, i, ins);
8589 MONO_ADD_INS (init_localsbb, store);
8594 /* resolve backward branches in the middle of an existing basic block */
8595 for (tmp = bb_recheck; tmp; tmp = tmp->next) {
8597 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
8598 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
8599 if (tblock != start_bblock) {
8601 split_bblock (cfg, tblock, bblock);
8602 l = bblock->cil_code - header->code;
8603 bblock->cil_length = tblock->cil_length - l;
8604 tblock->cil_length = l;
8606 g_print ("recheck failed.\n");
8610 if (cfg->method == method) {
8612 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8613 bb->region = mono_find_block_region (cfg, bb->real_offset);
8615 mono_create_spvar_for_region (cfg, bb->region);
8616 if (cfg->verbose_level > 2)
8617 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
8621 g_slist_free (class_inits);
8622 dont_inline = g_list_remove (dont_inline, method);
8624 if (inline_costs < 0) {
8627 /* Method is too large */
8628 mname = mono_method_full_name (method, TRUE);
8629 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
8630 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
8635 return inline_costs;
8638 g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
8639 g_slist_free (class_inits);
8640 dont_inline = g_list_remove (dont_inline, method);
8644 g_slist_free (class_inits);
8645 dont_inline = g_list_remove (dont_inline, method);
8649 g_slist_free (class_inits);
8650 dont_inline = g_list_remove (dont_inline, method);
8651 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
8655 g_slist_free (class_inits);
8656 dont_inline = g_list_remove (dont_inline, method);
8657 set_exception_type_from_invalid_il (cfg, method, ip);
8662 mono_print_tree (MonoInst *tree) {
8668 arity = mono_burg_arity [tree->opcode];
8670 printf (" %s%s", arity?"(":"", mono_inst_name (tree->opcode));
8672 switch (tree->opcode) {
8674 printf ("[%d]", (int)tree->inst_c0);
8677 printf ("[%lld]", (long long)tree->inst_l);
8680 printf ("[%f]", *(double*)tree->inst_p0);
8683 printf ("[%f]", *(float*)tree->inst_p0);
8687 printf ("[%d]", (int)tree->inst_c0);
8690 if (tree->inst_offset < 0)
8691 printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
8693 printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
8696 printf ("[%s]", mono_arch_regname (tree->dreg));
8699 printf ("[%s]", tree->inst_newa_class->name);
8700 mono_print_tree (tree->inst_newa_len);
8711 case OP_VOIDCALLVIRT:
8712 case OP_TRAMPCALL_VTABLE: {
8713 MonoCallInst *call = (MonoCallInst*)tree;
8715 printf ("[%s]", call->method->name);
8716 else if (call->fptr) {
8717 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
8719 printf ("[%s]", info->name);
8725 printf ("[%d (", (int)tree->inst_c0);
8726 for (i = 0; i < tree->inst_phi_args [0]; i++) {
8729 printf ("%d", tree->inst_phi_args [i + 1]);
8740 case OP_LOAD_MEMBASE:
8741 case OP_LOADI4_MEMBASE:
8742 case OP_LOADU4_MEMBASE:
8743 case OP_LOADU1_MEMBASE:
8744 case OP_LOADI1_MEMBASE:
8745 case OP_LOADU2_MEMBASE:
8746 case OP_LOADI2_MEMBASE:
8747 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
8750 case OP_CALL_HANDLER:
8751 printf ("[B%d]", tree->inst_target_bb->block_num);
8761 case OP_VOIDCALL_REG:
8762 mono_print_tree (tree->inst_left);
8774 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
8775 mono_print_tree (tree->inst_left);
8778 if (!mono_arch_print_tree(tree, arity)) {
8780 mono_print_tree (tree->inst_left);
8782 mono_print_tree (tree->inst_right);
8793 mono_print_tree_nl (MonoInst *tree)
8795 mono_print_tree (tree);
8800 create_helper_signature (void)
8802 helper_sig_domain_get = mono_create_icall_signature ("ptr");
8803 helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
8804 helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
8808 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
8811 MonoMethod *wrapper;
8812 gconstpointer trampoline;
8813 MonoDomain *domain = mono_get_root_domain ();
8815 if (callinfo->wrapper) {
8816 return callinfo->wrapper;
8819 if (callinfo->trampoline)
8820 return callinfo->trampoline;
8823 * We use the lock on the root domain instead of the JIT lock to protect
8824 * callinfo->trampoline, since we do a lot of stuff inside the critical section.
8826 mono_domain_lock (domain);
8828 if (callinfo->trampoline) {
8829 mono_domain_unlock (domain);
8830 return callinfo->trampoline;
8833 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
8834 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
8837 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
8838 mono_register_jit_icall_wrapper (callinfo, trampoline);
8840 callinfo->trampoline = trampoline;
8842 mono_domain_unlock (domain);
8844 return callinfo->trampoline;
8848 mono_init_trampolines (void)
8850 mono_trampoline_code [MONO_TRAMPOLINE_GENERIC] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC);
8851 mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_JUMP);
8852 mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
8853 mono_trampoline_code [MONO_TRAMPOLINE_GENERIC_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
8854 #ifdef MONO_ARCH_AOT_SUPPORTED
8855 mono_trampoline_code [MONO_TRAMPOLINE_AOT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT);
8856 mono_trampoline_code [MONO_TRAMPOLINE_AOT_PLT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT_PLT);
8858 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
8859 mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
8864 mono_init_exceptions (void)
8866 #ifndef CUSTOM_EXCEPTION_HANDLING
8867 mono_arch_get_restore_context ();
8868 mono_arch_get_call_filter ();
8869 mono_arch_get_throw_exception ();
8870 mono_arch_get_rethrow_exception ();
8875 mono_get_trampoline_code (MonoTrampolineType tramp_type)
8877 return mono_trampoline_code [tramp_type];
8881 mono_create_class_init_trampoline (MonoVTable *vtable)
8885 g_assert (!vtable->klass->generic_container);
8887 /* previously created trampoline code */
8888 mono_domain_lock (vtable->domain);
8890 g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
8892 mono_domain_unlock (vtable->domain);
8896 code = mono_arch_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, vtable->domain, NULL);
8898 ptr = mono_create_ftnptr (vtable->domain, code);
8900 /* store trampoline address */
8901 mono_domain_lock (vtable->domain);
8902 g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
8904 mono_domain_unlock (vtable->domain);
8907 if (!class_init_hash_addr)
8908 class_init_hash_addr = g_hash_table_new (NULL, NULL);
8909 g_hash_table_insert (class_init_hash_addr, ptr, vtable);
8916 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method,
8917 gboolean add_sync_wrapper)
8923 if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
8924 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
8926 code = mono_jit_find_compiled_method (domain, method);
8930 mono_domain_lock (domain);
8931 code = g_hash_table_lookup (domain->jump_trampoline_hash, method);
8932 mono_domain_unlock (domain);
8936 code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
8938 mono_domain_lock (domain);
8939 ji = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
8940 mono_domain_unlock (domain);
8941 ji->code_start = code;
8942 ji->code_size = code_size;
8943 ji->method = method;
8946 * mono_delegate_ctor needs to find the method metadata from the
8947 * trampoline address, so we save it here.
8950 mono_jit_info_table_add (domain, ji);
8952 mono_domain_lock (domain);
8953 g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
8954 mono_domain_unlock (domain);
8956 return ji->code_start;
8960 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
8964 mono_domain_lock (domain);
8965 tramp = g_hash_table_lookup (domain->jit_trampoline_hash, method);
8966 mono_domain_unlock (domain);
8970 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
8971 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
8973 tramp = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC, domain, NULL);
8975 mono_domain_lock (domain);
8976 g_hash_table_insert (domain->jit_trampoline_hash, method, tramp);
8977 mono_domain_unlock (domain);
8979 mono_jit_stats.method_trampolines++;
8985 mono_create_jit_trampoline (MonoMethod *method)
8987 return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
8990 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
8992 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
8996 MonoDomain *domain = mono_domain_get ();
8997 guint8 *buf, *start;
8999 mono_domain_lock (domain);
9000 buf = start = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
9001 mono_domain_unlock (domain);
9003 *(gpointer*)(gpointer)buf = image;
9004 buf += sizeof (gpointer);
9005 *(guint32*)(gpointer)buf = token;
9007 tramp = mono_arch_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
9009 mono_jit_stats.method_trampolines++;
9016 mono_create_delegate_trampoline (MonoClass *klass)
9018 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
9019 MonoDomain *domain = mono_domain_get ();
9023 mono_domain_lock (domain);
9024 ptr = g_hash_table_lookup (domain->delegate_trampoline_hash, klass);
9025 mono_domain_unlock (domain);
9029 ptr = mono_arch_create_specific_trampoline (klass, MONO_TRAMPOLINE_DELEGATE, mono_domain_get (), &code_size);
9031 /* store trampoline address */
9032 mono_domain_lock (domain);
9033 g_hash_table_insert (domain->delegate_trampoline_hash,
9035 mono_domain_unlock (domain);
9038 if (!delegate_trampoline_hash_addr)
9039 delegate_trampoline_hash_addr = g_hash_table_new (NULL, NULL);
9040 g_hash_table_insert (delegate_trampoline_hash_addr, ptr, klass);
9050 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
9055 if (class_init_hash_addr)
9056 res = g_hash_table_lookup (class_init_hash_addr, addr);
9064 mono_find_delegate_trampoline_by_addr (gconstpointer addr)
9069 if (delegate_trampoline_hash_addr)
9070 res = g_hash_table_lookup (delegate_trampoline_hash_addr, addr);
9078 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9080 if (!domain->dynamic_code_hash)
9081 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9082 g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9085 static MonoJitDynamicMethodInfo*
9086 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9088 MonoJitDynamicMethodInfo *res;
9090 if (domain->dynamic_code_hash)
9091 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9103 static inline GSList*
9104 g_slist_prepend_mempool (MonoMemPool *mp, GSList *list,
9109 new_list = mono_mempool_alloc (mp, sizeof (GSList));
9110 new_list->data = data;
9111 new_list->next = list;
9117 * mono_allocate_stack_slots_full:
9119 * Allocate stack slots for all non register allocated variables using a
9120 * linear scan algorithm.
9121 * Returns: an array of stack offsets.
9122 * STACK_SIZE is set to the amount of stack space needed.
9123 * STACK_ALIGN is set to the alignment needed by the locals area.
9126 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9128 int i, slot, offset, size;
9133 GList *vars = NULL, *l;
9134 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9138 scalar_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9139 vtype_stack_slots = NULL;
9142 offsets = mono_mempool_alloc (m->mempool, sizeof (gint32) * m->num_varinfo);
9143 for (i = 0; i < m->num_varinfo; ++i)
9146 for (i = m->locals_start; i < m->num_varinfo; i++) {
9147 inst = m->varinfo [i];
9148 vmv = MONO_VARINFO (m, i);
9150 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9153 vars = g_list_prepend (vars, vmv);
9156 vars = mono_varlist_sort (m, vars, 0);
9159 for (l = vars; l; l = l->next) {
9161 inst = m->varinfo [vmv->idx];
9163 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9164 * pinvoke wrappers when they call functions returning structures */
9165 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9166 size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9170 size = mono_type_size (inst->inst_vtype, &ialign);
9174 t = mono_type_get_underlying_type (inst->inst_vtype);
9176 slot_info = &scalar_stack_slots [MONO_TYPE_I];
9179 case MONO_TYPE_GENERICINST:
9180 if (!mono_type_generic_inst_is_valuetype (t)) {
9181 slot_info = &scalar_stack_slots [t->type];
9185 case MONO_TYPE_VALUETYPE:
9186 if (!vtype_stack_slots)
9187 vtype_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * 256);
9188 for (i = 0; i < nvtypes; ++i)
9189 if (t->data.klass == vtype_stack_slots [i].vtype)
9192 slot_info = &vtype_stack_slots [i];
9194 g_assert (nvtypes < 256);
9195 vtype_stack_slots [nvtypes].vtype = t->data.klass;
9196 slot_info = &vtype_stack_slots [nvtypes];
9200 case MONO_TYPE_CLASS:
9201 case MONO_TYPE_OBJECT:
9202 case MONO_TYPE_ARRAY:
9203 case MONO_TYPE_SZARRAY:
9204 case MONO_TYPE_STRING:
9208 #if SIZEOF_VOID_P == 4
9213 /* Share non-float stack slots of the same size */
9214 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9217 slot_info = &scalar_stack_slots [t->type];
9222 if (m->comp_done & MONO_COMP_LIVENESS) {
9223 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9225 /* expire old intervals in active */
9226 while (slot_info->active) {
9227 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9229 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9232 //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);
9234 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9235 slot_info->slots = g_slist_prepend_mempool (m->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9239 * This also handles the case when the variable is used in an
9240 * exception region, as liveness info is not computed there.
9243 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9246 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9247 if (slot_info->slots) {
9248 slot = GPOINTER_TO_INT (slot_info->slots->data);
9250 slot_info->slots = slot_info->slots->next;
9253 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
9258 static int count = 0;
9262 if (count == atoi (getenv ("COUNT")))
9263 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
9264 if (count > atoi (getenv ("COUNT")))
9267 mono_print_tree_nl (inst);
9271 if (slot == 0xffffff) {
9273 * Allways allocate valuetypes to sizeof (gpointer) to allow more
9274 * efficient copying (and to work around the fact that OP_MEMCPY
9275 * and OP_MEMSET ignores alignment).
9277 if (MONO_TYPE_ISSTRUCT (t))
9278 align = sizeof (gpointer);
9282 offset += align - 1;
9283 offset &= ~(align - 1);
9287 offset += align - 1;
9288 offset &= ~(align - 1);
9293 if (*stack_align == 0)
9294 *stack_align = align;
9297 offsets [vmv->idx] = slot;
9300 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9301 if (scalar_stack_slots [i].active)
9302 g_list_free (scalar_stack_slots [i].active);
9304 for (i = 0; i < nvtypes; ++i) {
9305 if (vtype_stack_slots [i].active)
9306 g_list_free (vtype_stack_slots [i].active);
9309 mono_jit_stats.locals_stack_size += offset;
9311 *stack_size = offset;
9316 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9318 return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9322 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9324 MonoJitICallInfo *info;
9325 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9327 if (!emul_opcode_map)
9328 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9330 g_assert (!sig->hasthis);
9331 g_assert (sig->param_count < 3);
9333 info = mono_register_jit_icall (func, name, sig, no_throw);
9335 emul_opcode_map [opcode] = info;
9339 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9341 MonoMethodSignature *sig;
9344 sig = mono_create_icall_signature (sigstr);
9348 mono_register_jit_icall (func, name, sig, save);
9352 decompose_foreach (MonoInst *tree, gpointer data)
9354 static MonoJitICallInfo *newarr_info = NULL;
9355 static MonoJitICallInfo *newarr_specific_info = NULL;
9356 MonoJitICallInfo *info;
9359 switch (tree->opcode) {
9361 MonoCompile *cfg = data;
9362 MonoInst *iargs [3];
9365 newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9366 g_assert (newarr_info);
9367 newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9368 g_assert (newarr_specific_info);
9371 if (cfg->opt & MONO_OPT_SHARED) {
9372 NEW_DOMAINCONST (cfg, iargs [0]);
9373 NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9374 iargs [2] = tree->inst_newa_len;
9379 MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9381 NEW_VTABLECONST (cfg, iargs [0], vtable);
9382 iargs [1] = tree->inst_newa_len;
9384 info = newarr_specific_info;
9387 mono_emulate_opcode (cfg, tree, iargs, info);
9389 /* Need to decompose arguments after the the opcode is decomposed */
9390 for (i = 0; i < info->sig->param_count; ++i)
9391 dec_foreach (iargs [i], cfg);
9394 #ifdef MONO_ARCH_SOFT_FLOAT
9405 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9406 MonoCompile *cfg = data;
9407 MonoInst *iargs [2];
9409 iargs [0] = tree->inst_i0;
9410 iargs [1] = tree->inst_i1;
9412 mono_emulate_opcode (cfg, tree, iargs, info);
9414 dec_foreach (iargs [0], cfg);
9415 dec_foreach (iargs [1], cfg);
9418 g_assert_not_reached ();
9427 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9428 MonoCompile *cfg = data;
9429 MonoInst *iargs [2];
9431 /* the args are in the compare opcode ... */
9432 iargs [0] = tree->inst_i0;
9433 iargs [1] = tree->inst_i1;
9435 mono_emulate_opcode (cfg, tree, iargs, info);
9437 dec_foreach (iargs [0], cfg);
9438 dec_foreach (iargs [1], cfg);
9441 g_assert_not_reached ();
9453 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
9455 switch (mono_burg_arity [tree->opcode]) {
9458 mono_inst_foreach (tree->inst_left, func, data);
9461 mono_inst_foreach (tree->inst_left, func, data);
9462 mono_inst_foreach (tree->inst_right, func, data);
9465 g_assert_not_reached ();
9472 mono_print_bb_code (MonoBasicBlock *bb)
9476 MONO_BB_FOR_EACH_INS (bb, c) {
9477 mono_print_tree (c);
9483 print_dfn (MonoCompile *cfg) {
9488 g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
9490 for (i = 0; i < cfg->num_bblocks; ++i) {
9493 bb = cfg->bblocks [i];
9494 /*if (bb->cil_code) {
9495 char* code1, *code2;
9496 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
9497 if (bb->last_ins->cil_code)
9498 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
9500 code2 = g_strdup ("");
9502 code1 [strlen (code1) - 1] = 0;
9503 code = g_strdup_printf ("%s -> %s", code1, code2);
9507 code = g_strdup ("\n");
9508 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
9509 MONO_BB_FOR_EACH_INS (bb, c) {
9510 mono_print_tree (c);
9514 g_print ("\tprev:");
9515 for (j = 0; j < bb->in_count; ++j) {
9516 g_print (" BB%d", bb->in_bb [j]->block_num);
9518 g_print ("\t\tsucc:");
9519 for (j = 0; j < bb->out_count; ++j) {
9520 g_print (" BB%d", bb->out_bb [j]->block_num);
9522 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
9525 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
9528 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
9530 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
9538 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
9540 MONO_INST_LIST_ADD_TAIL (&inst->node, &bb->ins_list);
9544 mono_destroy_compile (MonoCompile *cfg)
9546 //mono_mempool_stats (cfg->mempool);
9547 mono_free_loop_info (cfg);
9549 mono_regstate_free (cfg->rs);
9551 g_hash_table_destroy (cfg->spvars);
9553 g_hash_table_destroy (cfg->exvars);
9554 mono_mempool_destroy (cfg->mempool);
9555 g_list_free (cfg->ldstr_list);
9556 g_hash_table_destroy (cfg->token_info_hash);
9558 g_free (cfg->varinfo);
9560 g_free (cfg->exception_message);
9564 #ifdef HAVE_KW_THREAD
9565 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
9566 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
9568 * When this is defined, the current lmf is stored in this tls variable instead of in
9571 static __thread gpointer mono_lmf MONO_TLS_FAST;
9576 mono_get_jit_tls_key (void)
9578 return mono_jit_tls_id;
9582 mono_get_lmf_tls_offset (void)
9584 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9586 MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
9594 mono_get_lmf_addr_tls_offset (void)
9597 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
9604 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9607 MonoJitTlsData *jit_tls;
9609 if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9610 return jit_tls->lmf;
9612 g_assert_not_reached ();
9618 mono_get_lmf_addr (void)
9620 #ifdef HAVE_KW_THREAD
9621 return mono_lmf_addr;
9623 MonoJitTlsData *jit_tls;
9625 if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9626 return &jit_tls->lmf;
9628 g_assert_not_reached ();
9633 /* Called by native->managed wrappers */
9635 mono_jit_thread_attach (MonoDomain *domain)
9637 #ifdef HAVE_KW_THREAD
9638 if (!mono_lmf_addr) {
9639 mono_thread_attach (domain);
9642 if (!TlsGetValue (mono_jit_tls_id))
9643 mono_thread_attach (domain);
9645 if (mono_domain_get () != domain)
9646 mono_domain_set (domain, TRUE);
9650 * mono_thread_abort:
9651 * @obj: exception object
9653 * abort the thread, print exception information and stack trace
9656 mono_thread_abort (MonoObject *obj)
9658 /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
9660 /* handle_remove should be eventually called for this thread, too
9663 if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
9664 (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
9665 mono_thread_exit ();
9667 exit (mono_environment_exitcode_get ());
9672 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
9674 MonoJitTlsData *jit_tls;
9677 jit_tls = TlsGetValue (mono_jit_tls_id);
9681 jit_tls = g_new0 (MonoJitTlsData, 1);
9683 TlsSetValue (mono_jit_tls_id, jit_tls);
9685 jit_tls->abort_func = abort_func;
9686 jit_tls->end_of_stack = stack_start;
9688 lmf = g_new0 (MonoLMF, 1);
9689 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
9690 MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
9695 jit_tls->first_lmf = lmf;
9697 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9698 /* jit_tls->lmf is unused */
9700 mono_lmf_addr = &mono_lmf;
9702 #if defined(HAVE_KW_THREAD)
9703 mono_lmf_addr = &jit_tls->lmf;
9709 mono_arch_setup_jit_tls_data (jit_tls);
9710 mono_setup_altstack (jit_tls);
9716 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
9719 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
9720 thread = mono_thread_current ();
9721 mono_debugger_thread_created (tid, thread, jit_tls);
9723 thread->jit_data = jit_tls;
9726 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
9729 mono_thread_abort_dummy (MonoObject *obj)
9731 if (mono_thread_attach_aborted_cb)
9732 mono_thread_attach_aborted_cb (obj);
9734 mono_thread_abort (obj);
9738 mono_thread_attach_cb (gsize tid, gpointer stack_start)
9741 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
9742 thread = mono_thread_current ();
9743 mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
9745 thread->jit_data = jit_tls;
9746 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
9747 setup_stat_profiler ();
9751 mini_thread_cleanup (MonoThread *thread)
9753 MonoJitTlsData *jit_tls = thread->jit_data;
9756 mono_debugger_thread_cleanup (jit_tls);
9757 mono_arch_free_jit_tls_data (jit_tls);
9759 mono_free_altstack (jit_tls);
9760 g_free (jit_tls->first_lmf);
9762 thread->jit_data = NULL;
9763 TlsSetValue (mono_jit_tls_id, NULL);
9768 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
9770 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
9774 ji->data.target = target;
9775 ji->next = cfg->patch_info;
9777 cfg->patch_info = ji;
9781 mono_remove_patch_info (MonoCompile *cfg, int ip)
9783 MonoJumpInfo **ji = &cfg->patch_info;
9786 if ((*ji)->ip.i == ip)
9789 ji = &((*ji)->next);
9794 * mono_patch_info_dup_mp:
9796 * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
9799 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
9801 MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
9802 memcpy (res, patch_info, sizeof (MonoJumpInfo));
9804 switch (patch_info->type) {
9805 case MONO_PATCH_INFO_RVA:
9806 case MONO_PATCH_INFO_LDSTR:
9807 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9808 case MONO_PATCH_INFO_LDTOKEN:
9809 case MONO_PATCH_INFO_DECLSEC:
9810 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
9811 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
9813 case MONO_PATCH_INFO_SWITCH:
9814 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
9815 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
9825 mono_patch_info_hash (gconstpointer data)
9827 const MonoJumpInfo *ji = (MonoJumpInfo*)data;
9830 case MONO_PATCH_INFO_RVA:
9831 case MONO_PATCH_INFO_LDSTR:
9832 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9833 case MONO_PATCH_INFO_LDTOKEN:
9834 case MONO_PATCH_INFO_DECLSEC:
9835 return (ji->type << 8) | ji->data.token->token;
9836 case MONO_PATCH_INFO_VTABLE:
9837 case MONO_PATCH_INFO_CLASS:
9838 case MONO_PATCH_INFO_IID:
9839 case MONO_PATCH_INFO_ADJUSTED_IID:
9840 return (ji->type << 8) | (gssize)ji->data.klass;
9841 case MONO_PATCH_INFO_FIELD:
9842 case MONO_PATCH_INFO_SFLDA:
9843 return (ji->type << 8) | (gssize)ji->data.field;
9844 case MONO_PATCH_INFO_METHODCONST:
9845 case MONO_PATCH_INFO_METHOD:
9846 case MONO_PATCH_INFO_METHOD_JUMP:
9847 return (ji->type << 8) | (gssize)ji->data.method;
9848 case MONO_PATCH_INFO_IMAGE:
9849 return (ji->type << 8) | (gssize)ji->data.image;
9851 return (ji->type << 8);
9856 * mono_patch_info_equal:
9858 * This might fail to recognize equivalent patches, i.e. floats, so its only
9859 * usable in those cases where this is not a problem, i.e. sharing GOT slots
9863 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
9865 const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
9866 const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
9868 if (ji1->type != ji2->type)
9871 switch (ji1->type) {
9872 case MONO_PATCH_INFO_RVA:
9873 case MONO_PATCH_INFO_LDSTR:
9874 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9875 case MONO_PATCH_INFO_LDTOKEN:
9876 case MONO_PATCH_INFO_DECLSEC:
9877 if ((ji1->data.token->image != ji2->data.token->image) ||
9878 (ji1->data.token->token != ji2->data.token->token))
9882 if (ji1->data.name != ji2->data.name)
9891 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
9893 unsigned char *ip = patch_info->ip.i + code;
9894 gconstpointer target = NULL;
9896 switch (patch_info->type) {
9897 case MONO_PATCH_INFO_BB:
9898 target = patch_info->data.bb->native_offset + code;
9900 case MONO_PATCH_INFO_ABS:
9901 target = patch_info->data.target;
9903 case MONO_PATCH_INFO_LABEL:
9904 target = patch_info->data.inst->inst_c0 + code;
9906 case MONO_PATCH_INFO_IP:
9909 case MONO_PATCH_INFO_METHOD_REL:
9910 target = code + patch_info->data.offset;
9912 case MONO_PATCH_INFO_INTERNAL_METHOD: {
9913 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
9915 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
9916 g_assert_not_reached ();
9918 target = mono_icall_get_wrapper (mi);
9921 case MONO_PATCH_INFO_METHOD_JUMP: {
9924 /* get the trampoline to the method from the domain */
9925 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
9926 if (!domain->jump_target_hash)
9927 domain->jump_target_hash = g_hash_table_new (NULL, NULL);
9928 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
9929 list = g_slist_prepend (list, ip);
9930 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
9933 case MONO_PATCH_INFO_METHOD:
9934 if (patch_info->data.method == method) {
9937 /* get the trampoline to the method from the domain */
9938 target = mono_create_jit_trampoline (patch_info->data.method);
9940 case MONO_PATCH_INFO_SWITCH: {
9941 gpointer *jump_table;
9944 if (method && method->dynamic) {
9945 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9947 mono_domain_lock (domain);
9948 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9949 mono_domain_unlock (domain);
9952 for (i = 0; i < patch_info->data.table->table_size; i++) {
9953 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
9955 target = jump_table;
9958 case MONO_PATCH_INFO_METHODCONST:
9959 case MONO_PATCH_INFO_CLASS:
9960 case MONO_PATCH_INFO_IMAGE:
9961 case MONO_PATCH_INFO_FIELD:
9962 target = patch_info->data.target;
9964 case MONO_PATCH_INFO_IID:
9965 mono_class_init (patch_info->data.klass);
9966 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
9968 case MONO_PATCH_INFO_ADJUSTED_IID:
9969 mono_class_init (patch_info->data.klass);
9970 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
9972 case MONO_PATCH_INFO_VTABLE:
9973 target = mono_class_vtable (domain, patch_info->data.klass);
9975 case MONO_PATCH_INFO_CLASS_INIT:
9976 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
9978 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
9979 target = mono_create_delegate_trampoline (patch_info->data.klass);
9981 case MONO_PATCH_INFO_SFLDA: {
9982 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
9983 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
9984 /* Done by the generated code */
9988 mono_runtime_class_init (vtable);
9990 target = (char*)vtable->data + patch_info->data.field->offset;
9993 case MONO_PATCH_INFO_RVA:
9994 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
9996 case MONO_PATCH_INFO_R4:
9997 case MONO_PATCH_INFO_R8:
9998 target = patch_info->data.target;
10000 case MONO_PATCH_INFO_EXC_NAME:
10001 target = patch_info->data.name;
10003 case MONO_PATCH_INFO_LDSTR:
10005 mono_ldstr (domain, patch_info->data.token->image,
10006 mono_metadata_token_index (patch_info->data.token->token));
10008 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10010 MonoClass *handle_class;
10012 handle = mono_ldtoken (patch_info->data.token->image,
10013 patch_info->data.token->token, &handle_class, NULL);
10014 mono_class_init (handle_class);
10015 mono_class_init (mono_class_from_mono_type (handle));
10018 mono_type_get_object (domain, handle);
10021 case MONO_PATCH_INFO_LDTOKEN: {
10023 MonoClass *handle_class;
10025 handle = mono_ldtoken (patch_info->data.token->image,
10026 patch_info->data.token->token, &handle_class, NULL);
10027 mono_class_init (handle_class);
10032 case MONO_PATCH_INFO_DECLSEC:
10033 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10035 case MONO_PATCH_INFO_BB_OVF:
10036 case MONO_PATCH_INFO_EXC_OVF:
10037 case MONO_PATCH_INFO_GOT_OFFSET:
10038 case MONO_PATCH_INFO_NONE:
10041 g_assert_not_reached ();
10044 return (gpointer)target;
10048 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10049 MonoJitICallInfo *info;
10051 decompose_foreach (tree, cfg);
10053 switch (mono_burg_arity [tree->opcode]) {
10056 dec_foreach (tree->inst_left, cfg);
10058 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10059 MonoInst *iargs [2];
10061 iargs [0] = tree->inst_left;
10063 mono_emulate_opcode (cfg, tree, iargs, info);
10069 #ifdef MONO_ARCH_BIGMUL_INTRINS
10070 if (tree->opcode == OP_LMUL
10071 && (cfg->opt & MONO_OPT_INTRINS)
10072 && (tree->inst_left->opcode == CEE_CONV_I8
10073 || tree->inst_left->opcode == CEE_CONV_U8)
10074 && tree->inst_left->inst_left->type == STACK_I4
10075 && (tree->inst_right->opcode == CEE_CONV_I8
10076 || tree->inst_right->opcode == CEE_CONV_U8)
10077 && tree->inst_right->inst_left->type == STACK_I4
10078 && tree->inst_left->opcode == tree->inst_right->opcode) {
10079 tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10080 tree->inst_left = tree->inst_left->inst_left;
10081 tree->inst_right = tree->inst_right->inst_left;
10082 dec_foreach (tree, cfg);
10085 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10086 MonoInst *iargs [2];
10088 iargs [0] = tree->inst_i0;
10089 iargs [1] = tree->inst_i1;
10091 mono_emulate_opcode (cfg, tree, iargs, info);
10093 dec_foreach (iargs [0], cfg);
10094 dec_foreach (iargs [1], cfg);
10097 dec_foreach (tree->inst_left, cfg);
10098 dec_foreach (tree->inst_right, cfg);
10102 g_assert_not_reached ();
10107 decompose_pass (MonoCompile *cfg) {
10108 MonoBasicBlock *bb;
10110 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10113 cfg->prev_ins = NULL;
10114 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10115 dec_foreach (tree, cfg);
10116 cfg->prev_ins = tree;
10122 nullify_basic_block (MonoBasicBlock *bb)
10128 bb->next_bb = NULL;
10129 MONO_INST_LIST_INIT (&bb->ins_list);
10130 bb->cil_code = NULL;
10134 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10138 for (i = 0; i < bb->out_count; i++) {
10139 MonoBasicBlock *ob = bb->out_bb [i];
10142 if (bb->out_count > 1) {
10143 bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10147 bb->out_bb [i] = repl;
10154 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10158 for (i = 0; i < bb->in_count; i++) {
10159 MonoBasicBlock *ib = bb->in_bb [i];
10162 if (bb->in_count > 1) {
10163 bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10167 bb->in_bb [i] = repl;
10174 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10177 MONO_BB_FOR_EACH_INS (bb, inst) {
10178 if (inst->opcode == OP_CALL_HANDLER) {
10179 if (inst->inst_target_bb == orig)
10180 inst->inst_target_bb = repl;
10184 inst = mono_inst_list_last (&bb->ins_list);
10188 switch (inst->opcode) {
10190 if (inst->inst_target_bb == orig)
10191 inst->inst_target_bb = repl;
10195 int n = GPOINTER_TO_INT (inst->klass);
10196 for (i = 0; i < n; i++ ) {
10197 if (inst->inst_many_bb [i] == orig)
10198 inst->inst_many_bb [i] = repl;
10212 if (inst->inst_true_bb == orig)
10213 inst->inst_true_bb = repl;
10214 if (inst->inst_false_bb == orig)
10215 inst->inst_false_bb = repl;
10223 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10227 for (i = 0; i < bb->out_count; i++) {
10228 MonoBasicBlock *ob = bb->out_bb [i];
10229 for (j = 0; j < ob->in_count; j++) {
10230 if (ob->in_bb [j] == orig) {
10231 ob->in_bb [j] = repl;
10239 * Check if a bb is useless (is just made of NOPs and ends with an
10240 * unconditional branch, or nothing).
10241 * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10242 * Otherwise, return FALSE;
10245 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10246 MonoBasicBlock *target_bb = NULL;
10249 /* Do not touch handlers */
10250 if (bb->region != -1) {
10251 bb->not_useless = TRUE;
10255 MONO_BB_FOR_EACH_INS (bb, inst) {
10256 switch (inst->opcode) {
10260 target_bb = inst->inst_target_bb;
10263 bb->not_useless = TRUE;
10268 if (target_bb == NULL) {
10269 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10270 target_bb = bb->next_bb;
10272 /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10277 /* Do not touch BBs following a switch (they are the "default" branch) */
10278 inst = mono_inst_list_last (&previous_bb->ins_list);
10279 if (inst && inst->opcode == OP_SWITCH)
10282 /* Do not touch BBs following the entry BB and jumping to something that is not */
10283 /* thiry "next" bb (the entry BB cannot contain the branch) */
10284 if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10289 * Do not touch BBs following a try block as the code in
10290 * mini_method_compile needs them to compute the length of the try block.
10292 if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10295 /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10296 if ((target_bb != NULL) && (target_bb != bb)) {
10297 MonoInst *last_ins;
10300 if (cfg->verbose_level > 1) {
10301 printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10304 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10305 while (bb->in_count) {
10306 MonoBasicBlock *in_bb = bb->in_bb [0];
10307 mono_unlink_bblock (cfg, in_bb, bb);
10308 link_bblock (cfg, in_bb, target_bb);
10309 replace_out_block_in_code (in_bb, bb, target_bb);
10312 mono_unlink_bblock (cfg, bb, target_bb);
10314 last_ins = mono_inst_list_last (&previous_bb->ins_list);
10316 if ((previous_bb != cfg->bb_entry) &&
10317 (previous_bb->region == bb->region) &&
10318 ((last_ins == NULL) ||
10319 ((last_ins->opcode != OP_BR) &&
10320 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
10321 (last_ins->opcode != OP_SWITCH)))) {
10322 for (i = 0; i < previous_bb->out_count; i++) {
10323 if (previous_bb->out_bb [i] == target_bb) {
10325 MONO_INST_NEW (cfg, jump, OP_BR);
10326 MONO_ADD_INS (previous_bb, jump);
10327 jump->cil_code = previous_bb->cil_code;
10328 jump->inst_target_bb = target_bb;
10334 previous_bb->next_bb = bb->next_bb;
10335 nullify_basic_block (bb);
10344 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn)
10346 MonoInst *last_ins;
10348 bb->out_count = bbn->out_count;
10349 bb->out_bb = bbn->out_bb;
10351 replace_basic_block (bb, bbn, bb);
10353 last_ins = mono_inst_list_last (&bb->ins_list);
10355 /* Nullify branch at the end of bb */
10356 if (last_ins && MONO_IS_BRANCH_OP (last_ins))
10357 last_ins->opcode = OP_NOP;
10359 MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
10361 bb->next_bb = bbn->next_bb;
10362 nullify_basic_block (bbn);
10366 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
10368 MonoBasicBlock *bbn, *next;
10369 MonoInst *last_ins;
10371 next = bb->next_bb;
10373 /* Find the previous */
10374 for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
10376 if (bbn->next_bb) {
10377 bbn->next_bb = bb->next_bb;
10380 /* Find the last */
10381 for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
10384 bb->next_bb = NULL;
10386 last_ins = mono_inst_list_last (&bb->ins_list);
10389 if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
10392 MONO_INST_NEW (cfg, ins, OP_BR);
10393 MONO_ADD_INS (bb, ins);
10394 link_bblock (cfg, bb, next);
10395 ins->inst_target_bb = next;
10399 /* checks that a and b represent the same instructions, conservatively,
10400 * it can return FALSE also for two trees that are equal.
10401 * FIXME: also make sure there are no side effects.
10404 same_trees (MonoInst *a, MonoInst *b)
10407 if (a->opcode != b->opcode)
10409 arity = mono_burg_arity [a->opcode];
10411 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
10413 return same_trees (a->inst_left, b->inst_left);
10414 } else if (arity == 2) {
10415 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
10416 } else if (arity == 0) {
10417 switch (a->opcode) {
10419 return a->inst_c0 == b->inst_c0;
10428 get_unsigned_condbranch (int opcode)
10431 case CEE_BLE: return CEE_BLE_UN;
10432 case CEE_BLT: return CEE_BLT_UN;
10433 case CEE_BGE: return CEE_BGE_UN;
10434 case CEE_BGT: return CEE_BGT_UN;
10436 g_assert_not_reached ();
10441 tree_is_unsigned (MonoInst* ins) {
10442 switch (ins->opcode) {
10444 return (int)ins->inst_c0 >= 0;
10445 /* array lengths are positive as are string sizes */
10452 case CEE_CONV_OVF_U1:
10453 case CEE_CONV_OVF_U2:
10454 case CEE_CONV_OVF_U4:
10465 /* check if an unsigned compare can be used instead of two signed compares
10466 * for (val < 0 || val > limit) conditionals.
10467 * Returns TRUE if the optimization has been applied.
10468 * Note that this can't be applied if the second arg is not positive...
10471 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
10473 MonoBasicBlock *truet, *falset;
10474 MonoInst *cmp_inst = bb_last->inst_left;
10476 if (!cmp_inst->inst_right->inst_c0 == 0)
10478 truet = bb_last->inst_true_bb;
10479 falset = bb_last->inst_false_bb;
10480 if (falset->in_count != 1)
10482 condb = mono_inst_list_last (&falset->ins_list);
10483 /* target bb must have one instruction */
10484 if (!condb || (condb->node.next != &falset->ins_list))
10486 if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
10487 || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
10488 && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
10489 if (!tree_is_unsigned (condb->inst_left->inst_right))
10491 condb->opcode = get_unsigned_condbranch (condb->opcode);
10492 /* change the original condbranch to just point to the new unsigned check */
10493 bb_last->opcode = OP_BR;
10494 bb_last->inst_target_bb = falset;
10495 replace_out_block (bb, truet, NULL);
10496 replace_in_block (truet, bb, NULL);
10503 * Optimizes the branches on the Control Flow Graph
10507 optimize_branches (MonoCompile *cfg)
10509 int i, changed = FALSE;
10510 MonoBasicBlock *bb, *bbn;
10511 guint32 niterations;
10514 * Some crazy loops could cause the code below to go into an infinite
10515 * loop, see bug #53003 for an example. To prevent this, we put an upper
10516 * bound on the number of iterations.
10518 if (cfg->num_bblocks > 1000)
10519 niterations = cfg->num_bblocks * 2;
10521 niterations = 1000;
10524 MonoBasicBlock *previous_bb;
10528 /* we skip the entry block (exit is handled specially instead ) */
10529 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
10530 MonoInst *last_ins;
10532 /* dont touch code inside exception clauses */
10533 if (bb->region != -1)
10536 if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
10541 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10542 if (cfg->verbose_level > 2)
10543 g_print ("nullify block triggered %d\n", bbn->block_num);
10545 bb->next_bb = bbn->next_bb;
10547 for (i = 0; i < bbn->out_count; i++)
10548 replace_in_block (bbn->out_bb [i], bbn, NULL);
10550 nullify_basic_block (bbn);
10554 last_ins = mono_inst_list_last (&bb->ins_list);
10555 if (bb->out_count == 1) {
10556 bbn = bb->out_bb [0];
10558 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
10559 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
10561 MONO_INST_NEW (cfg, pop, CEE_POP);
10562 pop->inst_left = last_ins->inst_left->inst_left;
10563 mono_add_ins_to_end (bb, pop);
10564 MONO_INST_NEW (cfg, pop, CEE_POP);
10565 pop->inst_left = last_ins->inst_left->inst_right;
10566 mono_add_ins_to_end (bb, pop);
10567 last_ins->opcode = OP_BR;
10568 last_ins->inst_target_bb = last_ins->inst_true_bb;
10570 if (cfg->verbose_level > 2)
10571 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
10574 if (bb->region == bbn->region && bb->next_bb == bbn) {
10575 /* the block are in sequence anyway ... */
10577 /* branches to the following block can be removed */
10578 if (last_ins && last_ins->opcode == OP_BR) {
10579 last_ins->opcode = OP_NOP;
10581 if (cfg->verbose_level > 2)
10582 g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
10585 if (bbn->in_count == 1) {
10587 if (bbn != cfg->bb_exit) {
10588 if (cfg->verbose_level > 2)
10589 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
10590 merge_basic_blocks (bb, bbn);
10595 //mono_print_bb_code (bb);
10599 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10600 if (cfg->verbose_level > 2) {
10601 g_print ("nullify block triggered %d\n", bbn->block_num);
10603 bb->next_bb = bbn->next_bb;
10605 for (i = 0; i < bbn->out_count; i++)
10606 replace_in_block (bbn->out_bb [i], bbn, NULL);
10608 nullify_basic_block (bbn);
10613 if (bb->out_count == 1) {
10614 bbn = bb->out_bb [0];
10616 if (last_ins && last_ins->opcode == OP_BR) {
10617 MonoInst *bbn_code;
10619 bbn = last_ins->inst_target_bb;
10620 bbn_code = mono_inst_list_first (&bbn->ins_list);
10621 if (bb->region == bbn->region && bbn_code &&
10622 bbn_code->opcode == OP_BR &&
10623 bbn_code->inst_target_bb->region == bb->region) {
10624 if (cfg->verbose_level > 2)
10625 g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name,
10626 bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
10628 replace_in_block (bbn, bb, NULL);
10629 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
10630 link_bblock (cfg, bb, bbn_code->inst_target_bb);
10631 last_ins->inst_target_bb = bbn_code->inst_target_bb;
10636 } else if (bb->out_count == 2) {
10637 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
10638 int branch_result = mono_eval_cond_branch (last_ins);
10639 MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
10640 MonoInst *bbn_code;
10642 if (branch_result == BRANCH_TAKEN) {
10643 taken_branch_target = last_ins->inst_true_bb;
10644 untaken_branch_target = last_ins->inst_false_bb;
10645 } else if (branch_result == BRANCH_NOT_TAKEN) {
10646 taken_branch_target = last_ins->inst_false_bb;
10647 untaken_branch_target = last_ins->inst_true_bb;
10649 if (taken_branch_target) {
10650 /* if mono_eval_cond_branch () is ever taken to handle
10651 * non-constant values to compare, issue a pop here.
10653 last_ins->opcode = OP_BR;
10654 last_ins->inst_target_bb = taken_branch_target;
10655 mono_unlink_bblock (cfg, bb, untaken_branch_target);
10659 bbn = last_ins->inst_true_bb;
10660 bbn_code = mono_inst_list_first (&bbn->ins_list);
10661 if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
10662 bbn_code->inst_target_bb->region == bb->region) {
10663 if (cfg->verbose_level > 2)
10664 g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n",
10665 bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num,
10669 * Unlink, then relink bblocks to avoid various
10670 * tricky situations when the two targets of the branch
10671 * are equal, or will become equal after the change.
10673 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
10674 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
10676 last_ins->inst_true_bb = bbn_code->inst_target_bb;
10678 link_bblock (cfg, bb, last_ins->inst_true_bb);
10679 link_bblock (cfg, bb, last_ins->inst_false_bb);
10685 bbn = last_ins->inst_false_bb;
10686 bbn_code = mono_inst_list_first (&bbn->ins_list);
10687 if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
10688 bbn_code->inst_target_bb->region == bb->region) {
10689 if (cfg->verbose_level > 2)
10690 g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n",
10691 bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num,
10694 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
10695 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
10697 last_ins->inst_false_bb = bbn_code->inst_target_bb;
10699 link_bblock (cfg, bb, last_ins->inst_true_bb);
10700 link_bblock (cfg, bb, last_ins->inst_false_bb);
10707 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
10708 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
10709 if (try_unsigned_compare (cfg, bb, last_ins)) {
10710 /*g_print ("applied in bb %d (->%d) %s\n", bb->block_num, last_ins->inst_target_bb->block_num, mono_method_full_name (cfg->method, TRUE));*/
10716 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
10717 if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
10718 /* Reverse the branch */
10719 last_ins->opcode = reverse_branch_op (last_ins->opcode);
10720 bbn = last_ins->inst_false_bb;
10721 last_ins->inst_false_bb = last_ins->inst_true_bb;
10722 last_ins->inst_true_bb = bbn;
10724 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
10725 if (cfg->verbose_level > 2)
10726 g_print ("cbranch to throw block triggered %d.\n",
10732 } while (changed && (niterations > 0));
10737 mono_compile_create_vars (MonoCompile *cfg)
10739 MonoMethodSignature *sig;
10740 MonoMethodHeader *header;
10743 header = mono_method_get_header (cfg->method);
10745 sig = mono_method_signature (cfg->method);
10747 if (!MONO_TYPE_IS_VOID (sig->ret)) {
10748 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
10749 cfg->ret->opcode = OP_RETARG;
10750 cfg->ret->inst_vtype = sig->ret;
10751 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
10753 if (cfg->verbose_level > 2)
10754 g_print ("creating vars\n");
10756 cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
10759 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
10761 for (i = 0; i < sig->param_count; ++i) {
10762 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
10763 if (sig->params [i]->byref) {
10764 cfg->disable_ssa = TRUE;
10768 cfg->locals_start = cfg->num_varinfo;
10770 if (cfg->verbose_level > 2)
10771 g_print ("creating locals\n");
10773 for (i = 0; i < header->num_locals; ++i)
10774 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
10775 if (cfg->verbose_level > 2)
10776 g_print ("locals done\n");
10778 #ifdef MONO_ARCH_HAVE_CREATE_VARS
10779 mono_arch_create_vars (cfg);
10784 mono_print_code (MonoCompile *cfg)
10786 MonoBasicBlock *bb;
10788 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10791 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
10792 g_print ("CODE BLOCK %d (nesting %d):\n",
10793 bb->block_num, bb->nesting);
10795 MONO_BB_FOR_EACH_INS (bb, tree) {
10796 mono_print_tree (tree);
10802 extern const char * const mono_burg_rule_string [];
10805 emit_state (MonoCompile *cfg, MBState *state, int goal)
10807 MBState *kids [10];
10808 int ern = mono_burg_rule (state, goal);
10809 const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
10811 //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
10815 // state->reg1 = state->reg2; /* chain rule */
10817 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
10820 state->reg1 = mono_regstate_next_int (cfg->rs);
10821 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
10823 case MB_NTERM_lreg:
10824 state->reg1 = mono_regstate_next_int (cfg->rs);
10825 state->reg2 = mono_regstate_next_int (cfg->rs);
10827 case MB_NTERM_freg:
10828 #ifdef MONO_ARCH_SOFT_FLOAT
10829 state->reg1 = mono_regstate_next_int (cfg->rs);
10830 state->reg2 = mono_regstate_next_int (cfg->rs);
10832 state->reg1 = mono_regstate_next_float (cfg->rs);
10836 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
10838 * Enabling this might cause bugs to surface in the local register
10839 * allocators on some architectures like x86.
10841 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
10842 /* Do not optimize away reg-reg moves */
10843 if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
10844 state->right->reg1 = state->left->tree->dreg;
10853 mono_burg_kids (state, ern, kids);
10855 emit_state (cfg, kids [0], nts [0]);
10857 emit_state (cfg, kids [1], nts [1]);
10859 g_assert (!nts [3]);
10860 emit_state (cfg, kids [2], nts [2]);
10865 // g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
10866 mono_burg_emit (ern, state, state->tree, cfg);
10869 #define DEBUG_SELECTION
10872 mini_select_instructions (MonoCompile *cfg)
10874 MonoBasicBlock *bb;
10876 cfg->state_pool = mono_mempool_new ();
10877 cfg->rs = mono_regstate_new ();
10879 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10880 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
10882 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
10883 bb->next_bb != last_ins->inst_false_bb) {
10885 /* we are careful when inverting, since bugs like #59580
10886 * could show up when dealing with NaNs.
10888 if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
10889 MonoBasicBlock *tmp = last_ins->inst_true_bb;
10890 last_ins->inst_true_bb = last_ins->inst_false_bb;
10891 last_ins->inst_false_bb = tmp;
10893 last_ins->opcode = reverse_branch_op (last_ins->opcode);
10895 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
10896 inst->opcode = OP_BR;
10897 inst->inst_target_bb = last_ins->inst_false_bb;
10898 mono_bblock_add_inst (bb, inst);
10903 #ifdef DEBUG_SELECTION
10904 if (cfg->verbose_level >= 4) {
10905 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10907 g_print ("DUMP BLOCK %d:\n", bb->block_num);
10909 MONO_BB_FOR_EACH_INS (bb, tree) {
10910 mono_print_tree (tree);
10917 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10918 MonoInst *tree, *n;
10922 MONO_INST_LIST_INIT (&head);
10923 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
10925 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
10928 mono_regstate_reset (cfg->rs);
10930 #ifdef DEBUG_SELECTION
10931 if (cfg->verbose_level >= 3)
10932 g_print ("LABEL BLOCK %d:\n", bb->block_num);
10934 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
10935 #ifdef DEBUG_SELECTION
10936 if (cfg->verbose_level >= 3) {
10937 mono_print_tree (tree);
10942 if (!(mbstate = mono_burg_label (tree, cfg))) {
10943 g_warning ("unable to label tree %p", tree);
10944 mono_print_tree (tree);
10946 g_assert_not_reached ();
10948 emit_state (cfg, mbstate, MB_NTERM_stmt);
10950 bb->max_vreg = cfg->rs->next_vreg;
10952 mono_mempool_empty (cfg->state_pool);
10954 mono_mempool_destroy (cfg->state_pool);
10958 * mono_normalize_opcodes:
10960 * Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
10963 static gint16 *remap_table;
10965 #if SIZEOF_VOID_P == 8
10966 #define REMAP_OPCODE(opcode) OP_L ## opcode
10968 #define REMAP_OPCODE(opcode) OP_I ## opcode
10971 static G_GNUC_UNUSED void
10972 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
10976 if (!remap_table) {
10977 remap_table = g_new0 (gint16, OP_LAST);
10979 #if SIZEOF_VOID_P == 8
10980 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
10981 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
10982 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
10983 remap_table [CEE_CONV_I] = OP_SEXT_I4;
10984 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
10985 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
10988 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
10989 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
10990 remap_table [CEE_CONV_I4] = OP_MOVE;
10991 remap_table [CEE_CONV_U4] = OP_MOVE;
10992 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
10993 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
10994 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
10995 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
10996 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
10997 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
10998 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
10999 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11000 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11001 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11002 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11003 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11004 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11005 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11006 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11007 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11008 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11009 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11010 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11011 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11012 remap_table [CEE_CALL] = OP_CALL;
11013 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11014 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11015 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11016 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11017 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11018 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11019 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11020 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11021 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11022 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11023 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11024 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11025 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11026 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11027 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11028 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11031 MONO_BB_FOR_EACH_INS (bb, ins) {
11032 int remapped = remap_table [ins->opcode];
11034 ins->opcode = remapped;
11039 mono_codegen (MonoCompile *cfg)
11041 MonoJumpInfo *patch_info;
11042 MonoBasicBlock *bb;
11043 int i, max_epilog_size;
11046 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11047 cfg->spill_count = 0;
11048 /* we reuse dfn here */
11049 /* bb->dfn = bb_count++; */
11050 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11051 mono_normalize_opcodes (cfg, bb);
11054 mono_arch_lowering_pass (cfg, bb);
11056 if (cfg->opt & MONO_OPT_PEEPHOLE)
11057 mono_arch_peephole_pass_1 (cfg, bb);
11059 mono_local_regalloc (cfg, bb);
11061 if (cfg->opt & MONO_OPT_PEEPHOLE)
11062 mono_arch_peephole_pass_2 (cfg, bb);
11065 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11066 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11068 code = mono_arch_emit_prolog (cfg);
11070 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11071 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11073 cfg->code_len = code - cfg->native_code;
11074 cfg->prolog_end = cfg->code_len;
11076 mono_debug_open_method (cfg);
11078 /* emit code all basic blocks */
11079 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11080 bb->native_offset = cfg->code_len;
11081 mono_arch_output_basic_block (cfg, bb);
11083 if (bb == cfg->bb_exit) {
11084 cfg->epilog_begin = cfg->code_len;
11086 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11087 code = cfg->native_code + cfg->code_len;
11088 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11089 cfg->code_len = code - cfg->native_code;
11090 g_assert (cfg->code_len < cfg->code_size);
11093 mono_arch_emit_epilog (cfg);
11097 mono_arch_emit_exceptions (cfg);
11099 max_epilog_size = 0;
11101 code = cfg->native_code + cfg->code_len;
11103 /* we always allocate code in cfg->domain->code_mp to increase locality */
11104 cfg->code_size = cfg->code_len + max_epilog_size;
11105 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11107 if (cfg->method->dynamic) {
11108 /* Allocate the code into a separate memory pool so it can be freed */
11109 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11110 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11111 mono_domain_lock (cfg->domain);
11112 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11113 mono_domain_unlock (cfg->domain);
11115 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
11117 mono_domain_lock (cfg->domain);
11118 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
11119 mono_domain_unlock (cfg->domain);
11122 memcpy (code, cfg->native_code, cfg->code_len);
11123 g_free (cfg->native_code);
11124 cfg->native_code = code;
11125 code = cfg->native_code + cfg->code_len;
11127 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11128 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11129 switch (patch_info->type) {
11130 case MONO_PATCH_INFO_ABS: {
11131 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11133 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11134 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) &&
11135 strstr (cfg->method->name, info->name))
11137 * This is an icall wrapper, and this is a call to the
11138 * wrapped function.
11142 /* for these array methods we currently register the same function pointer
11143 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11144 * will return the incorrect one depending on the order they are registered.
11145 * See tests/test-arr.cs
11147 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11148 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11149 patch_info->data.name = info->name;
11154 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11156 patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11157 patch_info->data.klass = vtable->klass;
11159 MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11161 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11162 patch_info->data.klass = klass;
11168 case MONO_PATCH_INFO_SWITCH: {
11170 if (cfg->method->dynamic) {
11171 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11173 mono_domain_lock (cfg->domain);
11174 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11175 mono_domain_unlock (cfg->domain);
11178 if (!cfg->compile_aot)
11179 /* In the aot case, the patch already points to the correct location */
11180 patch_info->ip.i = patch_info->ip.label->inst_c0;
11181 for (i = 0; i < patch_info->data.table->table_size; i++) {
11182 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11184 patch_info->data.table->table = (MonoBasicBlock**)table;
11193 #ifdef VALGRIND_JIT_REGISTER_MAP
11194 if (valgrind_register){
11195 char* nm = mono_method_full_name (cfg->method, TRUE);
11196 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11201 if (cfg->verbose_level > 0) {
11202 char* nm = mono_method_full_name (cfg->method, TRUE);
11203 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
11205 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11209 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11210 mono_arch_save_unwind_info (cfg);
11213 mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11215 if (cfg->method->dynamic) {
11216 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11218 mono_domain_lock (cfg->domain);
11219 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11220 mono_domain_unlock (cfg->domain);
11223 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11225 mono_debug_close_method (cfg);
11231 remove_critical_edges (MonoCompile *cfg) {
11232 MonoBasicBlock *bb;
11233 MonoBasicBlock *previous_bb;
11235 if (cfg->verbose_level > 3) {
11236 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11237 MonoInst *last_ins;
11239 printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11240 for (i = 0; i < bb->in_count; i++) {
11241 printf (" %d", bb->in_bb [i]->block_num);
11243 printf (") (out:");
11244 for (i = 0; i < bb->out_count; i++) {
11245 printf (" %d", bb->out_bb [i]->block_num);
11248 last_ins = mono_inst_list_last (&bb->ins_list);
11251 mono_print_tree (last_ins);
11257 for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11258 if (bb->in_count > 1) {
11260 for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11261 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11262 if (in_bb->out_count > 1) {
11263 MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11264 MONO_INST_LIST_INIT (&new_bb->ins_list);
11265 new_bb->block_num = cfg->num_bblocks++;
11266 // new_bb->real_offset = bb->real_offset;
11267 new_bb->region = bb->region;
11269 /* Do not alter the CFG while altering the BB list */
11270 if (previous_bb->region == bb->region) {
11271 if (previous_bb != cfg->bb_entry) {
11272 MonoInst *last_ins;
11273 /* If previous_bb "followed through" to bb, */
11274 /* keep it linked with a OP_BR */
11275 last_ins = mono_inst_list_last (&previous_bb->ins_list);
11276 if ((last_ins == NULL) ||
11277 ((last_ins->opcode != OP_BR) &&
11278 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11279 (last_ins->opcode != OP_SWITCH))) {
11281 /* Make sure previous_bb really falls through bb */
11282 for (i = 0; i < previous_bb->out_count; i++) {
11283 if (previous_bb->out_bb [i] == bb) {
11285 MONO_INST_NEW (cfg, jump, OP_BR);
11286 MONO_ADD_INS (previous_bb, jump);
11287 jump->cil_code = previous_bb->cil_code;
11288 jump->inst_target_bb = bb;
11294 /* We cannot add any inst to the entry BB, so we must */
11295 /* put a new BB in the middle to hold the OP_BR */
11297 MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11298 MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
11299 new_bb_after_entry->block_num = cfg->num_bblocks++;
11300 // new_bb_after_entry->real_offset = bb->real_offset;
11301 new_bb_after_entry->region = bb->region;
11303 MONO_INST_NEW (cfg, jump, OP_BR);
11304 MONO_ADD_INS (new_bb_after_entry, jump);
11305 jump->cil_code = bb->cil_code;
11306 jump->inst_target_bb = bb;
11308 previous_bb->next_bb = new_bb_after_entry;
11309 previous_bb = new_bb_after_entry;
11311 if (cfg->verbose_level > 2) {
11312 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);
11317 /* Insert new_bb in the BB list */
11318 previous_bb->next_bb = new_bb;
11319 new_bb->next_bb = bb;
11320 previous_bb = new_bb;
11322 /* Setup in_bb and out_bb */
11323 new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11324 new_bb->in_bb [0] = in_bb;
11325 new_bb->in_count = 1;
11326 new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11327 new_bb->out_bb [0] = bb;
11328 new_bb->out_count = 1;
11330 /* Relink in_bb and bb to (from) new_bb */
11331 replace_out_block (in_bb, bb, new_bb);
11332 replace_out_block_in_code (in_bb, bb, new_bb);
11333 replace_in_block (bb, in_bb, new_bb);
11335 if (cfg->verbose_level > 2) {
11336 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);
11343 if (cfg->verbose_level > 3) {
11344 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11345 MonoInst *last_ins;
11347 printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11348 for (i = 0; i < bb->in_count; i++) {
11349 printf (" %d", bb->in_bb [i]->block_num);
11351 printf (") (out:");
11352 for (i = 0; i < bb->out_count; i++) {
11353 printf (" %d", bb->out_bb [i]->block_num);
11356 last_ins = mono_inst_list_last (&bb->ins_list);
11359 mono_print_tree (last_ins);
11367 * mini_method_compile:
11368 * @method: the method to compile
11369 * @opts: the optimization flags to use
11370 * @domain: the domain where the method will be compiled in
11371 * @run_cctors: whether we should run type ctors if possible
11372 * @compile_aot: whether this is an AOT compilation
11373 * @parts: debug flag
11375 * Returns: a MonoCompile* pointer. Caller must check the exception_type
11376 * field in the returned struct to see if compilation succeded.
11379 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
11381 MonoMethodHeader *header = mono_method_get_header (method);
11384 MonoJitInfo *jinfo;
11385 int dfn = 0, i, code_size_ratio;
11386 gboolean deadce_has_run = FALSE;
11387 gboolean try_generic_shared;
11388 MonoMethod *method_to_compile;
11391 mono_jit_stats.methods_compiled++;
11392 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
11393 mono_profiler_method_jit (method);
11396 /* We are passed the original generic method definition */
11397 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11398 (opts & MONO_OPT_GSHARED) && (method->generic_container || method->klass->generic_container);
11400 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11401 (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method);
11403 if (opts & MONO_OPT_GSHARED) {
11404 if (try_generic_shared)
11405 mono_stats.generics_sharable_methods++;
11406 else if (mono_method_is_generic_impl (method))
11407 mono_stats.generics_unsharable_methods++;
11411 if (try_generic_shared) {
11412 MonoMethod *declaring_method;
11413 MonoGenericContext *shared_context;
11416 declaring_method = method;
11418 declaring_method = mono_method_get_declaring_generic_method (method);
11419 g_assert (method->klass->generic_class->container_class == declaring_method->klass);
11422 if (declaring_method->generic_container)
11423 shared_context = &declaring_method->generic_container->context;
11425 shared_context = &declaring_method->klass->generic_container->context;
11427 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
11428 g_assert (method_to_compile);
11430 method_to_compile = method;
11433 cfg = g_new0 (MonoCompile, 1);
11434 cfg->method = method_to_compile;
11435 cfg->mempool = mono_mempool_new ();
11437 cfg->prof_options = mono_profiler_get_events ();
11438 cfg->run_cctors = run_cctors;
11439 cfg->domain = domain;
11440 cfg->verbose_level = mini_verbose;
11441 cfg->compile_aot = compile_aot;
11442 cfg->skip_visibility = method->skip_visibility;
11443 if (try_generic_shared)
11444 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
11445 cfg->token_info_hash = g_hash_table_new (NULL, NULL);
11447 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
11448 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
11449 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11450 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11454 ip = (guint8 *)header->code;
11456 cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
11457 cfg->aliasing_info = NULL;
11459 if (cfg->verbose_level > 2)
11460 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
11463 * create MonoInst* which represents arguments and local variables
11465 mono_compile_create_vars (cfg);
11467 if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
11468 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
11471 mono_destroy_compile (cfg);
11472 try_generic_shared = FALSE;
11473 goto restart_compile;
11475 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
11477 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11478 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11479 /* cfg contains the details of the failure, so let the caller cleanup */
11483 mono_jit_stats.basic_blocks += cfg->num_bblocks;
11484 mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
11486 if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
11488 * we disable some optimizations if there are too many variables
11489 * because JIT time may become too expensive. The actual number needs
11490 * to be tweaked and eventually the non-linear algorithms should be fixed.
11492 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
11493 cfg->disable_ssa = TRUE;
11496 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
11498 if (cfg->opt & MONO_OPT_BRANCH)
11499 optimize_branches (cfg);
11501 if (cfg->opt & MONO_OPT_SSAPRE) {
11502 remove_critical_edges (cfg);
11505 /* Depth-first ordering on basic blocks */
11506 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
11508 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
11509 if (cfg->num_bblocks != dfn + 1) {
11510 MonoBasicBlock *bb;
11512 cfg->num_bblocks = dfn + 1;
11514 if (!header->clauses) {
11515 /* remove unreachable code, because the code in them may be
11516 * inconsistent (access to dead variables for example) */
11517 for (bb = cfg->bb_entry; bb;) {
11518 MonoBasicBlock *bbn = bb->next_bb;
11520 if (bbn && bbn->region == -1 && !bbn->dfn) {
11521 if (cfg->verbose_level > 1)
11522 g_print ("found unreachable code in BB%d\n", bbn->block_num);
11523 bb->next_bb = bbn->next_bb;
11524 nullify_basic_block (bbn);
11532 if (cfg->opt & MONO_OPT_LOOP) {
11533 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
11534 mono_compute_natural_loops (cfg);
11537 /* after method_to_ir */
11541 //#define DEBUGSSA "logic_run"
11542 #define DEBUGSSA_CLASS "Tests"
11545 if (!header->num_clauses && !cfg->disable_ssa) {
11546 mono_local_cprop (cfg);
11547 #ifndef DISABLE_SSA
11548 mono_ssa_compute (cfg);
11553 /* fixme: add all optimizations which requires SSA */
11554 if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
11555 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
11556 mono_local_cprop (cfg);
11557 #ifndef DISABLE_SSA
11558 mono_ssa_compute (cfg);
11561 if (cfg->verbose_level >= 2) {
11568 /* after SSA translation */
11572 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
11573 if (cfg->comp_done & MONO_COMP_SSA) {
11574 #ifndef DISABLE_SSA
11575 mono_ssa_cprop (cfg);
11578 mono_local_cprop (cfg);
11582 #ifndef DISABLE_SSA
11583 if (cfg->comp_done & MONO_COMP_SSA) {
11584 //mono_ssa_deadce (cfg);
11586 //mono_ssa_strength_reduction (cfg);
11588 if (cfg->opt & MONO_OPT_SSAPRE) {
11589 mono_perform_ssapre (cfg);
11590 //mono_local_cprop (cfg);
11593 if (cfg->opt & MONO_OPT_DEADCE) {
11594 mono_ssa_deadce (cfg);
11595 deadce_has_run = TRUE;
11598 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
11599 mono_perform_abc_removal (cfg);
11601 mono_ssa_remove (cfg);
11603 if (cfg->opt & MONO_OPT_BRANCH)
11604 optimize_branches (cfg);
11608 /* after SSA removal */
11612 if (cfg->verbose_level > 4) {
11613 printf ("BEFORE DECOMPSE START\n");
11614 mono_print_code (cfg);
11615 printf ("BEFORE DECOMPSE END\n");
11618 decompose_pass (cfg);
11620 if (cfg->got_var) {
11623 g_assert (cfg->got_var_allocated);
11626 * Allways allocate the GOT var to a register, because keeping it
11627 * in memory will increase the number of live temporaries in some
11628 * code created by inssel.brg, leading to the well known spills+
11629 * branches problem. Testcase: mcs crash in
11630 * System.MonoCustomAttrs:GetCustomAttributes.
11632 regs = mono_arch_get_global_int_regs (cfg);
11634 cfg->got_var->opcode = OP_REGVAR;
11635 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
11636 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
11638 g_list_free (regs);
11641 /* todo: remove code when we have verified that the liveness for try/catch blocks
11645 * Currently, this can't be commented out since exception blocks are not
11646 * processed during liveness analysis.
11648 mono_liveness_handle_exception_clauses (cfg);
11650 if (cfg->opt & MONO_OPT_LINEARS) {
11651 GList *vars, *regs;
11653 /* For now, compute aliasing info only if needed for deadce... */
11654 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
11655 cfg->aliasing_info = mono_build_aliasing_information (cfg);
11658 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
11659 cfg->comp_done &= ~MONO_COMP_LIVENESS;
11660 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
11661 mono_analyze_liveness (cfg);
11663 if (cfg->aliasing_info != NULL) {
11664 mono_aliasing_deadce (cfg->aliasing_info);
11665 deadce_has_run = TRUE;
11668 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
11669 regs = mono_arch_get_global_int_regs (cfg);
11671 regs = g_list_delete_link (regs, regs);
11672 mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
11675 if (cfg->aliasing_info != NULL) {
11676 mono_destroy_aliasing_information (cfg->aliasing_info);
11677 cfg->aliasing_info = NULL;
11681 //mono_print_code (cfg);
11685 /* variables are allocated after decompose, since decompose could create temps */
11686 mono_arch_allocate_vars (cfg);
11688 if (cfg->opt & MONO_OPT_CFOLD)
11689 mono_constant_fold (cfg);
11691 mini_select_instructions (cfg);
11693 mono_codegen (cfg);
11694 if (cfg->verbose_level >= 2) {
11695 char *id = mono_method_full_name (cfg->method, FALSE);
11696 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
11700 if (cfg->generic_sharing_context)
11701 gsctx_size = sizeof (MonoGenericSharingContext*);
11705 if (cfg->method->dynamic) {
11706 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
11709 /* we access cfg->domain->mp */
11710 mono_domain_lock (cfg->domain);
11711 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
11712 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
11714 mono_domain_unlock (cfg->domain);
11717 jinfo->method = method;
11718 jinfo->code_start = cfg->native_code;
11719 jinfo->code_size = cfg->code_len;
11720 jinfo->used_regs = cfg->used_int_regs;
11721 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
11722 jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
11723 jinfo->num_clauses = header->num_clauses;
11725 if (cfg->generic_sharing_context) {
11726 jinfo->has_generic_sharing_context = 1;
11727 mono_jit_info_set_generic_sharing_context (jinfo, cfg->generic_sharing_context);
11730 if (header->num_clauses) {
11733 for (i = 0; i < header->num_clauses; i++) {
11734 MonoExceptionClause *ec = &header->clauses [i];
11735 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
11736 MonoBasicBlock *tblock;
11739 ei->flags = ec->flags;
11741 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
11742 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
11744 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
11745 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
11747 ei->data.filter = cfg->native_code + tblock->native_offset;
11749 ei->data.catch_class = ec->data.catch_class;
11752 tblock = cfg->cil_offset_to_bb [ec->try_offset];
11754 ei->try_start = cfg->native_code + tblock->native_offset;
11755 g_assert (tblock->native_offset);
11756 tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
11758 ei->try_end = cfg->native_code + tblock->native_offset;
11759 g_assert (tblock->native_offset);
11760 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
11762 ei->handler_start = cfg->native_code + tblock->native_offset;
11766 cfg->jit_info = jinfo;
11767 #if defined(__arm__)
11768 mono_arch_fixup_jinfo (cfg);
11771 mono_domain_lock (cfg->domain);
11772 mono_jit_info_table_add (cfg->domain, jinfo);
11774 if (cfg->method->dynamic)
11775 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
11776 mono_domain_unlock (cfg->domain);
11778 /* collect statistics */
11779 mono_jit_stats.allocated_code_size += cfg->code_len;
11780 code_size_ratio = cfg->code_len;
11781 if (code_size_ratio > mono_jit_stats.biggest_method_size) {
11782 mono_jit_stats.biggest_method_size = code_size_ratio;
11783 mono_jit_stats.biggest_method = method;
11785 code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
11786 if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
11787 mono_jit_stats.max_code_size_ratio = code_size_ratio;
11788 mono_jit_stats.max_ratio_method = method;
11790 mono_jit_stats.native_code_size += cfg->code_len;
11792 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11793 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
11798 static MonoJitInfo*
11799 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
11801 MonoMethod *open_method;
11803 if (!mono_method_is_generic_sharable_impl (method))
11806 open_method = mono_method_get_declaring_generic_method (method);
11808 return mono_domain_lookup_shared_generic (domain, open_method);
11811 static MonoJitInfo*
11812 lookup_method (MonoDomain *domain, MonoMethod *method)
11814 MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
11819 return lookup_generic_method (domain, method);
11823 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
11826 gpointer code = NULL;
11829 #ifdef MONO_USE_AOT_COMPILER
11830 if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
11831 MonoDomain *domain = mono_domain_get ();
11833 mono_class_init (method->klass);
11835 mono_domain_lock (domain);
11836 if ((code = mono_aot_get_method (domain, method))) {
11837 mono_domain_unlock (domain);
11838 mono_runtime_class_init (mono_class_vtable (domain, method->klass));
11842 mono_domain_unlock (domain);
11846 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
11847 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
11849 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
11851 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE && !MONO_CLASS_IS_IMPORT(method->klass))
11852 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);
11854 if (!piinfo->addr) {
11855 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
11856 piinfo->addr = mono_lookup_internal_call (method);
11858 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
11859 mono_lookup_pinvoke_call (method, NULL, NULL);
11861 nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
11862 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11864 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE)
11865 //mono_debug_add_wrapper (method, nm);
11866 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
11867 const char *name = method->name;
11870 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
11871 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
11872 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
11874 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
11875 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
11876 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
11877 return mono_create_delegate_trampoline (method->klass);
11879 nm = mono_marshal_get_delegate_invoke (method, NULL);
11880 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11882 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
11883 nm = mono_marshal_get_delegate_begin_invoke (method);
11884 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11885 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
11886 nm = mono_marshal_get_delegate_end_invoke (method);
11887 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11893 cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
11895 switch (cfg->exception_type) {
11896 case MONO_EXCEPTION_NONE: break;
11897 case MONO_EXCEPTION_TYPE_LOAD:
11898 case MONO_EXCEPTION_MISSING_FIELD:
11899 case MONO_EXCEPTION_MISSING_METHOD:
11900 case MONO_EXCEPTION_FILE_NOT_FOUND: {
11901 /* Throw a type load exception if needed */
11902 MonoLoaderError *error = mono_loader_get_last_error ();
11906 ex = mono_loader_error_prepare_exception (error);
11908 if (cfg->exception_ptr) {
11909 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
11911 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
11912 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
11913 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
11914 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
11915 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
11916 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
11917 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
11918 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
11920 g_assert_not_reached ();
11923 mono_destroy_compile (cfg);
11924 mono_raise_exception (ex);
11927 case MONO_EXCEPTION_INVALID_PROGRAM: {
11928 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
11929 mono_destroy_compile (cfg);
11930 mono_raise_exception (ex);
11933 case MONO_EXCEPTION_UNVERIFIABLE_IL: {
11934 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
11935 mono_destroy_compile (cfg);
11936 mono_raise_exception (ex);
11939 case MONO_EXCEPTION_METHOD_ACCESS: {
11940 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
11941 mono_destroy_compile (cfg);
11942 mono_raise_exception (ex);
11945 case MONO_EXCEPTION_FIELD_ACCESS: {
11946 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
11947 mono_destroy_compile (cfg);
11948 mono_raise_exception (ex);
11951 /* this can only be set if the security manager is active */
11952 case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
11953 MonoSecurityManager* secman = mono_security_manager_get_methods ();
11954 MonoObject *exc = NULL;
11957 args [0] = &cfg->exception_data;
11958 args [1] = &method;
11959 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
11961 mono_destroy_compile (cfg);
11964 mono_raise_exception ((MonoException*)exc);
11967 g_assert_not_reached ();
11970 mono_domain_lock (target_domain);
11972 /* Check if some other thread already did the job. In this case, we can
11973 discard the code this thread generated. */
11975 if ((info = lookup_method (target_domain, method))) {
11976 /* We can't use a domain specific method in another domain */
11977 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
11978 code = info->code_start;
11979 // printf("Discarding code for method %s\n", method->name);
11983 if (code == NULL) {
11984 mono_internal_hash_table_insert (&target_domain->jit_code_hash, method, cfg->jit_info);
11985 code = cfg->native_code;
11987 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method)) {
11988 /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
11989 mono_domain_register_shared_generic (target_domain,
11990 mono_method_get_declaring_generic_method (method), cfg->jit_info);
11991 mono_stats.generics_shared_methods++;
11995 mono_destroy_compile (cfg);
11997 if (target_domain->jump_target_hash) {
11998 MonoJumpInfo patch_info;
11999 GSList *list, *tmp;
12000 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12002 patch_info.next = NULL;
12003 patch_info.ip.i = 0;
12004 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12005 patch_info.data.method = method;
12006 g_hash_table_remove (target_domain->jump_target_hash, method);
12008 for (tmp = list; tmp; tmp = tmp->next)
12009 mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12010 g_slist_free (list);
12013 mono_domain_unlock (target_domain);
12015 mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
12020 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12022 MonoDomain *target_domain, *domain = mono_domain_get ();
12025 MonoJitICallInfo *callinfo = NULL;
12028 * ICALL wrappers are handled specially, since there is only one copy of them
12029 * shared by all appdomains.
12031 if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12032 const char *icall_name;
12034 icall_name = method->name + strlen ("__icall_wrapper_");
12035 g_assert (icall_name);
12036 callinfo = mono_find_jit_icall_by_name (icall_name);
12037 g_assert (callinfo);
12039 /* Must be domain neutral since there is only one copy */
12040 opt |= MONO_OPT_SHARED;
12043 if (opt & MONO_OPT_SHARED)
12044 target_domain = mono_get_root_domain ();
12046 target_domain = domain;
12048 mono_domain_lock (target_domain);
12050 if ((info = lookup_method (target_domain, method))) {
12051 /* We can't use a domain specific method in another domain */
12052 if (! ((domain != target_domain) && !info->domain_neutral)) {
12053 mono_domain_unlock (target_domain);
12054 mono_jit_stats.methods_lookups++;
12055 mono_runtime_class_init (mono_class_vtable (domain, method->klass));
12056 return mono_create_ftnptr (target_domain, info->code_start);
12060 mono_domain_unlock (target_domain);
12061 p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12065 if (!callinfo->wrapper) {
12066 callinfo->wrapper = p;
12067 mono_register_jit_icall_wrapper (callinfo, p);
12068 mono_debug_add_icall_wrapper (method, callinfo);
12070 mono_jit_unlock ();
12077 mono_jit_compile_method (MonoMethod *method)
12079 return mono_jit_compile_method_with_opt (method, default_opt);
12083 invalidated_delegate_trampoline (char *desc)
12085 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12086 "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12091 * mono_jit_free_method:
12093 * Free all memory allocated by the JIT for METHOD.
12096 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
12098 MonoJitDynamicMethodInfo *ji;
12099 gboolean destroy = TRUE;
12101 g_assert (method->dynamic);
12103 mono_domain_lock (domain);
12104 ji = mono_dynamic_code_hash_lookup (domain, method);
12105 mono_domain_unlock (domain);
12109 mono_domain_lock (domain);
12110 g_hash_table_remove (domain->dynamic_code_hash, method);
12111 mono_internal_hash_table_remove (&domain->jit_code_hash, method);
12112 g_hash_table_remove (domain->jump_trampoline_hash, method);
12113 mono_domain_unlock (domain);
12115 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12116 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
12118 * Instead of freeing the code, change it to call an error routine
12119 * so people can fix their code.
12121 char *type = mono_type_full_name (&method->klass->byval_arg);
12122 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
12125 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
12131 * This needs to be done before freeing code_mp, since the code address is the
12132 * key in the table, so if we free the code_mp first, another thread can grab the
12133 * same code address and replace our entry in the table.
12135 mono_jit_info_table_remove (domain, ji->ji);
12138 mono_code_manager_destroy (ji->code_mp);
12139 mono_thread_hazardous_free_or_queue (ji->ji, g_free);
12144 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
12146 MonoDomain *target_domain;
12149 if (default_opt & MONO_OPT_SHARED)
12150 target_domain = mono_get_root_domain ();
12152 target_domain = domain;
12154 mono_domain_lock (target_domain);
12156 if ((info = lookup_method (target_domain, method))) {
12157 /* We can't use a domain specific method in another domain */
12158 if (! ((domain != target_domain) && !info->domain_neutral)) {
12159 mono_domain_unlock (target_domain);
12160 mono_jit_stats.methods_lookups++;
12161 return info->code_start;
12165 mono_domain_unlock (target_domain);
12171 * mono_jit_runtime_invoke:
12172 * @method: the method to invoke
12173 * @obj: this pointer
12174 * @params: array of parameter values.
12175 * @exc: used to catch exceptions objects
12178 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
12180 MonoMethod *invoke;
12181 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
12182 void* compiled_method;
12184 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
12185 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
12189 invoke = mono_marshal_get_runtime_invoke (method);
12190 runtime_invoke = mono_jit_compile_method (invoke);
12192 /* We need this here becuase mono_marshal_get_runtime_invoke can be place
12193 * the helper method in System.Object and not the target class
12195 mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
12197 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
12198 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
12200 * Array Get/Set/Address methods. The JIT implements them using inline code
12201 * inside the runtime invoke wrappers, so no need to compile them.
12203 compiled_method = NULL;
12205 compiled_method = mono_jit_compile_method (method);
12207 return runtime_invoke (obj, params, exc, compiled_method);
12210 #ifdef MONO_GET_CONTEXT
12211 #define GET_CONTEXT MONO_GET_CONTEXT
12214 #ifndef GET_CONTEXT
12215 #ifdef PLATFORM_WIN32
12216 #define GET_CONTEXT \
12217 struct sigcontext *ctx = (struct sigcontext*)_dummy;
12219 #ifdef MONO_ARCH_USE_SIGACTION
12220 #define GET_CONTEXT \
12221 void *ctx = context;
12222 #elif defined(__sparc__)
12223 #define GET_CONTEXT \
12224 void *ctx = sigctx;
12226 #define GET_CONTEXT \
12227 void **_p = (void **)&_dummy; \
12228 struct sigcontext *ctx = (struct sigcontext *)++_p;
12233 #ifdef MONO_ARCH_USE_SIGACTION
12234 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
12235 #elif defined(__sparc__)
12236 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
12238 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
12242 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
12244 MonoException *exc = NULL;
12245 #ifndef MONO_ARCH_USE_SIGACTION
12250 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
12251 if (mono_arch_is_int_overflow (ctx, info))
12252 exc = mono_get_exception_arithmetic ();
12254 exc = mono_get_exception_divide_by_zero ();
12256 exc = mono_get_exception_divide_by_zero ();
12259 mono_arch_handle_exception (ctx, exc, FALSE);
12263 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
12265 MonoException *exc;
12268 exc = mono_get_exception_execution_engine ("SIGILL");
12270 mono_arch_handle_exception (ctx, exc, FALSE);
12274 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
12276 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12277 MonoException *exc = NULL;
12281 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12282 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
12286 #ifdef MONO_ARCH_USE_SIGACTION
12287 if (debug_options.collect_pagefault_stats) {
12288 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
12289 mono_raw_buffer_handle_pagefault (info->si_addr);
12292 if (mono_aot_is_pagefault (info->si_addr)) {
12293 mono_aot_handle_pagefault (info->si_addr);
12299 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
12301 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12302 /* we got a stack overflow in the soft-guard pages
12303 * There are two cases:
12304 * 1) managed code caused the overflow: we unprotect the soft-guard page
12305 * and let the arch-specific code trigger the exception handling mechanism
12306 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
12307 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
12308 * and hope we can continue with those enabled, at least until the hard-guard page
12309 * is hit. The alternative to continuing here is to just print a message and abort.
12310 * We may add in the future the code to protect the pages again in the codepath
12311 * when we return from unmanaged to managed code.
12313 if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
12314 (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
12315 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
12317 mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
12319 /* We print a message: after this even managed stack overflows
12320 * may crash the runtime
12322 fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12326 /* The hard-guard page has been hit: there is not much we can do anymore
12327 * Print a hopefully clear message and abort.
12329 if (jit_tls->stack_size &&
12330 ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
12331 const char *method;
12332 /* we don't do much now, but we can warn the user with a useful message */
12333 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12334 if (ji && ji->method)
12335 method = mono_method_full_name (ji->method, TRUE);
12337 method = "Unmanaged";
12338 fprintf (stderr, "At %s\n", method);
12341 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
12346 mono_handle_native_sigsegv (SIGSEGV, ctx);
12349 mono_arch_handle_exception (ctx, exc, FALSE);
12353 #ifndef PLATFORM_WIN32
12356 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
12361 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12363 mono_handle_native_sigsegv (SIGABRT, ctx);
12368 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
12370 gboolean running_managed;
12371 MonoException *exc;
12372 MonoThread *thread = mono_thread_current ();
12377 if (thread->thread_dump_requested) {
12378 thread->thread_dump_requested = FALSE;
12380 mono_print_thread_dump (ctx);
12385 * This is an async signal, so the code below must not call anything which
12386 * is not async safe. That includes the pthread locking functions. If we
12387 * know that we interrupted managed code, then locking is safe.
12389 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12390 running_managed = ji != NULL;
12392 exc = mono_thread_request_interruption (running_managed);
12395 mono_arch_handle_exception (ctx, exc, FALSE);
12399 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
12403 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
12407 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
12411 printf ("Full thread dump:\n");
12413 mono_threads_request_thread_dump ();
12416 * print_thread_dump () skips the current thread, since sending a signal
12417 * to it would invoke the signal handler below the sigquit signal handler,
12418 * and signal handlers don't create an lmf, so the stack walk could not
12421 mono_print_thread_dump (ctx);
12425 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
12427 gboolean enabled = mono_trace_is_enabled ();
12429 mono_trace_enable (!enabled);
12435 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
12437 MonoException *exc;
12440 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
12442 mono_arch_handle_exception (ctx, exc, FALSE);
12445 #ifdef PLATFORM_MACOSX
12448 * This code disables the CrashReporter of MacOS X by installing
12449 * a dummy Mach exception handler.
12453 * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
12457 exc_server (mach_msg_header_t *request_msg,
12458 mach_msg_header_t *reply_msg);
12461 * The exception message
12464 mach_msg_base_t msg; /* common mach message header */
12465 char payload [1024]; /* opaque */
12466 } mach_exception_msg_t;
12468 /* The exception port */
12469 static mach_port_t mach_exception_port = VM_MAP_NULL;
12472 * Implicitly called by exc_server. Must be public.
12474 * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
12477 catch_exception_raise (
12478 mach_port_t exception_port,
12479 mach_port_t thread,
12481 exception_type_t exception,
12482 exception_data_t code,
12483 mach_msg_type_number_t code_count)
12485 /* consume the exception */
12486 return KERN_FAILURE;
12490 * Exception thread handler.
12494 mach_exception_thread (void *arg)
12497 mach_exception_msg_t request;
12498 mach_exception_msg_t reply;
12499 mach_msg_return_t result;
12501 /* receive from "mach_exception_port" */
12502 result = mach_msg (&request.msg.header,
12503 MACH_RCV_MSG | MACH_RCV_LARGE,
12506 mach_exception_port,
12507 MACH_MSG_TIMEOUT_NONE,
12510 g_assert (result == MACH_MSG_SUCCESS);
12512 /* dispatch to catch_exception_raise () */
12513 exc_server (&request.msg.header, &reply.msg.header);
12515 /* send back to sender */
12516 result = mach_msg (&reply.msg.header,
12518 reply.msg.header.msgh_size,
12521 MACH_MSG_TIMEOUT_NONE,
12524 g_assert (result == MACH_MSG_SUCCESS);
12530 macosx_register_exception_handler ()
12533 pthread_attr_t attr;
12536 if (mach_exception_port != VM_MAP_NULL)
12539 task = mach_task_self ();
12541 /* create the "mach_exception_port" with send & receive rights */
12542 g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
12543 &mach_exception_port) == KERN_SUCCESS);
12544 g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
12545 MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
12547 /* create the exception handler thread */
12548 g_assert (!pthread_attr_init (&attr));
12549 g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
12550 g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
12551 pthread_attr_destroy (&attr);
12554 * register "mach_exception_port" as a receiver for the
12555 * EXC_BAD_ACCESS exception
12557 * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
12559 g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
12560 mach_exception_port,
12562 MACHINE_THREAD_STATE) == KERN_SUCCESS);
12566 #ifndef PLATFORM_WIN32
12568 add_signal_handler (int signo, gpointer handler)
12570 struct sigaction sa;
12572 #ifdef MONO_ARCH_USE_SIGACTION
12573 sa.sa_sigaction = handler;
12574 sigemptyset (&sa.sa_mask);
12575 sa.sa_flags = SA_SIGINFO;
12576 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12577 if (signo == SIGSEGV)
12578 sa.sa_flags |= SA_ONSTACK;
12581 sa.sa_handler = handler;
12582 sigemptyset (&sa.sa_mask);
12585 g_assert (sigaction (signo, &sa, NULL) != -1);
12589 remove_signal_handler (int signo)
12591 struct sigaction sa;
12593 sa.sa_handler = SIG_DFL;
12594 sigemptyset (&sa.sa_mask);
12597 g_assert (sigaction (signo, &sa, NULL) != -1);
12602 mono_runtime_install_handlers (void)
12604 #ifdef PLATFORM_WIN32
12606 win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
12607 win32_seh_set_handler(SIGILL, sigill_signal_handler);
12608 win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
12609 if (debug_options.handle_sigint)
12610 win32_seh_set_handler(SIGINT, sigint_signal_handler);
12612 #else /* !PLATFORM_WIN32 */
12615 #ifdef PLATFORM_MACOSX
12616 macosx_register_exception_handler ();
12619 if (debug_options.handle_sigint)
12620 add_signal_handler (SIGINT, sigint_signal_handler);
12622 add_signal_handler (SIGFPE, sigfpe_signal_handler);
12623 add_signal_handler (SIGQUIT, sigquit_signal_handler);
12624 add_signal_handler (SIGILL, sigill_signal_handler);
12625 add_signal_handler (SIGBUS, sigsegv_signal_handler);
12626 if (mono_jit_trace_calls != NULL)
12627 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
12629 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
12630 signal (SIGPIPE, SIG_IGN);
12632 add_signal_handler (SIGABRT, sigabrt_signal_handler);
12634 /* catch SIGSEGV */
12635 add_signal_handler (SIGSEGV, sigsegv_signal_handler);
12636 #endif /* PLATFORM_WIN32 */
12640 mono_runtime_cleanup_handlers (void)
12642 #ifdef PLATFORM_WIN32
12643 win32_seh_cleanup();
12645 if (debug_options.handle_sigint)
12646 remove_signal_handler (SIGINT);
12648 remove_signal_handler (SIGFPE);
12649 remove_signal_handler (SIGQUIT);
12650 remove_signal_handler (SIGILL);
12651 remove_signal_handler (SIGBUS);
12652 if (mono_jit_trace_calls != NULL)
12653 remove_signal_handler (SIGUSR2);
12655 remove_signal_handler (mono_thread_get_abort_signal ());
12657 remove_signal_handler (SIGABRT);
12659 remove_signal_handler (SIGSEGV);
12660 #endif /* PLATFORM_WIN32 */
12664 #ifdef HAVE_LINUX_RTC_H
12665 #include <linux/rtc.h>
12666 #include <sys/ioctl.h>
12668 static int rtc_fd = -1;
12671 enable_rtc_timer (gboolean enable)
12674 flags = fcntl (rtc_fd, F_GETFL);
12676 perror ("getflags");
12683 if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
12684 perror ("setflags");
12691 #ifdef PLATFORM_WIN32
12692 static HANDLE win32_main_thread;
12693 static MMRESULT win32_timer;
12695 static void CALLBACK
12696 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
12700 context.ContextFlags = CONTEXT_CONTROL;
12701 if (GetThreadContext (win32_main_thread, &context)) {
12703 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
12705 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
12712 setup_stat_profiler (void)
12715 struct itimerval itval;
12716 static int inited = 0;
12717 #ifdef HAVE_LINUX_RTC_H
12718 const char *rtc_freq;
12719 if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
12723 freq = atoi (rtc_freq);
12726 rtc_fd = open ("/dev/rtc", O_RDONLY);
12727 if (rtc_fd == -1) {
12728 perror ("open /dev/rtc");
12731 add_signal_handler (SIGPROF, sigprof_signal_handler);
12732 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
12733 perror ("set rtc freq");
12736 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
12737 perror ("start rtc");
12740 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
12744 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
12748 enable_rtc_timer (TRUE);
12755 itval.it_interval.tv_usec = 999;
12756 itval.it_interval.tv_sec = 0;
12757 itval.it_value = itval.it_interval;
12758 setitimer (ITIMER_PROF, &itval, NULL);
12762 add_signal_handler (SIGPROF, sigprof_signal_handler);
12763 #elif defined (PLATFORM_WIN32)
12764 static int inited = 0;
12771 if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
12774 if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
12777 if (timeBeginPeriod (1) != TIMERR_NOERROR)
12780 if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
12787 /* mono_jit_create_remoting_trampoline:
12788 * @method: pointer to the method info
12790 * Creates a trampoline which calls the remoting functions. This
12791 * is used in the vtable of transparent proxies.
12793 * Returns: a pointer to the newly created code
12796 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
12799 guint8 *addr = NULL;
12801 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
12802 (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
12803 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
12804 addr = mono_compile_method (nm);
12806 addr = mono_compile_method (method);
12808 return mono_get_addr_from_ftnptr (addr);
12811 #ifdef MONO_ARCH_HAVE_IMT
12813 mini_get_imt_trampoline (void)
12815 static gpointer tramp = NULL;
12817 tramp = mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
12822 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
12824 mini_get_vtable_trampoline (void)
12826 static gpointer tramp = NULL;
12828 tramp = mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
12834 mini_parse_debug_options (void)
12836 char *options = getenv ("MONO_DEBUG");
12837 gchar **args, **ptr;
12842 args = g_strsplit (options, ",", -1);
12844 for (ptr = args; ptr && *ptr; ptr++) {
12845 const char *arg = *ptr;
12847 if (!strcmp (arg, "handle-sigint"))
12848 debug_options.handle_sigint = TRUE;
12849 else if (!strcmp (arg, "keep-delegates"))
12850 debug_options.keep_delegates = TRUE;
12851 else if (!strcmp (arg, "collect-pagefault-stats"))
12852 debug_options.collect_pagefault_stats = TRUE;
12853 else if (!strcmp (arg, "break-on-unverified"))
12854 debug_options.break_on_unverified = TRUE;
12856 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
12857 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified'\n");
12864 mini_init (const char *filename, const char *runtime_version)
12866 MonoDomain *domain;
12869 if (access ("/proc/self/maps", F_OK) != 0) {
12870 g_print ("Mono requires /proc to be mounted.\n");
12875 /* Happens when using the embedding interface */
12876 if (!default_opt_set)
12877 default_opt = mono_parse_default_optimizations (NULL);
12879 InitializeCriticalSection (&jit_mutex);
12881 if (!global_codeman)
12882 global_codeman = mono_code_manager_new ();
12883 jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12885 mono_arch_cpu_init ();
12889 mono_init_trampolines ();
12891 mono_init_exceptions ();
12893 if (!g_thread_supported ())
12894 g_thread_init (NULL);
12896 if (getenv ("MONO_DEBUG") != NULL)
12897 mini_parse_debug_options ();
12899 mono_gc_base_init ();
12901 mono_jit_tls_id = TlsAlloc ();
12902 setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
12906 if (default_opt & MONO_OPT_AOT)
12909 mono_runtime_install_handlers ();
12910 mono_threads_install_cleanup (mini_thread_cleanup);
12912 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
12913 // This is experimental code so provide an env var to switch it off
12914 if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
12915 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
12917 check_for_pending_exc = FALSE;
12918 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
12922 #define JIT_TRAMPOLINES_WORK
12923 #ifdef JIT_TRAMPOLINES_WORK
12924 mono_install_compile_method (mono_jit_compile_method);
12925 mono_install_free_method (mono_jit_free_method);
12926 mono_install_trampoline (mono_create_jit_trampoline);
12927 mono_install_jump_trampoline (mono_create_jump_trampoline);
12928 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
12929 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
12931 #define JIT_INVOKE_WORKS
12932 #ifdef JIT_INVOKE_WORKS
12933 mono_install_runtime_invoke (mono_jit_runtime_invoke);
12934 mono_install_handler (mono_arch_get_throw_exception ());
12936 mono_install_stack_walk (mono_jit_walk_stack);
12937 mono_install_init_vtable (mono_aot_init_vtable);
12938 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
12939 mono_install_get_class_from_name (mono_aot_get_class_from_name);
12940 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
12942 if (debug_options.collect_pagefault_stats) {
12943 mono_raw_buffer_set_make_unreadable (TRUE);
12944 mono_aot_set_make_unreadable (TRUE);
12947 if (runtime_version)
12948 domain = mono_init_version (filename, runtime_version);
12950 domain = mono_init_from_assembly (filename, filename);
12951 #ifdef MONO_ARCH_HAVE_IMT
12952 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
12953 mono_install_imt_trampoline (mini_get_imt_trampoline ());
12954 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
12955 mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
12958 mono_icall_init ();
12960 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
12961 ves_icall_get_frame_info);
12962 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
12963 ves_icall_get_trace);
12964 mono_add_internal_call ("System.Exception::get_trace",
12965 ves_icall_System_Exception_get_trace);
12966 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
12967 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
12968 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
12969 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
12970 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
12971 mono_runtime_install_handlers);
12974 create_helper_signature ();
12976 #define JIT_CALLS_WORK
12977 #ifdef JIT_CALLS_WORK
12978 /* Needs to be called here since register_jit_icall depends on it */
12979 mono_marshal_init ();
12981 mono_arch_register_lowlevel_calls ();
12982 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
12983 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
12984 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
12985 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
12986 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
12987 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
12988 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
12990 register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
12991 register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
12992 register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE);
12993 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
12994 register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception",
12997 register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
12998 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
12999 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
13000 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
13001 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
13004 * NOTE, NOTE, NOTE, NOTE:
13005 * when adding emulation for some opcodes, remember to also add a dummy
13006 * rule to the burg files, because we need the arity information to be correct.
13008 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
13009 mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
13010 mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
13011 mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
13012 mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
13013 mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
13014 mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
13015 mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
13018 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
13019 mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
13020 mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
13021 mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
13024 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13025 mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
13026 mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
13027 mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
13028 mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
13031 #ifdef MONO_ARCH_EMULATE_MUL_DIV
13032 mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
13033 mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
13034 mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
13036 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
13037 mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
13040 mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
13041 mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
13042 mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
13043 mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
13045 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
13046 mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
13048 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
13049 mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
13051 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
13052 mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
13054 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
13055 mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
13057 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
13058 mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
13060 #ifdef MONO_ARCH_EMULATE_FREM
13061 mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
13064 #ifdef MONO_ARCH_SOFT_FLOAT
13065 mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
13066 mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
13067 mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
13068 mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
13069 mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
13070 mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
13071 mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
13072 mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
13073 mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
13074 mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
13075 mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
13076 mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
13078 mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
13079 mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
13080 mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
13081 mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
13082 mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
13083 mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
13084 mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
13085 mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
13086 mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
13087 mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
13089 mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
13090 mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
13091 mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
13092 mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
13093 mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
13095 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
13096 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
13097 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
13100 #if SIZEOF_VOID_P == 4
13101 mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
13104 /* other jit icalls */
13105 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
13106 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
13107 "ptr ptr ptr", FALSE);
13108 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
13109 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
13110 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
13111 register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
13112 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
13113 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
13114 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
13115 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
13116 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
13117 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
13118 register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
13119 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
13120 register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
13121 register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
13122 register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
13123 register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
13124 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
13125 register_icall (mono_helper_get_rgctx_other_ptr, "get_rgctx_other_ptr", "ptr ptr ptr int32 int32", FALSE);
13126 register_icall (mono_break, "mono_break", NULL, TRUE);
13129 #define JIT_RUNTIME_WORKS
13130 #ifdef JIT_RUNTIME_WORKS
13131 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
13132 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
13135 mono_generic_sharing_init ();
13137 mono_thread_attach (domain);
13141 MonoJitStats mono_jit_stats = {0};
13144 print_jit_stats (void)
13146 if (mono_jit_stats.enabled) {
13147 g_print ("Mono Jit statistics\n");
13148 g_print ("Compiled methods: %ld\n", mono_jit_stats.methods_compiled);
13149 g_print ("Methods from AOT: %ld\n", mono_jit_stats.methods_aot);
13150 g_print ("Methods cache lookup: %ld\n", mono_jit_stats.methods_lookups);
13151 g_print ("Method trampolines: %ld\n", mono_jit_stats.method_trampolines);
13152 g_print ("Basic blocks: %ld\n", mono_jit_stats.basic_blocks);
13153 g_print ("Max basic blocks: %ld\n", mono_jit_stats.max_basic_blocks);
13154 g_print ("Allocated vars: %ld\n", mono_jit_stats.allocate_var);
13155 g_print ("Analyze stack repeat: %ld\n", mono_jit_stats.analyze_stack_repeat);
13156 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
13157 g_print ("Native code size: %ld\n", mono_jit_stats.native_code_size);
13158 g_print ("Max code size ratio: %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
13159 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
13160 g_print ("Biggest method: %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
13161 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
13162 g_print ("Code reallocs: %ld\n", mono_jit_stats.code_reallocs);
13163 g_print ("Allocated code size: %ld\n", mono_jit_stats.allocated_code_size);
13164 g_print ("Inlineable methods: %ld\n", mono_jit_stats.inlineable_methods);
13165 g_print ("Inlined methods: %ld\n", mono_jit_stats.inlined_methods);
13166 g_print ("Locals stack size: %ld\n", mono_jit_stats.locals_stack_size);
13168 g_print ("\nCreated object count: %ld\n", mono_stats.new_object_count);
13169 g_print ("Delegates created: %ld\n", mono_stats.delegate_creations);
13170 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
13171 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
13172 g_print ("Generic vtables: %ld\n", mono_stats.generic_vtable_count);
13173 g_print ("Methods: %ld\n", mono_stats.method_count);
13174 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
13175 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
13176 g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
13178 g_print ("\nGeneric instances: %ld\n", mono_stats.generic_instance_count);
13179 g_print ("Initialized classes: %ld\n", mono_stats.generic_class_count);
13180 g_print ("Inflated methods: %ld / %ld\n", mono_stats.inflated_method_count_2,
13181 mono_stats.inflated_method_count);
13182 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
13183 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
13184 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
13186 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
13187 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
13188 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
13190 g_print ("Dynamic code allocs: %ld\n", mono_stats.dynamic_code_alloc_count);
13191 g_print ("Dynamic code bytes: %ld\n", mono_stats.dynamic_code_bytes_count);
13192 g_print ("Dynamic code frees: %ld\n", mono_stats.dynamic_code_frees_count);
13194 g_print ("IMT tables size: %ld\n", mono_stats.imt_tables_size);
13195 g_print ("IMT number of tables: %ld\n", mono_stats.imt_number_of_tables);
13196 g_print ("IMT number of methods: %ld\n", mono_stats.imt_number_of_methods);
13197 g_print ("IMT used slots: %ld\n", mono_stats.imt_used_slots);
13198 g_print ("IMT colliding slots: %ld\n", mono_stats.imt_slots_with_collisions);
13199 g_print ("IMT max collisions: %ld\n", mono_stats.imt_max_collisions_in_slot);
13200 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
13201 g_print ("IMT thunks size: %ld\n", mono_stats.imt_thunks_size);
13203 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
13204 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
13205 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
13207 g_print ("Hazardous pointers: %ld\n", mono_stats.hazardous_pointer_count);
13208 #ifdef HAVE_SGEN_GC
13209 g_print ("Minor GC collections: %ld\n", mono_stats.minor_gc_count);
13210 g_print ("Major GC collections: %ld\n", mono_stats.major_gc_count);
13211 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
13212 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
13214 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
13215 g_print ("\nDecl security check : %ld\n", mono_jit_stats.cas_declsec_check);
13216 g_print ("LinkDemand (user) : %ld\n", mono_jit_stats.cas_linkdemand);
13217 g_print ("LinkDemand (icall) : %ld\n", mono_jit_stats.cas_linkdemand_icall);
13218 g_print ("LinkDemand (pinvoke) : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
13219 g_print ("LinkDemand (aptc) : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
13220 g_print ("Demand (code gen) : %ld\n", mono_jit_stats.cas_demand_generation);
13222 if (debug_options.collect_pagefault_stats) {
13223 g_print ("Metadata pagefaults : %d\n", mono_raw_buffer_get_n_pagefaults ());
13224 g_print ("AOT pagefaults : %d\n", mono_aot_get_n_pagefaults ());
13230 mini_cleanup (MonoDomain *domain)
13232 #ifdef HAVE_LINUX_RTC_H
13234 enable_rtc_timer (FALSE);
13238 * mono_runtime_cleanup() and mono_domain_finalize () need to
13239 * be called early since they need the execution engine still
13240 * fully working (mono_domain_finalize may invoke managed finalizers
13241 * and mono_runtime_cleanup will wait for other threads to finish).
13243 mono_domain_finalize (domain, 2000);
13245 /* This accesses metadata so needs to be called before runtime shutdown */
13246 print_jit_stats ();
13248 mono_runtime_cleanup (domain);
13250 mono_profiler_shutdown ();
13252 mono_icall_cleanup ();
13254 mono_runtime_cleanup_handlers ();
13256 mono_domain_free (domain, TRUE);
13258 mono_debugger_cleanup ();
13260 mono_code_manager_destroy (global_codeman);
13261 g_hash_table_destroy (jit_icall_name_hash);
13262 if (class_init_hash_addr)
13263 g_hash_table_destroy (class_init_hash_addr);
13264 if (delegate_trampoline_hash_addr)
13265 g_hash_table_destroy (delegate_trampoline_hash_addr);
13266 g_free (emul_opcode_map);
13268 mono_arch_cleanup ();
13272 mono_trace_cleanup ();
13274 mono_counters_dump (-1, stdout);
13276 if (mono_inject_async_exc_method)
13277 mono_method_desc_free (mono_inject_async_exc_method);
13279 TlsFree(mono_jit_tls_id);
13281 DeleteCriticalSection (&jit_mutex);
13283 DeleteCriticalSection (&mono_delegate_section);
13287 mono_set_defaults (int verbose_level, guint32 opts)
13289 mini_verbose = verbose_level;
13290 default_opt = opts;
13291 default_opt_set = TRUE;
13295 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
13297 GHashTable *assemblies = (GHashTable*)user_data;
13298 MonoImage *image = mono_assembly_get_image (ass);
13299 MonoMethod *method, *invoke;
13302 if (g_hash_table_lookup (assemblies, ass))
13305 g_hash_table_insert (assemblies, ass, ass);
13307 if (mini_verbose > 0)
13308 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
13310 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
13311 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
13312 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
13316 if (mini_verbose > 1) {
13317 char * desc = mono_method_full_name (method, TRUE);
13318 g_print ("Compiling %d %s\n", count, desc);
13321 mono_compile_method (method);
13322 if (strcmp (method->name, "Finalize") == 0) {
13323 invoke = mono_marshal_get_runtime_invoke (method);
13324 mono_compile_method (invoke);
13326 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
13327 invoke = mono_marshal_get_remoting_invoke_with_check (method);
13328 mono_compile_method (invoke);
13332 /* Load and precompile referenced assemblies as well */
13333 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
13334 mono_assembly_load_reference (image, i);
13335 if (image->references [i])
13336 mono_precompile_assembly (image->references [i], assemblies);
13340 void mono_precompile_assemblies ()
13342 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
13344 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
13346 g_hash_table_destroy (assemblies);