Replace SIZEOF_REGISTER with sizeof(mgreg_t) for consistency with sizeof(gpointer)
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * Copyright 2002-2003 Ximian, Inc.
9  * Coprygith 2003-2010 Novell, Inc.
10  */
11
12 #define MONO_LLVM_IN_MINI 1
13 #include <config.h>
14 #include <signal.h>
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #include <math.h>
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25
26 #include <mono/utils/memcheck.h>
27
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/loader.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/class.h>
32 #include <mono/metadata/object.h>
33 #include <mono/metadata/tokentype.h>
34 #include <mono/metadata/tabledefs.h>
35 #include <mono/metadata/threads.h>
36 #include <mono/metadata/appdomain.h>
37 #include <mono/metadata/debug-helpers.h>
38 #include <mono/io-layer/io-layer.h>
39 #include "mono/metadata/profiler.h"
40 #include <mono/metadata/profiler-private.h>
41 #include <mono/metadata/mono-config.h>
42 #include <mono/metadata/environment.h>
43 #include <mono/metadata/mono-debug.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/threads-types.h>
46 #include <mono/metadata/verify.h>
47 #include <mono/metadata/verify-internals.h>
48 #include <mono/metadata/mempool-internals.h>
49 #include <mono/metadata/attach.h>
50 #include <mono/metadata/runtime.h>
51 #include <mono/utils/mono-math.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-counters.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/dtrace.h>
57
58 #include "mini.h"
59 #include "mini-llvm.h"
60 #include "tasklets.h"
61 #include <string.h>
62 #include <ctype.h>
63 #include "trace.h"
64 #include "version.h"
65
66 #include "jit-icalls.h"
67
68 #include "debug-mini.h"
69 #include "mini-gc.h"
70 #include "debugger-agent.h"
71
72 #if defined(HAVE_KW_THREAD)
73 #define MINI_FAST_TLS_SET(x,y) x = y
74 #define MINI_FAST_TLS_GET(x) x
75 #define MINI_FAST_TLS_INIT(x)
76 #define MINI_FAST_TLS_DECLARE(x) static __thread gpointer x MONO_TLS_FAST;
77 #define MINI_HAVE_FAST_TLS
78 #define MINI_THREAD_VAR_OFFSET(x,y) MONO_THREAD_VAR_OFFSET(x,y)
79 #elif (defined(__APPLE__) && defined(__i386__))
80 #define MINI_FAST_TLS_SET(x,y) pthread_setspecific(x, y)
81 #define MINI_FAST_TLS_GET(x) pthread_getspecific(x)
82 #define MINI_FAST_TLS_INIT(x) pthread_key_create(&x, NULL)
83 #define MINI_FAST_TLS_DECLARE(x) static pthread_key_t x;
84 #define MINI_HAVE_FAST_TLS
85 #define MINI_THREAD_VAR_OFFSET(x,y) y = (gint32) x
86 #else
87 #define MINI_THREAD_VAR_OFFSET(x,y) MONO_THREAD_VAR_OFFSET(x,y)
88 #endif
89
90 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex);
91
92
93 static guint32 default_opt = 0;
94 static gboolean default_opt_set = FALSE;
95
96 guint32 mono_jit_tls_id = -1;
97
98 #ifdef MINI_HAVE_FAST_TLS
99 MINI_FAST_TLS_DECLARE(mono_jit_tls);
100 #endif
101
102 MonoTraceSpec *mono_jit_trace_calls = NULL;
103 gboolean mono_break_on_exc = FALSE;
104 gboolean mono_compile_aot = FALSE;
105 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
106 gboolean mono_aot_only = FALSE;
107 /* Whenever to use IMT */
108 #ifdef MONO_ARCH_HAVE_IMT
109 gboolean mono_use_imt = TRUE;
110 #else
111 gboolean mono_use_imt = FALSE;
112 #endif
113 MonoMethodDesc *mono_inject_async_exc_method = NULL;
114 int mono_inject_async_exc_pos;
115 MonoMethodDesc *mono_break_at_bb_method = NULL;
116 int mono_break_at_bb_bb_num;
117 gboolean mono_do_x86_stack_align = TRUE;
118 const char *mono_build_date;
119 gboolean mono_do_signal_chaining;
120 static gboolean mono_using_xdebug;
121 static int mini_verbose = 0;
122
123 /*
124  * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
125  * it can load AOT code compiled by LLVM.
126  */
127 gboolean mono_use_llvm = FALSE;
128
129 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
130 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
131 static CRITICAL_SECTION jit_mutex;
132
133 static MonoCodeManager *global_codeman = NULL;
134
135 static GHashTable *jit_icall_name_hash = NULL;
136
137 static MonoDebugOptions debug_options;
138
139 #ifdef VALGRIND_JIT_REGISTER_MAP
140 static int valgrind_register = 0;
141 #endif
142
143 /*
144  * Table written to by the debugger with a 1-based index into the
145  * mono_breakpoint_info table, which contains changes made to
146  * the JIT instructions by the debugger.
147  */
148 gssize
149 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
150
151 /* Whenever to check for pending exceptions in managed-to-native wrappers */
152 gboolean check_for_pending_exc = TRUE;
153
154 /* Whenever to disable passing/returning small valuetypes in registers for managed methods */
155 gboolean disable_vtypes_in_regs = FALSE;
156
157 gboolean mono_dont_free_global_codeman;
158
159 gpointer
160 mono_realloc_native_code (MonoCompile *cfg)
161 {
162 #if defined(__default_codegen__)
163         return g_realloc (cfg->native_code, cfg->code_size);
164 #elif defined(__native_client_codegen__)
165         guint old_padding;
166         gpointer native_code;
167         guint alignment_check;
168
169         /* Save the old alignment offset so we can re-align after the realloc. */
170         old_padding = (guint)(cfg->native_code - cfg->native_code_alloc);
171
172         cfg->native_code_alloc = g_realloc ( cfg->native_code_alloc,
173                                                                                  cfg->code_size + kNaClAlignment );
174
175         /* Align native_code to next nearest kNaClAlignment byte. */
176         native_code = (guint)cfg->native_code_alloc + kNaClAlignment;
177         native_code = (guint)native_code & ~kNaClAlignmentMask;
178
179         /* Shift the data to be 32-byte aligned again. */
180         memmove (native_code, cfg->native_code_alloc + old_padding, cfg->code_size);
181
182         alignment_check = (guint)native_code & kNaClAlignmentMask;
183         g_assert (alignment_check == 0);
184         return native_code;
185 #else
186         g_assert_not_reached ();
187         return cfg->native_code;
188 #endif
189 }
190
191 #ifdef __native_client_codegen__
192
193 /* Prevent instructions from straddling a 32-byte alignment boundary.   */
194 /* Instructions longer than 32 bytes must be aligned internally.        */
195 /* IN: pcode, instlen                                                   */
196 /* OUT: pcode                                                           */
197 void mono_nacl_align_inst(guint8 **pcode, int instlen) {
198   int space_in_block;
199
200   space_in_block = kNaClAlignment - ((uintptr_t)(*pcode) & kNaClAlignmentMask);
201
202   if (G_UNLIKELY (instlen >= kNaClAlignment)) {
203     g_assert_not_reached();
204   } else if (instlen > space_in_block) {
205     *pcode = mono_arch_nacl_pad(*pcode, space_in_block);
206   }
207 }
208
209 /* Move emitted call sequence to the end of a kNaClAlignment-byte block.  */
210 /* IN: start    pointer to start of call sequence                         */
211 /* IN: pcode    pointer to end of call sequence (current "IP")            */
212 /* OUT: start   pointer to the start of the call sequence after padding   */
213 /* OUT: pcode   pointer to the end of the call sequence after padding     */
214 void mono_nacl_align_call(guint8 **start, guint8 **pcode) {
215   const size_t MAX_NACL_CALL_LENGTH = kNaClAlignment;
216   guint8 copy_of_call[MAX_NACL_CALL_LENGTH];
217   guint8 *temp;
218
219   const size_t length = (size_t)((*pcode)-(*start));
220   g_assert(length < MAX_NACL_CALL_LENGTH);
221
222   memcpy(copy_of_call, *start, length);
223   temp = mono_nacl_pad_call(*start, (guint8)length);
224   memcpy(temp, copy_of_call, length);
225   (*start) = temp;
226   (*pcode) = temp + length;
227 }
228
229 /* mono_nacl_pad_call(): Insert padding for Native Client call instructions */
230 /*    code     pointer to buffer for emitting code                          */
231 /*    ilength  length of call instruction                                   */
232 guint8 *mono_nacl_pad_call(guint8 *code, guint8 ilength) {
233   int freeSpaceInBlock = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
234   int padding = freeSpaceInBlock - ilength;
235
236   if (padding < 0) {
237     /* There isn't enough space in this block for the instruction. */
238     /* Fill this block and start a new one.                        */
239     code = mono_arch_nacl_pad(code, freeSpaceInBlock);
240     freeSpaceInBlock = kNaClAlignment;
241     padding = freeSpaceInBlock - ilength;
242   }
243   g_assert(ilength > 0);
244   g_assert(padding >= 0);
245   g_assert(padding < kNaClAlignment);
246   if (0 == padding) return code;
247   return mono_arch_nacl_pad(code, padding);
248 }
249
250 guint8 *mono_nacl_align(guint8 *code) {
251   int padding = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
252   if (padding != kNaClAlignment) code = mono_arch_nacl_pad(code, padding);
253   return code;
254 }
255
256 void mono_nacl_fix_patches(const guint8 *code, MonoJumpInfo *ji)
257 {
258   MonoJumpInfo *patch_info;
259   for (patch_info = ji; patch_info; patch_info = patch_info->next) {
260     unsigned char *ip = patch_info->ip.i + code;
261     ip = mono_arch_nacl_skip_nops(ip);
262     patch_info->ip.i = ip - code;
263   }
264 }
265 #endif  /* __native_client_codegen__ */
266
267 gboolean
268 mono_running_on_valgrind (void)
269 {
270         if (RUNNING_ON_VALGRIND){
271 #ifdef VALGRIND_JIT_REGISTER_MAP
272                 valgrind_register = TRUE;
273 #endif
274                 return TRUE;
275         } else
276                 return FALSE;
277 }
278
279 typedef struct {
280         MonoExceptionClause *clause;
281         MonoBasicBlock *basic_block;
282         int start_offset;
283 } TryBlockHole;
284
285 typedef struct {
286         void *ip;
287         MonoMethod *method;
288 } FindTrampUserData;
289
290 static void
291 find_tramp (gpointer key, gpointer value, gpointer user_data)
292 {
293         FindTrampUserData *ud = (FindTrampUserData*)user_data;
294
295         if (value == ud->ip)
296                 ud->method = (MonoMethod*)key;
297 }
298
299 /* debug function */
300 G_GNUC_UNUSED static char*
301 get_method_from_ip (void *ip)
302 {
303         MonoJitInfo *ji;
304         char *method;
305         char *res;
306         MonoDomain *domain = mono_domain_get ();
307         MonoDebugSourceLocation *location;
308         FindTrampUserData user_data;
309         
310         ji = mono_jit_info_table_find (domain, ip);
311         if (!ji) {
312                 user_data.ip = ip;
313                 user_data.method = NULL;
314                 mono_domain_lock (domain);
315                 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
316                 mono_domain_unlock (domain);
317                 if (user_data.method) {
318                         char *mname = mono_method_full_name (user_data.method, TRUE);
319                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
320                         g_free (mname);
321                         return res;
322                 }
323                 else
324                         return NULL;
325         }
326         method = mono_method_full_name (ji->method, TRUE);
327         /* FIXME: unused ? */
328         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
329
330         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);
331
332         mono_debug_free_source_location (location);
333         g_free (method);
334
335         return res;
336 }
337
338 /** 
339  * mono_pmip:
340  * @ip: an instruction pointer address
341  *
342  * This method is used from a debugger to get the name of the
343  * method at address @ip.   This routine is typically invoked from
344  * a debugger like this:
345  *
346  * (gdb) print mono_pmip ($pc)
347  *
348  * Returns: the name of the method at address @ip.
349  */
350 G_GNUC_UNUSED char *
351 mono_pmip (void *ip)
352 {
353         return get_method_from_ip (ip);
354 }
355
356 /** 
357  * mono_print_method_from_ip
358  * @ip: an instruction pointer address
359  *
360  * This method is used from a debugger to get the name of the
361  * method at address @ip.
362  *
363  * This prints the name of the method at address @ip in the standard
364  * output.  Unlike mono_pmip which returns a string, this routine
365  * prints the value on the standard output. 
366  */
367 void
368 mono_print_method_from_ip (void *ip)
369 {
370         MonoJitInfo *ji;
371         char *method;
372         MonoDebugSourceLocation *source;
373         MonoDomain *domain = mono_domain_get ();
374         MonoDomain *target_domain = mono_domain_get ();
375         FindTrampUserData user_data;
376         
377         ji = mini_jit_info_table_find (domain, ip, &target_domain);
378         if (!ji) {
379                 user_data.ip = ip;
380                 user_data.method = NULL;
381                 mono_domain_lock (domain);
382                 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
383                 mono_domain_unlock (domain);
384                 if (user_data.method) {
385                         char *mname = mono_method_full_name (user_data.method, TRUE);
386                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
387                         g_free (mname);
388                 }
389                 else
390                         g_print ("No method at %p\n", ip);
391                 return;
392         }
393         method = mono_method_full_name (ji->method, TRUE);
394         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
395
396         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, target_domain, target_domain->friendly_name);
397
398         if (source)
399                 g_print ("%s:%d\n", source->source_file, source->row);
400
401         mono_debug_free_source_location (source);
402         g_free (method);
403 }
404         
405 /* 
406  * mono_method_same_domain:
407  *
408  * Determine whenever two compiled methods are in the same domain, thus
409  * the address of the callee can be embedded in the caller.
410  */
411 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
412 {
413         if (!caller || !callee)
414                 return FALSE;
415
416         /*
417          * If the call was made from domain-neutral to domain-specific 
418          * code, we can't patch the call site.
419          */
420         if (caller->domain_neutral && !callee->domain_neutral)
421                 return FALSE;
422
423         if ((caller->method->klass == mono_defaults.appdomain_class) &&
424                 (strstr (caller->method->name, "InvokeInDomain"))) {
425                  /* The InvokeInDomain methods change the current appdomain */
426                 return FALSE;
427         }
428
429         return TRUE;
430 }
431
432 /*
433  * mono_global_codeman_reserve:
434  *
435  *  Allocate code memory from the global code manager.
436  */
437 void *mono_global_codeman_reserve (int size)
438 {
439         void *ptr;
440
441         if (mono_aot_only)
442                 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
443
444         if (!global_codeman) {
445                 /* This can happen during startup */
446                 global_codeman = mono_code_manager_new ();
447                 return mono_code_manager_reserve (global_codeman, size);
448         }
449         else {
450                 mono_jit_lock ();
451                 ptr = mono_code_manager_reserve (global_codeman, size);
452                 mono_jit_unlock ();
453                 return ptr;
454         }
455 }
456
457 #if defined(__native_client_codegen__) && defined(__native_client__)
458 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
459  * which we are generating code, return a pointer to the destination in the
460  * dynamic code segment into which the code will be copied when
461  * mono_global_codeman_commit is called.
462  * LOCKING: Acquires the jit lock.
463  */
464 void*
465 nacl_global_codeman_get_dest (void *data)
466 {
467         void *dest;
468         mono_jit_lock ();
469         dest = nacl_code_manager_get_code_dest (global_codeman, data);
470         mono_jit_unlock ();
471         return dest;
472 }
473
474 void
475 mono_global_codeman_commit (void *data, int size, int newsize)
476 {
477         mono_jit_lock ();
478         mono_code_manager_commit (global_codeman, data, size, newsize);
479         mono_jit_unlock ();
480 }
481
482 /* 
483  * Convenience function which calls mono_global_codeman_commit to validate and
484  * copy the code. The caller sets *buf_base and *buf_size to the start and size
485  * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
486  * the byte after the last instruction byte. On return, *buf_base will point to
487  * the start of the copied in the code segment, and *code_end will point after
488  * the end of the copied code.
489  */
490 void
491 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
492 {
493         guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
494         mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
495         *code_end = tmp + (*code_end - *buf_base);
496         *buf_base = tmp;
497 }
498 #else
499 /* no-op versions of Native Client functions */
500 void*
501 nacl_global_codeman_get_dest (void *data)
502 {
503         return data;
504 }
505
506 void
507 mono_global_codeman_commit (void *data, int size, int newsize)
508 {
509 }
510
511 void
512 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
513 {
514 }
515
516 #endif /* __native_client__ */
517
518 /**
519  * mono_create_unwind_op:
520  *
521  *   Create an unwind op with the given parameters.
522  */
523 MonoUnwindOp*
524 mono_create_unwind_op (int when, int tag, int reg, int val)
525 {
526         MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
527
528         op->op = tag;
529         op->reg = reg;
530         op->val = val;
531         op->when = when;
532
533         return op;
534 }
535
536 /**
537  * mono_emit_unwind_op:
538  *
539  *   Add an unwind op with the given parameters for the list of unwind ops stored in
540  * cfg->unwind_ops.
541  */
542 void
543 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
544 {
545         MonoUnwindOp *op = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
546
547         op->op = tag;
548         op->reg = reg;
549         op->val = val;
550         op->when = when;
551         
552         cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
553 }
554
555 MonoJumpInfoToken *
556 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
557 {
558         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
559         res->image = image;
560         res->token = token;
561         res->has_context = context != NULL;
562         if (context)
563                 memcpy (&res->context, context, sizeof (MonoGenericContext));
564
565         return res;
566 }
567
568 MonoJumpInfoToken *
569 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
570 {
571         return mono_jump_info_token_new2 (mp, image, token, NULL);
572 }
573  
574 /*
575  * mono_tramp_info_create:
576  *
577  *   Create a MonoTrampInfo structure from the arguments. This function assumes ownership
578  * of NAME, JI, and UNWIND_OPS.
579  */
580 MonoTrampInfo*
581 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
582 {
583         MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
584
585         info->name = (char*)name;
586         info->code = code;
587         info->code_size = code_size;
588         info->ji = ji;
589         info->unwind_ops = unwind_ops;
590
591         return info;
592 }
593
594 void
595 mono_tramp_info_free (MonoTrampInfo *info)
596 {
597         GSList *l;
598
599         g_free (info->name);
600
601         // FIXME: ji
602         for (l = info->unwind_ops; l; l = l->next)
603                 g_free (l->data);
604         g_slist_free (info->unwind_ops);
605         g_free (info);
606 }
607
608 #define MONO_INIT_VARINFO(vi,id) do { \
609         (vi)->range.first_use.pos.bid = 0xffff; \
610         (vi)->reg = -1; \
611         (vi)->idx = (id); \
612 } while (0)
613
614 /**
615  * mono_unlink_bblock:
616  *
617  *   Unlink two basic blocks.
618  */
619 void
620 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
621 {
622         int i, pos;
623         gboolean found;
624
625         found = FALSE;
626         for (i = 0; i < from->out_count; ++i) {
627                 if (to == from->out_bb [i]) {
628                         found = TRUE;
629                         break;
630                 }
631         }
632         if (found) {
633                 pos = 0;
634                 for (i = 0; i < from->out_count; ++i) {
635                         if (from->out_bb [i] != to)
636                                 from->out_bb [pos ++] = from->out_bb [i];
637                 }
638                 g_assert (pos == from->out_count - 1);
639                 from->out_count--;
640         }
641
642         found = FALSE;
643         for (i = 0; i < to->in_count; ++i) {
644                 if (from == to->in_bb [i]) {
645                         found = TRUE;
646                         break;
647                 }
648         }
649         if (found) {
650                 pos = 0;
651                 for (i = 0; i < to->in_count; ++i) {
652                         if (to->in_bb [i] != from)
653                                 to->in_bb [pos ++] = to->in_bb [i];
654                 }
655                 g_assert (pos == to->in_count - 1);
656                 to->in_count--;
657         }
658 }
659
660 /*
661  * mono_bblocks_linked:
662  *
663  *   Return whenever BB1 and BB2 are linked in the CFG.
664  */
665 gboolean
666 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
667 {
668         int i;
669
670         for (i = 0; i < bb1->out_count; ++i) {
671                 if (bb1->out_bb [i] == bb2)
672                         return TRUE;
673         }
674
675         return FALSE;
676 }
677
678 static int
679 mono_find_block_region_notry (MonoCompile *cfg, int offset)
680 {
681         MonoMethodHeader *header = cfg->header;
682         MonoExceptionClause *clause;
683         int i;
684
685         for (i = 0; i < header->num_clauses; ++i) {
686                 clause = &header->clauses [i];
687                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
688                     (offset < (clause->handler_offset)))
689                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
690                            
691                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
692                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
693                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
694                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
695                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
696                         else
697                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
698                 }
699         }
700
701         return -1;
702 }
703
704 /*
705  * mono_get_block_region_notry:
706  *
707  *   Return the region corresponding to REGION, ignoring try clauses nested inside
708  * finally clauses.
709  */
710 int
711 mono_get_block_region_notry (MonoCompile *cfg, int region)
712 {
713         if ((region & (0xf << 4)) == MONO_REGION_TRY) {
714                 MonoMethodHeader *header = cfg->header;
715                 
716                 /*
717                  * This can happen if a try clause is nested inside a finally clause.
718                  */
719                 int clause_index = (region >> 8) - 1;
720                 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
721                 
722                 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
723         }
724
725         return region;
726 }
727
728 MonoInst *
729 mono_find_spvar_for_region (MonoCompile *cfg, int region)
730 {
731         region = mono_get_block_region_notry (cfg, region);
732
733         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
734 }
735
736 static void
737 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
738 {
739         int i;
740
741         array [*dfn] = start;
742         /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
743         for (i = 0; i < start->out_count; ++i) {
744                 if (start->out_bb [i]->dfn)
745                         continue;
746                 (*dfn)++;
747                 start->out_bb [i]->dfn = *dfn;
748                 start->out_bb [i]->df_parent = start;
749                 array [*dfn] = start->out_bb [i];
750                 df_visit (start->out_bb [i], dfn, array);
751         }
752 }
753
754 guint32
755 mono_reverse_branch_op (guint32 opcode)
756 {
757         static const int reverse_map [] = {
758                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
759                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
760         };
761         static const int reverse_fmap [] = {
762                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
763                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
764         };
765         static const int reverse_lmap [] = {
766                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
767                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
768         };
769         static const int reverse_imap [] = {
770                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
771                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
772         };
773                                 
774         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
775                 opcode = reverse_map [opcode - CEE_BEQ];
776         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
777                 opcode = reverse_fmap [opcode - OP_FBEQ];
778         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
779                 opcode = reverse_lmap [opcode - OP_LBEQ];
780         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
781                 opcode = reverse_imap [opcode - OP_IBEQ];
782         } else
783                 g_assert_not_reached ();
784
785         return opcode;
786 }
787
788 guint
789 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
790 {
791         if (type->byref)
792                 return OP_STORE_MEMBASE_REG;
793
794 handle_enum:
795         switch (type->type) {
796         case MONO_TYPE_I1:
797         case MONO_TYPE_U1:
798         case MONO_TYPE_BOOLEAN:
799                 return OP_STOREI1_MEMBASE_REG;
800         case MONO_TYPE_I2:
801         case MONO_TYPE_U2:
802         case MONO_TYPE_CHAR:
803                 return OP_STOREI2_MEMBASE_REG;
804         case MONO_TYPE_I4:
805         case MONO_TYPE_U4:
806                 return OP_STOREI4_MEMBASE_REG;
807         case MONO_TYPE_I:
808         case MONO_TYPE_U:
809         case MONO_TYPE_PTR:
810         case MONO_TYPE_FNPTR:
811                 return OP_STORE_MEMBASE_REG;
812         case MONO_TYPE_CLASS:
813         case MONO_TYPE_STRING:
814         case MONO_TYPE_OBJECT:
815         case MONO_TYPE_SZARRAY:
816         case MONO_TYPE_ARRAY:    
817                 return OP_STORE_MEMBASE_REG;
818         case MONO_TYPE_I8:
819         case MONO_TYPE_U8:
820                 return OP_STOREI8_MEMBASE_REG;
821         case MONO_TYPE_R4:
822                 return OP_STORER4_MEMBASE_REG;
823         case MONO_TYPE_R8:
824                 return OP_STORER8_MEMBASE_REG;
825         case MONO_TYPE_VALUETYPE:
826                 if (type->data.klass->enumtype) {
827                         type = mono_class_enum_basetype (type->data.klass);
828                         goto handle_enum;
829                 }
830                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
831                         return OP_STOREX_MEMBASE;
832                 return OP_STOREV_MEMBASE;
833         case MONO_TYPE_TYPEDBYREF:
834                 return OP_STOREV_MEMBASE;
835         case MONO_TYPE_GENERICINST:
836                 type = &type->data.generic_class->container_class->byval_arg;
837                 goto handle_enum;
838         case MONO_TYPE_VAR:
839         case MONO_TYPE_MVAR:
840                 /* FIXME: all the arguments must be references for now,
841                  * later look inside cfg and see if the arg num is
842                  * really a reference
843                  */
844                 g_assert (cfg->generic_sharing_context);
845                 return OP_STORE_MEMBASE_REG;
846         default:
847                 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
848         }
849         return -1;
850 }
851
852 guint
853 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
854 {
855         if (type->byref)
856                 return OP_LOAD_MEMBASE;
857
858         type = mono_type_get_underlying_type (type);
859
860         switch (type->type) {
861         case MONO_TYPE_I1:
862                 return OP_LOADI1_MEMBASE;
863         case MONO_TYPE_U1:
864         case MONO_TYPE_BOOLEAN:
865                 return OP_LOADU1_MEMBASE;
866         case MONO_TYPE_I2:
867                 return OP_LOADI2_MEMBASE;
868         case MONO_TYPE_U2:
869         case MONO_TYPE_CHAR:
870                 return OP_LOADU2_MEMBASE;
871         case MONO_TYPE_I4:
872                 return OP_LOADI4_MEMBASE;
873         case MONO_TYPE_U4:
874                 return OP_LOADU4_MEMBASE;
875         case MONO_TYPE_I:
876         case MONO_TYPE_U:
877         case MONO_TYPE_PTR:
878         case MONO_TYPE_FNPTR:
879                 return OP_LOAD_MEMBASE;
880         case MONO_TYPE_CLASS:
881         case MONO_TYPE_STRING:
882         case MONO_TYPE_OBJECT:
883         case MONO_TYPE_SZARRAY:
884         case MONO_TYPE_ARRAY:    
885                 return OP_LOAD_MEMBASE;
886         case MONO_TYPE_I8:
887         case MONO_TYPE_U8:
888                 return OP_LOADI8_MEMBASE;
889         case MONO_TYPE_R4:
890                 return OP_LOADR4_MEMBASE;
891         case MONO_TYPE_R8:
892                 return OP_LOADR8_MEMBASE;
893         case MONO_TYPE_VALUETYPE:
894                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
895                         return OP_LOADX_MEMBASE;
896         case MONO_TYPE_TYPEDBYREF:
897                 return OP_LOADV_MEMBASE;
898         case MONO_TYPE_GENERICINST:
899                 if (mono_type_generic_inst_is_valuetype (type))
900                         return OP_LOADV_MEMBASE;
901                 else
902                         return OP_LOAD_MEMBASE;
903                 break;
904         case MONO_TYPE_VAR:
905         case MONO_TYPE_MVAR:
906                 /* FIXME: all the arguments must be references for now,
907                  * later look inside cfg and see if the arg num is
908                  * really a reference
909                  */
910                 g_assert (cfg->generic_sharing_context);
911                 return OP_LOAD_MEMBASE;
912         default:
913                 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
914         }
915         return -1;
916 }
917
918 static guint
919 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
920 {
921         if (cfg->generic_sharing_context && !type->byref) {
922                 /* FIXME: all the arguments must be references for now,
923                  * later look inside cfg and see if the arg num is
924                  * really a reference
925                  */
926                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
927                         return CEE_LDIND_REF;
928         }
929         return mono_type_to_ldind (type);
930 }
931
932 guint
933 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
934 {
935         if (cfg->generic_sharing_context && !type->byref) {
936                 /* FIXME: all the arguments must be references for now,
937                  * later look inside cfg and see if the arg num is
938                  * really a reference
939                  */
940                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
941                         return CEE_STIND_REF;
942         }
943         return mono_type_to_stind (type);
944 }
945
946 int
947 mono_op_imm_to_op (int opcode)
948 {
949         switch (opcode) {
950         case OP_ADD_IMM:
951 #if SIZEOF_REGISTER == 4
952                 return OP_IADD;
953 #else
954                 return OP_LADD;
955 #endif
956         case OP_IADD_IMM:
957                 return OP_IADD;
958         case OP_LADD_IMM:
959                 return OP_LADD;
960         case OP_ISUB_IMM:
961                 return OP_ISUB;
962         case OP_LSUB_IMM:
963                 return OP_LSUB;
964         case OP_IMUL_IMM:
965                 return OP_IMUL;
966         case OP_AND_IMM:
967 #if SIZEOF_REGISTER == 4
968                 return OP_IAND;
969 #else
970                 return OP_LAND;
971 #endif
972         case OP_OR_IMM:
973 #if SIZEOF_REGISTER == 4
974                 return OP_IOR;
975 #else
976                 return OP_LOR;
977 #endif
978         case OP_XOR_IMM:
979 #if SIZEOF_REGISTER == 4
980                 return OP_IXOR;
981 #else
982                 return OP_LXOR;
983 #endif
984         case OP_IAND_IMM:
985                 return OP_IAND;
986         case OP_LAND_IMM:
987                 return OP_LAND;
988         case OP_IOR_IMM:
989                 return OP_IOR;
990         case OP_LOR_IMM:
991                 return OP_LOR;
992         case OP_IXOR_IMM:
993                 return OP_IXOR;
994         case OP_LXOR_IMM:
995                 return OP_LXOR;
996         case OP_ISHL_IMM:
997                 return OP_ISHL;
998         case OP_LSHL_IMM:
999                 return OP_LSHL;
1000         case OP_ISHR_IMM:
1001                 return OP_ISHR;
1002         case OP_LSHR_IMM:
1003                 return OP_LSHR;
1004         case OP_ISHR_UN_IMM:
1005                 return OP_ISHR_UN;
1006         case OP_LSHR_UN_IMM:
1007                 return OP_LSHR_UN;
1008         case OP_IDIV_IMM:
1009                 return OP_IDIV;
1010         case OP_IDIV_UN_IMM:
1011                 return OP_IDIV_UN;
1012         case OP_IREM_UN_IMM:
1013                 return OP_IREM_UN;
1014         case OP_IREM_IMM:
1015                 return OP_IREM;
1016         case OP_DIV_IMM:
1017 #if SIZEOF_REGISTER == 4
1018                 return OP_IDIV;
1019 #else
1020                 return OP_LDIV;
1021 #endif
1022         case OP_REM_IMM:
1023 #if SIZEOF_REGISTER == 4
1024                 return OP_IREM;
1025 #else
1026                 return OP_LREM;
1027 #endif
1028         case OP_ADDCC_IMM:
1029                 return OP_ADDCC;
1030         case OP_ADC_IMM:
1031                 return OP_ADC;
1032         case OP_SUBCC_IMM:
1033                 return OP_SUBCC;
1034         case OP_SBB_IMM:
1035                 return OP_SBB;
1036         case OP_IADC_IMM:
1037                 return OP_IADC;
1038         case OP_ISBB_IMM:
1039                 return OP_ISBB;
1040         case OP_COMPARE_IMM:
1041                 return OP_COMPARE;
1042         case OP_ICOMPARE_IMM:
1043                 return OP_ICOMPARE;
1044         case OP_LOCALLOC_IMM:
1045                 return OP_LOCALLOC;
1046         default:
1047                 printf ("%s\n", mono_inst_name (opcode));
1048                 g_assert_not_reached ();
1049                 return -1;
1050         }
1051 }
1052
1053 /*
1054  * mono_decompose_op_imm:
1055  *
1056  *   Replace the OP_.._IMM INS with its non IMM variant.
1057  */
1058 void
1059 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
1060 {
1061         MonoInst *temp;
1062
1063         MONO_INST_NEW (cfg, temp, OP_ICONST);
1064         temp->inst_c0 = ins->inst_imm;
1065         temp->dreg = mono_alloc_ireg (cfg);
1066         mono_bblock_insert_before_ins (bb, ins, temp);
1067         ins->opcode = mono_op_imm_to_op (ins->opcode);
1068         if (ins->opcode == OP_LOCALLOC)
1069                 ins->sreg1 = temp->dreg;
1070         else
1071                 ins->sreg2 = temp->dreg;
1072
1073         bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
1074 }
1075
1076 static void
1077 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
1078 {
1079         if (vreg >= cfg->vreg_to_inst_len) {
1080                 MonoInst **tmp = cfg->vreg_to_inst;
1081                 int size = cfg->vreg_to_inst_len;
1082
1083                 while (vreg >= cfg->vreg_to_inst_len)
1084                         cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
1085                 cfg->vreg_to_inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
1086                 if (size)
1087                         memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
1088         }
1089         cfg->vreg_to_inst [vreg] = inst;
1090 }
1091
1092 #define mono_type_is_long(type) (!(type)->byref && ((mono_type_get_underlying_type (type)->type == MONO_TYPE_I8) || (mono_type_get_underlying_type (type)->type == MONO_TYPE_U8)))
1093 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
1094
1095 #ifdef DISABLE_JIT
1096
1097 MonoInst*
1098 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1099 {
1100         return NULL;
1101 }
1102
1103 #else
1104
1105 MonoInst*
1106 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
1107 {
1108         MonoInst *inst;
1109         int num = cfg->num_varinfo;
1110         gboolean regpair;
1111
1112         if ((num + 1) >= cfg->varinfo_count) {
1113                 int orig_count = cfg->varinfo_count;
1114                 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 64;
1115                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1116                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1117                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1118         }
1119
1120         mono_jit_stats.allocate_var++;
1121
1122         MONO_INST_NEW (cfg, inst, opcode);
1123         inst->inst_c0 = num;
1124         inst->inst_vtype = type;
1125         inst->klass = mono_class_from_mono_type (type);
1126         type_to_eval_stack_type (cfg, type, inst);
1127         /* if set to 1 the variable is native */
1128         inst->backend.is_pinvoke = 0;
1129         inst->dreg = vreg;
1130
1131         cfg->varinfo [num] = inst;
1132
1133         MONO_INIT_VARINFO (&cfg->vars [num], num);
1134         MONO_VARINFO (cfg, num)->vreg = vreg;
1135
1136         if (vreg != -1)
1137                 set_vreg_to_inst (cfg, vreg, inst);
1138
1139 #if SIZEOF_REGISTER == 4
1140 #ifdef MONO_ARCH_SOFT_FLOAT
1141         regpair = mono_type_is_long (type) || mono_type_is_float (type);
1142 #else
1143         regpair = mono_type_is_long (type);
1144 #endif
1145 #else
1146         regpair = FALSE;
1147 #endif
1148
1149         if (regpair) {
1150                 MonoInst *tree;
1151
1152                 /* 
1153                  * These two cannot be allocated using create_var_for_vreg since that would
1154                  * put it into the cfg->varinfo array, confusing many parts of the JIT.
1155                  */
1156
1157                 /* 
1158                  * Set flags to VOLATILE so SSA skips it.
1159                  */
1160
1161                 if (cfg->verbose_level >= 4) {
1162                         printf ("  Create LVAR R%d (R%d, R%d)\n", inst->dreg, inst->dreg + 1, inst->dreg + 2);
1163                 }
1164
1165 #ifdef MONO_ARCH_SOFT_FLOAT
1166                 if (cfg->opt & MONO_OPT_SSA) {
1167                         if (mono_type_is_float (type))
1168                                 inst->flags = MONO_INST_VOLATILE;
1169                 }
1170 #endif
1171
1172                 /* Allocate a dummy MonoInst for the first vreg */
1173                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
1174                 tree->dreg = inst->dreg + 1;
1175                 if (cfg->opt & MONO_OPT_SSA)
1176                         tree->flags = MONO_INST_VOLATILE;
1177                 tree->inst_c0 = num;
1178                 tree->type = STACK_I4;
1179                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
1180                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
1181
1182                 set_vreg_to_inst (cfg, inst->dreg + 1, tree);
1183
1184                 /* Allocate a dummy MonoInst for the second vreg */
1185                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
1186                 tree->dreg = inst->dreg + 2;
1187                 if (cfg->opt & MONO_OPT_SSA)
1188                         tree->flags = MONO_INST_VOLATILE;
1189                 tree->inst_c0 = num;
1190                 tree->type = STACK_I4;
1191                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
1192                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
1193
1194                 set_vreg_to_inst (cfg, inst->dreg + 2, tree);
1195         }
1196
1197         cfg->num_varinfo++;
1198         if (cfg->verbose_level > 2)
1199                 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
1200         return inst;
1201 }
1202
1203 MonoInst*
1204 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1205 {
1206         int dreg;
1207
1208         if (mono_type_is_long (type))
1209                 dreg = mono_alloc_dreg (cfg, STACK_I8);
1210 #ifdef MONO_ARCH_SOFT_FLOAT
1211         else if (mono_type_is_float (type))
1212                 dreg = mono_alloc_dreg (cfg, STACK_R8);
1213 #endif
1214         else
1215                 /* All the others are unified */
1216                 dreg = mono_alloc_preg (cfg);
1217
1218         return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
1219 }
1220
1221 /*
1222  * Transform a MonoInst into a load from the variable of index var_index.
1223  */
1224 void
1225 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1226         memset (dest, 0, sizeof (MonoInst));
1227         dest->inst_i0 = cfg->varinfo [var_index];
1228         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1229         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1230         dest->klass = dest->inst_i0->klass;
1231 }
1232
1233 #endif
1234
1235 static MonoType*
1236 type_from_stack_type (MonoInst *ins) {
1237         switch (ins->type) {
1238         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1239         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1240         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1241         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1242         case STACK_MP:
1243                 /* 
1244                  * this if used to be commented without any specific reason, but
1245                  * it breaks #80235 when commented
1246                  */
1247                 if (ins->klass)
1248                         return &ins->klass->this_arg;
1249                 else
1250                         return &mono_defaults.object_class->this_arg;
1251         case STACK_OBJ:
1252                 /* ins->klass may not be set for ldnull.
1253                  * Also, if we have a boxed valuetype, we want an object lass,
1254                  * not the valuetype class
1255                  */
1256                 if (ins->klass && !ins->klass->valuetype)
1257                         return &ins->klass->byval_arg;
1258                 return &mono_defaults.object_class->byval_arg;
1259         case STACK_VTYPE: return &ins->klass->byval_arg;
1260         default:
1261                 g_error ("stack type %d to montype not handled\n", ins->type);
1262         }
1263         return NULL;
1264 }
1265
1266 MonoType*
1267 mono_type_from_stack_type (MonoInst *ins) {
1268         return type_from_stack_type (ins);
1269 }
1270
1271 /*
1272  * mono_add_ins_to_end:
1273  *
1274  *   Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
1275  */
1276 void
1277 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1278 {
1279         int opcode;
1280
1281         if (!bb->code) {
1282                 MONO_ADD_INS (bb, inst);
1283                 return;
1284         }
1285
1286         switch (bb->last_ins->opcode) {
1287         case OP_BR:
1288         case OP_BR_REG:
1289         case CEE_BEQ:
1290         case CEE_BGE:
1291         case CEE_BGT:
1292         case CEE_BLE:
1293         case CEE_BLT:
1294         case CEE_BNE_UN:
1295         case CEE_BGE_UN:
1296         case CEE_BGT_UN:
1297         case CEE_BLE_UN:
1298         case CEE_BLT_UN:
1299         case OP_SWITCH:
1300                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1301                 break;
1302         default:
1303                 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
1304                         /* Need to insert the ins before the compare */
1305                         if (bb->code == bb->last_ins) {
1306                                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1307                                 return;
1308                         }
1309
1310                         if (bb->code->next == bb->last_ins) {
1311                                 /* Only two instructions */
1312                                 opcode = bb->code->opcode;
1313
1314                                 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM)) {
1315                                         /* NEW IR */
1316                                         mono_bblock_insert_before_ins (bb, bb->code, inst);
1317                                 } else {
1318                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1319                                 }
1320                         } else {
1321                                 opcode = bb->last_ins->prev->opcode;
1322
1323                                 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM)) {
1324                                         /* NEW IR */
1325                                         mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
1326                                 } else {
1327                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1328                                 }                                       
1329                         }
1330                 }
1331                 else
1332                         MONO_ADD_INS (bb, inst);
1333                 break;
1334         }
1335 }
1336
1337 void
1338 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1339 {
1340         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1341         MonoJumpInfoBBTable *table;
1342
1343         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
1344         table->table = bbs;
1345         table->table_size = num_blocks;
1346         
1347         ji->ip.label = label;
1348         ji->type = MONO_PATCH_INFO_SWITCH;
1349         ji->data.table = table;
1350         ji->next = cfg->patch_info;
1351         cfg->patch_info = ji;
1352 }
1353
1354 static MonoMethodSignature *
1355 mono_get_array_new_va_signature (int arity)
1356 {
1357         static GHashTable *sighash = NULL;
1358         MonoMethodSignature *res;
1359         int i;
1360
1361         mono_jit_lock ();
1362         if (!sighash) {
1363                 sighash = g_hash_table_new (NULL, NULL);
1364         }
1365         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
1366                 mono_jit_unlock ();
1367                 return res;
1368         }
1369
1370         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1371
1372         res->pinvoke = 1;
1373 #ifdef MONO_ARCH_VARARG_ICALLS
1374         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
1375         res->call_convention = MONO_CALL_VARARG;
1376 #endif
1377
1378 #ifdef TARGET_WIN32
1379         res->call_convention = MONO_CALL_C;
1380 #endif
1381
1382         res->params [0] = &mono_defaults.int_class->byval_arg;  
1383         for (i = 0; i < arity; i++)
1384                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
1385
1386         res->ret = &mono_defaults.object_class->byval_arg;
1387
1388         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
1389         mono_jit_unlock ();
1390
1391         return res;
1392 }
1393
1394 MonoJitICallInfo *
1395 mono_get_array_new_va_icall (int rank)
1396 {
1397         MonoMethodSignature *esig;
1398         char icall_name [256];
1399         char *name;
1400         MonoJitICallInfo *info;
1401
1402         /* Need to register the icall so it gets an icall wrapper */
1403         sprintf (icall_name, "ves_array_new_va_%d", rank);
1404
1405         mono_jit_lock ();
1406         info = mono_find_jit_icall_by_name (icall_name);
1407         if (info == NULL) {
1408                 esig = mono_get_array_new_va_signature (rank);
1409                 name = g_strdup (icall_name);
1410                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
1411
1412                 g_hash_table_insert (jit_icall_name_hash, name, name);
1413         }
1414         mono_jit_unlock ();
1415
1416         return info;
1417 }
1418
1419 gboolean
1420 mini_class_is_system_array (MonoClass *klass)
1421 {
1422         if (klass->parent == mono_defaults.array_class)
1423                 return TRUE;
1424         else
1425                 return FALSE;
1426 }
1427
1428 gboolean
1429 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1430 {
1431         MonoAssembly *assembly = method->klass->image->assembly;
1432         if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1433                 return FALSE;
1434         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1435                 return FALSE;
1436         if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
1437                 return FALSE;
1438         return mono_assembly_has_skip_verification (assembly);
1439 }
1440
1441 /*
1442  * mini_method_verify:
1443  * 
1444  * Verify the method using the new verfier.
1445  * 
1446  * Returns true if the method is invalid. 
1447  */
1448 static gboolean
1449 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1450 {
1451         GSList *tmp, *res;
1452         gboolean is_fulltrust;
1453         MonoLoaderError *error;
1454
1455         if (method->verification_success)
1456                 return FALSE;
1457
1458         is_fulltrust = mono_verifier_is_method_full_trust (method);
1459
1460         if (!mono_verifier_is_enabled_for_method (method))
1461                 return FALSE;
1462
1463         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility);
1464
1465         if ((error = mono_loader_get_last_error ())) {
1466                 if (fail_compile)
1467                         cfg->exception_type = error->exception_type;
1468                 else
1469                         mono_loader_clear_error ();
1470                 if (res)
1471                         mono_free_verify_list (res);
1472                 return TRUE;
1473         }
1474
1475         if (res) { 
1476                 for (tmp = res; tmp; tmp = tmp->next) {
1477                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1478                         if (info->info.status == MONO_VERIFY_ERROR) {
1479                                 if (fail_compile) {
1480                                 char *method_name = mono_method_full_name (method, TRUE);
1481                                         cfg->exception_type = info->exception_type;
1482                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1483                                         g_free (method_name);
1484                                 }
1485                                 mono_free_verify_list (res);
1486                                 return TRUE;
1487                         }
1488                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1489                                 if (fail_compile) {
1490                                         char *method_name = mono_method_full_name (method, TRUE);
1491                                         cfg->exception_type = info->exception_type;
1492                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1493                                         g_free (method_name);
1494                                 }
1495                                 mono_free_verify_list (res);
1496                                 return TRUE;
1497                         }
1498                 }
1499                 mono_free_verify_list (res);
1500         }
1501         method->verification_success = 1;
1502         return FALSE;
1503 }
1504
1505 /*Returns true if something went wrong*/
1506 gboolean
1507 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1508 {
1509         MonoMethod *method_definition = method;
1510         gboolean dont_verify = mini_assembly_can_skip_verification (cfg->domain, method);
1511         dont_verify |= method->klass->image->assembly->corlib_internal;
1512
1513         while (method_definition->is_inflated) {
1514                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1515                 method_definition = imethod->declaring;
1516         }
1517
1518         return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1519 }
1520
1521 static gconstpointer
1522 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
1523 {
1524         char *name;
1525         MonoMethod *wrapper;
1526         gconstpointer trampoline;
1527         MonoDomain *domain = mono_get_root_domain ();
1528         
1529         if (callinfo->wrapper) {
1530                 return callinfo->wrapper;
1531         }
1532
1533         if (callinfo->trampoline)
1534                 return callinfo->trampoline;
1535
1536         /* 
1537          * We use the lock on the root domain instead of the JIT lock to protect 
1538          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
1539          */
1540         mono_loader_lock (); /*FIXME mono_compile_method requires the loader lock, by large.*/
1541         mono_domain_lock (domain);
1542
1543         if (callinfo->trampoline) {
1544                 mono_domain_unlock (domain);
1545                 mono_loader_unlock ();
1546                 return callinfo->trampoline;
1547         }
1548
1549         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1550         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1551         g_free (name);
1552
1553         if (do_compile)
1554                 trampoline = mono_compile_method (wrapper);
1555         else
1556                 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
1557         mono_register_jit_icall_wrapper (callinfo, trampoline);
1558
1559         callinfo->trampoline = trampoline;
1560
1561         mono_domain_unlock (domain);
1562         mono_loader_unlock ();
1563         
1564         return callinfo->trampoline;
1565 }
1566
1567 gconstpointer
1568 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
1569 {
1570         return mono_icall_get_wrapper_full (callinfo, FALSE);
1571 }
1572
1573 static void
1574 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1575 {
1576         if (!domain_jit_info (domain)->dynamic_code_hash)
1577                 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1578         g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1579 }
1580
1581 static MonoJitDynamicMethodInfo*
1582 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1583 {
1584         MonoJitDynamicMethodInfo *res;
1585
1586         if (domain_jit_info (domain)->dynamic_code_hash)
1587                 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1588         else
1589                 res = NULL;
1590         return res;
1591 }
1592
1593 typedef struct {
1594         MonoClass *vtype;
1595         GList *active, *inactive;
1596         GSList *slots;
1597 } StackSlotInfo;
1598
1599 static gint 
1600 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1601 {
1602         MonoMethodVar *v1 = (MonoMethodVar*)a;
1603         MonoMethodVar *v2 = (MonoMethodVar*)b;
1604
1605         if (v1 == v2)
1606                 return 0;
1607         else if (v1->interval->range && v2->interval->range)
1608                 return v1->interval->range->from - v2->interval->range->from;
1609         else if (v1->interval->range)
1610                 return -1;
1611         else
1612                 return 1;
1613 }
1614
1615 #ifndef DISABLE_JIT
1616
1617 #if 0
1618 #define LSCAN_DEBUG(a) do { a; } while (0)
1619 #else
1620 #define LSCAN_DEBUG(a)
1621 #endif
1622
1623 static gint32*
1624 mono_allocate_stack_slots_full2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1625 {
1626         int i, slot, offset, size;
1627         guint32 align;
1628         MonoMethodVar *vmv;
1629         MonoInst *inst;
1630         gint32 *offsets;
1631         GList *vars = NULL, *l, *unhandled;
1632         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1633         MonoType *t;
1634         int nvtypes;
1635         gboolean reuse_slot;
1636
1637         LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1638
1639         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1640         vtype_stack_slots = NULL;
1641         nvtypes = 0;
1642
1643         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1644         for (i = 0; i < cfg->num_varinfo; ++i)
1645                 offsets [i] = -1;
1646
1647         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1648                 inst = cfg->varinfo [i];
1649                 vmv = MONO_VARINFO (cfg, i);
1650
1651                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1652                         continue;
1653
1654                 vars = g_list_prepend (vars, vmv);
1655         }
1656
1657         vars = g_list_sort (g_list_copy (vars), compare_by_interval_start_pos_func);
1658
1659         /* Sanity check */
1660         /*
1661         i = 0;
1662         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1663                 MonoMethodVar *current = unhandled->data;
1664
1665                 if (current->interval->range) {
1666                         g_assert (current->interval->range->from >= i);
1667                         i = current->interval->range->from;
1668                 }
1669         }
1670         */
1671
1672         offset = 0;
1673         *stack_align = 0;
1674         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1675                 MonoMethodVar *current = unhandled->data;
1676
1677                 vmv = current;
1678                 inst = cfg->varinfo [vmv->idx];
1679
1680                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1681                 * pinvoke wrappers when they call functions returning structures */
1682                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) {
1683                         size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), &align);
1684                 }
1685                 else {
1686                         int ialign;
1687
1688                         size = mono_type_size (inst->inst_vtype, &ialign);
1689                         align = ialign;
1690
1691                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (inst->inst_vtype)))
1692                                 align = 16;
1693                 }
1694
1695                 reuse_slot = TRUE;
1696                 if (cfg->disable_reuse_stack_slots)
1697                         reuse_slot = FALSE;
1698
1699                 t = mono_type_get_underlying_type (inst->inst_vtype);
1700                 switch (t->type) {
1701                 case MONO_TYPE_GENERICINST:
1702                         if (!mono_type_generic_inst_is_valuetype (t)) {
1703                                 slot_info = &scalar_stack_slots [t->type];
1704                                 break;
1705                         }
1706                         /* Fall through */
1707                 case MONO_TYPE_VALUETYPE:
1708                         if (!vtype_stack_slots)
1709                                 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1710                         for (i = 0; i < nvtypes; ++i)
1711                                 if (t->data.klass == vtype_stack_slots [i].vtype)
1712                                         break;
1713                         if (i < nvtypes)
1714                                 slot_info = &vtype_stack_slots [i];
1715                         else {
1716                                 g_assert (nvtypes < 256);
1717                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1718                                 slot_info = &vtype_stack_slots [nvtypes];
1719                                 nvtypes ++;
1720                         }
1721                         if (cfg->disable_reuse_ref_stack_slots)
1722                                 reuse_slot = FALSE;
1723                         break;
1724
1725                 case MONO_TYPE_PTR:
1726                 case MONO_TYPE_I:
1727                 case MONO_TYPE_U:
1728 #if SIZEOF_VOID_P == 4
1729                 case MONO_TYPE_I4:
1730 #else
1731                 case MONO_TYPE_I8:
1732 #endif
1733                         if (cfg->disable_ref_noref_stack_slot_share) {
1734                                 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1735                                 break;
1736                         }
1737                         /* Fall through */
1738
1739                 case MONO_TYPE_CLASS:
1740                 case MONO_TYPE_OBJECT:
1741                 case MONO_TYPE_ARRAY:
1742                 case MONO_TYPE_SZARRAY:
1743                 case MONO_TYPE_STRING:
1744                         /* Share non-float stack slots of the same size */
1745                         slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1746                         if (cfg->disable_reuse_ref_stack_slots)
1747                                 reuse_slot = FALSE;
1748                         break;
1749
1750                 default:
1751                         slot_info = &scalar_stack_slots [t->type];
1752                 }
1753
1754                 slot = 0xffffff;
1755                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1756                         int pos;
1757                         gboolean changed;
1758
1759                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1760
1761                         if (!current->interval->range) {
1762                                 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1763                                         pos = ~0;
1764                                 else {
1765                                         /* Dead */
1766                                         inst->flags |= MONO_INST_IS_DEAD;
1767                                         continue;
1768                                 }
1769                         }
1770                         else
1771                                 pos = current->interval->range->from;
1772
1773                         LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1774                         if (current->interval->range)
1775                                 LSCAN_DEBUG (mono_linterval_print (current->interval));
1776                         LSCAN_DEBUG (printf ("\n"));
1777
1778                         /* Check for intervals in active which expired or inactive */
1779                         changed = TRUE;
1780                         /* FIXME: Optimize this */
1781                         while (changed) {
1782                                 changed = FALSE;
1783                                 for (l = slot_info->active; l != NULL; l = l->next) {
1784                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1785
1786                                         if (v->interval->last_range->to < pos) {
1787                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1788                                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1789                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1790                                                 changed = TRUE;
1791                                                 break;
1792                                         }
1793                                         else if (!mono_linterval_covers (v->interval, pos)) {
1794                                                 slot_info->inactive = g_list_append (slot_info->inactive, v);
1795                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1796                                                 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1797                                                 changed = TRUE;
1798                                                 break;
1799                                         }
1800                                 }
1801                         }
1802
1803                         /* Check for intervals in inactive which expired or active */
1804                         changed = TRUE;
1805                         /* FIXME: Optimize this */
1806                         while (changed) {
1807                                 changed = FALSE;
1808                                 for (l = slot_info->inactive; l != NULL; l = l->next) {
1809                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1810
1811                                         if (v->interval->last_range->to < pos) {
1812                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1813                                                 // FIXME: Enabling this seems to cause impossible to debug crashes
1814                                                 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1815                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1816                                                 changed = TRUE;
1817                                                 break;
1818                                         }
1819                                         else if (mono_linterval_covers (v->interval, pos)) {
1820                                                 slot_info->active = g_list_append (slot_info->active, v);
1821                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1822                                                 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1823                                                 changed = TRUE;
1824                                                 break;
1825                                         }
1826                                 }
1827                         }
1828
1829                         /* 
1830                          * This also handles the case when the variable is used in an
1831                          * exception region, as liveness info is not computed there.
1832                          */
1833                         /* 
1834                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1835                          * opcodes.
1836                          */
1837                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1838                                 if (slot_info->slots) {
1839                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
1840
1841                                         slot_info->slots = slot_info->slots->next;
1842                                 }
1843
1844                                 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1845
1846                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1847                         }
1848                 }
1849
1850 #if 0
1851                 {
1852                         static int count = 0;
1853                         count ++;
1854
1855                         if (count == atoi (getenv ("COUNT3")))
1856                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1857                         if (count > atoi (getenv ("COUNT3")))
1858                                 slot = 0xffffff;
1859                         else {
1860                                 mono_print_ins (inst);
1861                                 }
1862                 }
1863 #endif
1864
1865                 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1866
1867                 if (!reuse_slot)
1868                         slot = 0xffffff;
1869
1870                 if (slot == 0xffffff) {
1871                         /*
1872                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
1873                          * efficient copying (and to work around the fact that OP_MEMCPY
1874                          * and OP_MEMSET ignores alignment).
1875                          */
1876                         if (MONO_TYPE_ISSTRUCT (t)) {
1877                                 align = MAX (align, sizeof (gpointer));
1878                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1879                         }
1880
1881                         if (backward) {
1882                                 offset += size;
1883                                 offset += align - 1;
1884                                 offset &= ~(align - 1);
1885                                 slot = offset;
1886                         }
1887                         else {
1888                                 offset += align - 1;
1889                                 offset &= ~(align - 1);
1890                                 slot = offset;
1891                                 offset += size;
1892                         }
1893
1894                         if (*stack_align == 0)
1895                                 *stack_align = align;
1896                 }
1897
1898                 offsets [vmv->idx] = slot;
1899         }
1900         g_list_free (vars);
1901         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1902                 if (scalar_stack_slots [i].active)
1903                         g_list_free (scalar_stack_slots [i].active);
1904         }
1905         for (i = 0; i < nvtypes; ++i) {
1906                 if (vtype_stack_slots [i].active)
1907                         g_list_free (vtype_stack_slots [i].active);
1908         }
1909
1910         mono_jit_stats.locals_stack_size += offset;
1911
1912         *stack_size = offset;
1913         return offsets;
1914 }
1915
1916 /*
1917  *  mono_allocate_stack_slots_full:
1918  *
1919  *  Allocate stack slots for all non register allocated variables using a
1920  * linear scan algorithm.
1921  * Returns: an array of stack offsets.
1922  * STACK_SIZE is set to the amount of stack space needed.
1923  * STACK_ALIGN is set to the alignment needed by the locals area.
1924  */
1925 gint32*
1926 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1927 {
1928         int i, slot, offset, size;
1929         guint32 align;
1930         MonoMethodVar *vmv;
1931         MonoInst *inst;
1932         gint32 *offsets;
1933         GList *vars = NULL, *l;
1934         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1935         MonoType *t;
1936         int nvtypes;
1937         gboolean reuse_slot;
1938
1939         if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1940                 return mono_allocate_stack_slots_full2 (cfg, backward, stack_size, stack_align);
1941
1942         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1943         vtype_stack_slots = NULL;
1944         nvtypes = 0;
1945
1946         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1947         for (i = 0; i < cfg->num_varinfo; ++i)
1948                 offsets [i] = -1;
1949
1950         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1951                 inst = cfg->varinfo [i];
1952                 vmv = MONO_VARINFO (cfg, i);
1953
1954                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1955                         continue;
1956
1957                 vars = g_list_prepend (vars, vmv);
1958         }
1959
1960         vars = mono_varlist_sort (cfg, vars, 0);
1961         offset = 0;
1962         *stack_align = sizeof(mgreg_t);
1963         for (l = vars; l; l = l->next) {
1964                 vmv = l->data;
1965                 inst = cfg->varinfo [vmv->idx];
1966
1967                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1968                 * pinvoke wrappers when they call functions returning structures */
1969                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) {
1970                         size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), &align);
1971                 } else {
1972                         int ialign;
1973
1974                         size = mono_type_size (inst->inst_vtype, &ialign);
1975                         align = ialign;
1976
1977                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (inst->inst_vtype)))
1978                                 align = 16;
1979                 }
1980
1981                 reuse_slot = TRUE;
1982                 if (cfg->disable_reuse_stack_slots)
1983                         reuse_slot = FALSE;
1984
1985                 t = mono_type_get_underlying_type (inst->inst_vtype);
1986                 if (t->byref) {
1987                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
1988                 } else {
1989                         switch (t->type) {
1990                         case MONO_TYPE_GENERICINST:
1991                                 if (!mono_type_generic_inst_is_valuetype (t)) {
1992                                         slot_info = &scalar_stack_slots [t->type];
1993                                         break;
1994                                 }
1995                                 /* Fall through */
1996                         case MONO_TYPE_VALUETYPE:
1997                                 if (!vtype_stack_slots)
1998                                         vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1999                                 for (i = 0; i < nvtypes; ++i)
2000                                         if (t->data.klass == vtype_stack_slots [i].vtype)
2001                                                 break;
2002                                 if (i < nvtypes)
2003                                         slot_info = &vtype_stack_slots [i];
2004                                 else {
2005                                         g_assert (nvtypes < 256);
2006                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
2007                                         slot_info = &vtype_stack_slots [nvtypes];
2008                                         nvtypes ++;
2009                                 }
2010                                 if (cfg->disable_reuse_ref_stack_slots)
2011                                         reuse_slot = FALSE;
2012                                 break;
2013
2014                         case MONO_TYPE_PTR:
2015                         case MONO_TYPE_I:
2016                         case MONO_TYPE_U:
2017 #if SIZEOF_VOID_P == 4
2018                         case MONO_TYPE_I4:
2019 #else
2020                         case MONO_TYPE_I8:
2021 #endif
2022                                 if (cfg->disable_ref_noref_stack_slot_share) {
2023                                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
2024                                         break;
2025                                 }
2026                                 /* Fall through */
2027
2028                         case MONO_TYPE_CLASS:
2029                         case MONO_TYPE_OBJECT:
2030                         case MONO_TYPE_ARRAY:
2031                         case MONO_TYPE_SZARRAY:
2032                         case MONO_TYPE_STRING:
2033                                 /* Share non-float stack slots of the same size */
2034                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
2035                                 if (cfg->disable_reuse_ref_stack_slots)
2036                                         reuse_slot = FALSE;
2037                                 break;
2038
2039                         default:
2040                                 slot_info = &scalar_stack_slots [t->type];
2041                         }
2042                 }
2043
2044                 slot = 0xffffff;
2045                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
2046                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
2047                         
2048                         /* expire old intervals in active */
2049                         while (slot_info->active) {
2050                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
2051
2052                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
2053                                         break;
2054
2055                                 //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);
2056
2057                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
2058                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
2059                         }
2060
2061                         /* 
2062                          * This also handles the case when the variable is used in an
2063                          * exception region, as liveness info is not computed there.
2064                          */
2065                         /* 
2066                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
2067                          * opcodes.
2068                          */
2069                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
2070                                 if (slot_info->slots) {
2071                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
2072
2073                                         slot_info->slots = slot_info->slots->next;
2074                                 }
2075
2076                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
2077                         }
2078                 }
2079
2080                 {
2081                         static int count = 0;
2082                         count ++;
2083
2084                         /*
2085                         if (count == atoi (getenv ("COUNT")))
2086                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
2087                         if (count > atoi (getenv ("COUNT")))
2088                                 slot = 0xffffff;
2089                         else {
2090                                 mono_print_ins (inst);
2091                                 }
2092                         */
2093                 }
2094
2095                 if (!reuse_slot)
2096                         slot = 0xffffff;
2097
2098                 if (slot == 0xffffff) {
2099                         /*
2100                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
2101                          * efficient copying (and to work around the fact that OP_MEMCPY
2102                          * and OP_MEMSET ignores alignment).
2103                          */
2104                         if (MONO_TYPE_ISSTRUCT (t)) {
2105                                 align = MAX (align, sizeof (gpointer));
2106                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
2107                                 /* 
2108                                  * Align the size too so the code generated for passing vtypes in
2109                                  * registers doesn't overwrite random locals.
2110                                  */
2111                                 size = (size + (align - 1)) & ~(align -1);
2112                         }
2113
2114                         if (backward) {
2115                                 offset += size;
2116                                 offset += align - 1;
2117                                 offset &= ~(align - 1);
2118                                 slot = offset;
2119                         }
2120                         else {
2121                                 offset += align - 1;
2122                                 offset &= ~(align - 1);
2123                                 slot = offset;
2124                                 offset += size;
2125                         }
2126
2127                         *stack_align = MAX (*stack_align, align);
2128                 }
2129
2130                 offsets [vmv->idx] = slot;
2131         }
2132         g_list_free (vars);
2133         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
2134                 if (scalar_stack_slots [i].active)
2135                         g_list_free (scalar_stack_slots [i].active);
2136         }
2137         for (i = 0; i < nvtypes; ++i) {
2138                 if (vtype_stack_slots [i].active)
2139                         g_list_free (vtype_stack_slots [i].active);
2140         }
2141
2142         mono_jit_stats.locals_stack_size += offset;
2143
2144         *stack_size = offset;
2145         return offsets;
2146 }
2147
2148 #else
2149
2150 gint32*
2151 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
2152 {
2153         g_assert_not_reached ();
2154         return NULL;
2155 }
2156
2157 #endif /* DISABLE_JIT */
2158
2159 gint32*
2160 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
2161 {
2162         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
2163 }
2164
2165 #define EMUL_HIT_SHIFT 3
2166 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
2167 /* small hit bitmap cache */
2168 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
2169 static short emul_opcode_num = 0;
2170 static short emul_opcode_alloced = 0;
2171 static short *emul_opcode_opcodes = NULL;
2172 static MonoJitICallInfo **emul_opcode_map = NULL;
2173
2174 MonoJitICallInfo *
2175 mono_find_jit_opcode_emulation (int opcode)
2176 {
2177         g_assert (opcode >= 0 && opcode <= OP_LAST);
2178         if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
2179                 int i;
2180                 for (i = 0; i < emul_opcode_num; ++i) {
2181                         if (emul_opcode_opcodes [i] == opcode)
2182                                 return emul_opcode_map [i];
2183                 }
2184         }
2185         return NULL;
2186 }
2187
2188 void
2189 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
2190 {
2191         MonoJitICallInfo *info;
2192         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
2193
2194         g_assert (!sig->hasthis);
2195         g_assert (sig->param_count < 3);
2196
2197         info = mono_register_jit_icall (func, name, sig, no_throw);
2198
2199         if (emul_opcode_num >= emul_opcode_alloced) {
2200                 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
2201                 emul_opcode_alloced += incr;
2202                 emul_opcode_map = g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
2203                 emul_opcode_opcodes = g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
2204         }
2205         emul_opcode_map [emul_opcode_num] = info;
2206         emul_opcode_opcodes [emul_opcode_num] = opcode;
2207         emul_opcode_num++;
2208         emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
2209 }
2210
2211 static void
2212 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
2213 {
2214         MonoMethodSignature *sig;
2215
2216         if (sigstr)
2217                 sig = mono_create_icall_signature (sigstr);
2218         else
2219                 sig = NULL;
2220
2221         mono_register_jit_icall (func, name, sig, save);
2222 }
2223
2224 static void
2225 print_dfn (MonoCompile *cfg) {
2226         int i, j;
2227         char *code;
2228         MonoBasicBlock *bb;
2229         MonoInst *c;
2230
2231         {
2232                 char *method_name = mono_method_full_name (cfg->method, TRUE);
2233                 g_print ("IR code for method %s\n", method_name);
2234                 g_free (method_name);
2235         }
2236
2237         for (i = 0; i < cfg->num_bblocks; ++i) {
2238                 bb = cfg->bblocks [i];
2239                 /*if (bb->cil_code) {
2240                         char* code1, *code2;
2241                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
2242                         if (bb->last_ins->cil_code)
2243                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
2244                         else
2245                                 code2 = g_strdup ("");
2246
2247                         code1 [strlen (code1) - 1] = 0;
2248                         code = g_strdup_printf ("%s -> %s", code1, code2);
2249                         g_free (code1);
2250                         g_free (code2);
2251                 } else*/
2252                         code = g_strdup ("\n");
2253                 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
2254                 MONO_BB_FOR_EACH_INS (bb, c) {
2255                         mono_print_ins_index (-1, c);
2256                 }
2257
2258                 g_print ("\tprev:");
2259                 for (j = 0; j < bb->in_count; ++j) {
2260                         g_print (" BB%d", bb->in_bb [j]->block_num);
2261                 }
2262                 g_print ("\t\tsucc:");
2263                 for (j = 0; j < bb->out_count; ++j) {
2264                         g_print (" BB%d", bb->out_bb [j]->block_num);
2265                 }
2266                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
2267
2268                 if (bb->idom)
2269                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
2270
2271                 if (bb->dominators)
2272                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
2273                 if (bb->dfrontier)
2274                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
2275                 g_free (code);
2276         }
2277
2278         g_print ("\n");
2279 }
2280
2281 void
2282 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
2283 {
2284         MONO_ADD_INS (bb, inst);
2285 }
2286
2287 void
2288 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
2289 {
2290         if (ins == NULL) {
2291                 ins = bb->code;
2292                 bb->code = ins_to_insert;
2293
2294                 /* Link with next */
2295                 ins_to_insert->next = ins;
2296                 if (ins)
2297                         ins->prev = ins_to_insert;
2298
2299                 if (bb->last_ins == NULL)
2300                         bb->last_ins = ins_to_insert;
2301         } else {
2302                 /* Link with next */
2303                 ins_to_insert->next = ins->next;
2304                 if (ins->next)
2305                         ins->next->prev = ins_to_insert;
2306
2307                 /* Link with previous */
2308                 ins->next = ins_to_insert;
2309                 ins_to_insert->prev = ins;
2310
2311                 if (bb->last_ins == ins)
2312                         bb->last_ins = ins_to_insert;
2313         }
2314 }
2315
2316 void
2317 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
2318 {
2319         if (ins == NULL) {
2320                 ins = bb->code;
2321                 if (ins)
2322                         ins->prev = ins_to_insert;
2323                 bb->code = ins_to_insert;
2324                 ins_to_insert->next = ins;
2325                 if (bb->last_ins == NULL)
2326                         bb->last_ins = ins_to_insert;
2327         } else {
2328                 /* Link with previous */
2329                 if (ins->prev)
2330                         ins->prev->next = ins_to_insert;
2331                 ins_to_insert->prev = ins->prev;
2332
2333                 /* Link with next */
2334                 ins->prev = ins_to_insert;
2335                 ins_to_insert->next = ins;
2336
2337                 if (bb->code == ins)
2338                         bb->code = ins_to_insert;
2339         }
2340 }
2341
2342 /*
2343  * mono_verify_bblock:
2344  *
2345  *   Verify that the next and prev pointers are consistent inside the instructions in BB.
2346  */
2347 void
2348 mono_verify_bblock (MonoBasicBlock *bb)
2349 {
2350         MonoInst *ins, *prev;
2351
2352         prev = NULL;
2353         for (ins = bb->code; ins; ins = ins->next) {
2354                 g_assert (ins->prev == prev);
2355                 prev = ins;
2356         }
2357         if (bb->last_ins)
2358                 g_assert (!bb->last_ins->next);
2359 }
2360
2361 /*
2362  * mono_verify_cfg:
2363  *
2364  *   Perform consistency checks on the JIT data structures and the IR
2365  */
2366 void
2367 mono_verify_cfg (MonoCompile *cfg)
2368 {
2369         MonoBasicBlock *bb;
2370
2371         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2372                 mono_verify_bblock (bb);
2373 }
2374
2375 void
2376 mono_destroy_compile (MonoCompile *cfg)
2377 {
2378         GSList *l;
2379
2380         if (cfg->header)
2381                 mono_metadata_free_mh (cfg->header);
2382         //mono_mempool_stats (cfg->mempool);
2383         mono_free_loop_info (cfg);
2384         if (cfg->rs)
2385                 mono_regstate_free (cfg->rs);
2386         if (cfg->spvars)
2387                 g_hash_table_destroy (cfg->spvars);
2388         if (cfg->exvars)
2389                 g_hash_table_destroy (cfg->exvars);
2390         for (l = cfg->headers_to_free; l; l = l->next)
2391                 mono_metadata_free_mh (l->data);
2392         g_list_free (cfg->ldstr_list);
2393         g_hash_table_destroy (cfg->token_info_hash);
2394         if (cfg->abs_patches)
2395                 g_hash_table_destroy (cfg->abs_patches);
2396         mono_mempool_destroy (cfg->mempool);
2397
2398         mono_debug_free_method (cfg);
2399
2400         g_free (cfg->varinfo);
2401         g_free (cfg->vars);
2402         g_free (cfg->exception_message);
2403         g_free (cfg);
2404 }
2405
2406 #ifdef MINI_HAVE_FAST_TLS
2407 MINI_FAST_TLS_DECLARE(mono_lmf_addr);
2408 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
2409 /* 
2410  * When this is defined, the current lmf is stored in this tls variable instead of in 
2411  * jit_tls->lmf.
2412  */
2413 MINI_FAST_TLS_DECLARE(mono_lmf);
2414 #endif
2415 #endif
2416
2417 guint32
2418 mono_get_jit_tls_key (void)
2419 {
2420         return mono_jit_tls_id;
2421 }
2422
2423 gint32
2424 mono_get_jit_tls_offset (void)
2425 {
2426 #ifdef MINI_HAVE_FAST_TLS
2427         int offset;
2428         MINI_THREAD_VAR_OFFSET (mono_jit_tls, offset);
2429         return offset;
2430 #else
2431         return -1;
2432 #endif
2433 }
2434
2435 gint32
2436 mono_get_lmf_tls_offset (void)
2437 {
2438 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2439         int offset;
2440         MINI_THREAD_VAR_OFFSET(mono_lmf,offset);
2441         return offset;
2442 #else
2443         return -1;
2444 #endif
2445 }
2446
2447 gint32
2448 mono_get_lmf_addr_tls_offset (void)
2449 {
2450         int offset;
2451         MINI_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
2452         return offset;
2453 }
2454
2455 MonoLMF *
2456 mono_get_lmf (void)
2457 {
2458 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2459         return MINI_FAST_TLS_GET (mono_lmf);
2460 #else
2461         MonoJitTlsData *jit_tls;
2462
2463         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
2464                 return jit_tls->lmf;
2465
2466         g_assert_not_reached ();
2467         return NULL;
2468 #endif
2469 }
2470
2471 MonoLMF **
2472 mono_get_lmf_addr (void)
2473 {
2474 #ifdef MINI_HAVE_FAST_TLS
2475         return MINI_FAST_TLS_GET (mono_lmf_addr);
2476 #else
2477         MonoJitTlsData *jit_tls;
2478
2479         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
2480                 return &jit_tls->lmf;
2481
2482         /*
2483          * When resolving the call to mono_jit_thread_attach full-aot will look
2484          * in the plt, which causes a call into the generic trampoline, which in turn
2485          * tries to resolve the lmf_addr creating a cyclic dependency.  We cannot
2486          * call mono_jit_thread_attach from the native-to-managed wrapper, without
2487          * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
2488          */
2489
2490         mono_jit_thread_attach (NULL);
2491         
2492         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
2493                 return &jit_tls->lmf;
2494
2495         g_assert_not_reached ();
2496         return NULL;
2497 #endif
2498 }
2499
2500 void
2501 mono_set_lmf (MonoLMF *lmf)
2502 {
2503 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2504         MINI_FAST_TLS_SET (mono_lmf, lmf);
2505 #endif
2506
2507         (*mono_get_lmf_addr ()) = lmf;
2508 }
2509
2510 static void
2511 mono_set_jit_tls (MonoJitTlsData *jit_tls)
2512 {
2513         TlsSetValue (mono_jit_tls_id, jit_tls);
2514
2515 #ifdef MINI_HAVE_FAST_TLS
2516         MINI_FAST_TLS_SET (mono_jit_tls, jit_tls);
2517 #endif
2518 }
2519
2520 static void
2521 mono_set_lmf_addr (gpointer lmf_addr)
2522 {
2523 #ifdef MINI_HAVE_FAST_TLS
2524         MINI_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
2525 #endif
2526 }
2527
2528 /* Called by native->managed wrappers */
2529 void
2530 mono_jit_thread_attach (MonoDomain *domain)
2531 {
2532         if (!domain)
2533                 /* 
2534                  * Happens when called from AOTed code which is only used in the root
2535                  * domain.
2536                  */
2537                 domain = mono_get_root_domain ();
2538
2539 #ifdef MINI_HAVE_FAST_TLS
2540         if (!MINI_FAST_TLS_GET (mono_lmf_addr)) {
2541                 mono_thread_attach (domain);
2542         }
2543 #else
2544         if (!TlsGetValue (mono_jit_tls_id))
2545                 mono_thread_attach (domain);
2546 #endif
2547         if (mono_domain_get () != domain)
2548                 mono_domain_set (domain, TRUE);
2549 }       
2550
2551 /**
2552  * mono_thread_abort:
2553  * @obj: exception object
2554  *
2555  * abort the thread, print exception information and stack trace
2556  */
2557 static void
2558 mono_thread_abort (MonoObject *obj)
2559 {
2560         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
2561         
2562         /* handle_remove should be eventually called for this thread, too
2563         g_free (jit_tls);*/
2564
2565         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
2566                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
2567                 mono_thread_exit ();
2568         } else {
2569                 exit (mono_environment_exitcode_get ());
2570         }
2571 }
2572
2573 static void*
2574 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
2575 {
2576         MonoJitTlsData *jit_tls;
2577         MonoLMF *lmf;
2578
2579         jit_tls = TlsGetValue (mono_jit_tls_id);
2580         if (jit_tls)
2581                 return jit_tls;
2582
2583         jit_tls = g_new0 (MonoJitTlsData, 1);
2584
2585         jit_tls->abort_func = abort_func;
2586         jit_tls->end_of_stack = stack_start;
2587
2588         mono_set_jit_tls (jit_tls);
2589
2590         lmf = g_new0 (MonoLMF, 1);
2591         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
2592
2593         jit_tls->first_lmf = lmf;
2594
2595 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2596         /* jit_tls->lmf is unused */
2597         MINI_FAST_TLS_SET (mono_lmf, lmf);
2598         mono_set_lmf_addr (&mono_lmf);
2599 #else
2600         mono_set_lmf_addr (&jit_tls->lmf);
2601
2602         jit_tls->lmf = lmf;
2603 #endif
2604
2605         mono_arch_setup_jit_tls_data (jit_tls);
2606         mono_setup_altstack (jit_tls);
2607
2608         return jit_tls;
2609 }
2610
2611 static void
2612 free_jit_tls_data (MonoJitTlsData *jit_tls)
2613 {
2614         mono_arch_free_jit_tls_data (jit_tls);
2615         mono_free_altstack (jit_tls);
2616
2617         g_free (jit_tls->first_lmf);
2618         g_free (jit_tls);
2619 }
2620
2621 static void
2622 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
2623 {
2624         MonoInternalThread *thread;
2625         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
2626         thread = mono_thread_internal_current ();
2627         mono_debugger_thread_created (tid, thread->root_domain_thread, jit_tls, func);
2628         if (thread)
2629                 thread->jit_data = jit_tls;
2630
2631         mono_arch_cpu_init ();
2632 }
2633
2634 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
2635
2636 static void
2637 mono_thread_abort_dummy (MonoObject *obj)
2638 {
2639   if (mono_thread_attach_aborted_cb)
2640     mono_thread_attach_aborted_cb (obj);
2641   else
2642     mono_thread_abort (obj);
2643 }
2644
2645 static void
2646 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
2647 {
2648         MonoInternalThread *thread;
2649         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
2650         thread = mono_thread_internal_current ();
2651         mono_debugger_thread_created (tid, thread->root_domain_thread, (MonoJitTlsData *) jit_tls, NULL);
2652         if (thread)
2653                 thread->jit_data = jit_tls;
2654         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
2655                 mono_runtime_setup_stat_profiler ();
2656
2657         mono_arch_cpu_init ();
2658 }
2659
2660 static void
2661 mini_thread_cleanup (MonoInternalThread *thread)
2662 {
2663         MonoJitTlsData *jit_tls = thread->jit_data;
2664
2665         if (jit_tls) {
2666                 mono_debugger_thread_cleanup (jit_tls);
2667
2668                 /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
2669                  * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
2670                  * not a trivial thing.
2671                  *
2672                  * The current offender is mono_thread_manage which cleanup threads from the outside.
2673                  */
2674                 if (thread == mono_thread_internal_current ()) {
2675                         mono_set_lmf (NULL);
2676                         mono_set_jit_tls (NULL);
2677                         mono_set_lmf_addr (NULL);
2678                 }
2679
2680                 free_jit_tls_data (jit_tls);
2681
2682                 thread->jit_data = NULL;
2683         }
2684 }
2685
2686 static MonoInst*
2687 mono_create_tls_get (MonoCompile *cfg, int offset)
2688 {
2689 #ifdef MONO_ARCH_HAVE_TLS_GET
2690         if (MONO_ARCH_HAVE_TLS_GET) {
2691                 MonoInst* ins;
2692
2693                 if (offset == -1)
2694                         return NULL;
2695
2696                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
2697                 ins->dreg = mono_alloc_preg (cfg);
2698                 ins->inst_offset = offset;
2699                 return ins;
2700         }
2701 #endif
2702         return NULL;
2703 }
2704
2705 MonoInst*
2706 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2707 {
2708         return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
2709 }
2710
2711 MonoInst*
2712 mono_get_domain_intrinsic (MonoCompile* cfg)
2713 {
2714         return mono_create_tls_get (cfg, mono_domain_get_tls_offset ());
2715 }
2716
2717 MonoInst*
2718 mono_get_thread_intrinsic (MonoCompile* cfg)
2719 {
2720         return mono_create_tls_get (cfg, mono_thread_get_tls_offset ());
2721 }
2722
2723 void
2724 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2725 {
2726         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2727
2728         ji->ip.i = ip;
2729         ji->type = type;
2730         ji->data.target = target;
2731         ji->next = cfg->patch_info;
2732
2733         cfg->patch_info = ji;
2734 }
2735
2736 MonoJumpInfo *
2737 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
2738 {
2739         MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
2740
2741         ji->ip.i = ip;
2742         ji->type = type;
2743         ji->data.target = target;
2744         ji->next = list;
2745
2746         return ji;
2747 }
2748
2749 void
2750 mono_remove_patch_info (MonoCompile *cfg, int ip)
2751 {
2752         MonoJumpInfo **ji = &cfg->patch_info;
2753
2754         while (*ji) {
2755                 if ((*ji)->ip.i == ip)
2756                         *ji = (*ji)->next;
2757                 else
2758                         ji = &((*ji)->next);
2759         }
2760 }
2761
2762 /**
2763  * mono_patch_info_dup_mp:
2764  *
2765  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
2766  */
2767 MonoJumpInfo*
2768 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
2769 {
2770         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2771         memcpy (res, patch_info, sizeof (MonoJumpInfo));
2772
2773         switch (patch_info->type) {
2774         case MONO_PATCH_INFO_RVA:
2775         case MONO_PATCH_INFO_LDSTR:
2776         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2777         case MONO_PATCH_INFO_LDTOKEN:
2778         case MONO_PATCH_INFO_DECLSEC:
2779                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
2780                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
2781                 break;
2782         case MONO_PATCH_INFO_SWITCH:
2783                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
2784                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
2785                 res->data.table->table = mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
2786                 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
2787                 break;
2788         case MONO_PATCH_INFO_RGCTX_FETCH:
2789                 res->data.rgctx_entry = mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
2790                 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
2791                 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
2792                 break;
2793         default:
2794                 break;
2795         }
2796
2797         return res;
2798 }
2799
2800 guint
2801 mono_patch_info_hash (gconstpointer data)
2802 {
2803         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
2804
2805         switch (ji->type) {
2806         case MONO_PATCH_INFO_RVA:
2807         case MONO_PATCH_INFO_LDSTR:
2808         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2809         case MONO_PATCH_INFO_LDTOKEN:
2810         case MONO_PATCH_INFO_DECLSEC:
2811                 return (ji->type << 8) | ji->data.token->token;
2812         case MONO_PATCH_INFO_INTERNAL_METHOD:
2813                 return (ji->type << 8) | g_str_hash (ji->data.name);
2814         case MONO_PATCH_INFO_VTABLE:
2815         case MONO_PATCH_INFO_CLASS:
2816         case MONO_PATCH_INFO_IID:
2817         case MONO_PATCH_INFO_ADJUSTED_IID:
2818         case MONO_PATCH_INFO_CLASS_INIT:
2819         case MONO_PATCH_INFO_METHODCONST:
2820         case MONO_PATCH_INFO_METHOD:
2821         case MONO_PATCH_INFO_METHOD_JUMP:
2822         case MONO_PATCH_INFO_IMAGE:
2823         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2824         case MONO_PATCH_INFO_FIELD:
2825         case MONO_PATCH_INFO_SFLDA:
2826         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2827                 return (ji->type << 8) | (gssize)ji->data.target;
2828         default:
2829                 return (ji->type << 8);
2830         }
2831 }
2832
2833 /* 
2834  * mono_patch_info_equal:
2835  * 
2836  * This might fail to recognize equivalent patches, i.e. floats, so its only
2837  * usable in those cases where this is not a problem, i.e. sharing GOT slots
2838  * in AOT.
2839  */
2840 gint
2841 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
2842 {
2843         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
2844         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
2845
2846         if (ji1->type != ji2->type)
2847                 return 0;
2848
2849         switch (ji1->type) {
2850         case MONO_PATCH_INFO_RVA:
2851         case MONO_PATCH_INFO_LDSTR:
2852         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2853         case MONO_PATCH_INFO_LDTOKEN:
2854         case MONO_PATCH_INFO_DECLSEC:
2855                 if ((ji1->data.token->image != ji2->data.token->image) ||
2856                         (ji1->data.token->token != ji2->data.token->token) || 
2857                         (ji1->data.token->has_context != ji2->data.token->has_context) ||
2858                         (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
2859                         (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
2860                         return 0;
2861                 break;
2862         case MONO_PATCH_INFO_INTERNAL_METHOD:
2863                 return g_str_equal (ji1->data.name, ji2->data.name);
2864
2865         case MONO_PATCH_INFO_RGCTX_FETCH: {
2866                 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
2867                 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
2868
2869                 return e1->method == e2->method && e1->in_mrgctx == e2->in_mrgctx && e1->info_type == e2->info_type && mono_patch_info_equal (e1->data, e2->data);
2870         }
2871         default:
2872                 if (ji1->data.target != ji2->data.target)
2873                         return 0;
2874                 break;
2875         }
2876
2877         return 1;
2878 }
2879
2880 gpointer
2881 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
2882 {
2883         unsigned char *ip = patch_info->ip.i + code;
2884         gconstpointer target = NULL;
2885
2886         switch (patch_info->type) {
2887         case MONO_PATCH_INFO_BB:
2888                 /* 
2889                  * FIXME: This could be hit for methods without a prolog. Should use -1
2890                  * but too much code depends on a 0 initial value.
2891                  */
2892                 //g_assert (patch_info->data.bb->native_offset);
2893                 target = patch_info->data.bb->native_offset + code;
2894                 break;
2895         case MONO_PATCH_INFO_ABS:
2896                 target = patch_info->data.target;
2897                 break;
2898         case MONO_PATCH_INFO_LABEL:
2899                 target = patch_info->data.inst->inst_c0 + code;
2900                 break;
2901         case MONO_PATCH_INFO_IP:
2902 #if defined(__native_client__) && defined(__native_client_codegen__)
2903                 /* Need to transform to the destination address, it's */
2904                 /* emitted as an immediate in the code. */
2905                 target = nacl_inverse_modify_patch_target(ip);
2906 #else
2907                 target = ip;
2908 #endif
2909                 break;
2910         case MONO_PATCH_INFO_METHOD_REL:
2911                 target = code + patch_info->data.offset;
2912                 break;
2913         case MONO_PATCH_INFO_INTERNAL_METHOD: {
2914                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
2915                 if (!mi) {
2916                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
2917                         g_assert_not_reached ();
2918                 }
2919                 target = mono_icall_get_wrapper (mi);
2920                 break;
2921         }
2922         case MONO_PATCH_INFO_METHOD_JUMP:
2923                 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE);
2924 #if defined(__native_client__) && defined(__native_client_codegen__)
2925 #if defined(TARGET_AMD64)
2926                 /* This target is an absolute address, not relative to the */
2927                 /* current code being emitted on AMD64. */
2928                 target = nacl_inverse_modify_patch_target(target);
2929 #endif
2930 #endif
2931                 break;
2932         case MONO_PATCH_INFO_METHOD:
2933                 if (patch_info->data.method == method) {
2934                         target = code;
2935                 } else {
2936                         /* get the trampoline to the method from the domain */
2937                         target = mono_create_jit_trampoline (patch_info->data.method);
2938                 }
2939                 break;
2940         case MONO_PATCH_INFO_SWITCH: {
2941                 gpointer *jump_table;
2942                 int i;
2943
2944 #if defined(__native_client__) && defined(__native_client_codegen__)
2945                 /* This memory will leak, but we don't care if we're */
2946                 /* not deleting JIT'd methods anyway                 */
2947                 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
2948 #else
2949                 if (method && method->dynamic) {
2950                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2951                 } else {
2952                         if (mono_aot_only) {
2953                                 jump_table = mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
2954                         } else {
2955                                 jump_table = mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
2956                         }
2957                 }
2958 #endif
2959
2960                 for (i = 0; i < patch_info->data.table->table_size; i++) {
2961 #if defined(__native_client__) && defined(__native_client_codegen__)
2962                         /* 'code' is relative to the current code blob, we */
2963                         /* need to do this transform on it to make the     */
2964                         /* pointers in this table absolute                 */
2965                         jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
2966 #else
2967                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
2968 #endif
2969                 }
2970
2971 #if defined(__native_client__) && defined(__native_client_codegen__)
2972                 /* jump_table is in the data section, we need to transform */
2973                 /* it here so when it gets modified in amd64_patch it will */
2974                 /* then point back to the absolute data address            */
2975                 target = nacl_inverse_modify_patch_target (jump_table);
2976 #else
2977                 target = jump_table;
2978 #endif
2979                 break;
2980         }
2981         case MONO_PATCH_INFO_METHODCONST:
2982         case MONO_PATCH_INFO_CLASS:
2983         case MONO_PATCH_INFO_IMAGE:
2984         case MONO_PATCH_INFO_FIELD:
2985                 target = patch_info->data.target;
2986                 break;
2987         case MONO_PATCH_INFO_IID:
2988                 mono_class_init (patch_info->data.klass);
2989                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
2990                 break;
2991         case MONO_PATCH_INFO_ADJUSTED_IID:
2992                 mono_class_init (patch_info->data.klass);
2993                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
2994                 break;
2995         case MONO_PATCH_INFO_VTABLE:
2996                 target = mono_class_vtable (domain, patch_info->data.klass);
2997                 g_assert (target);
2998                 break;
2999         case MONO_PATCH_INFO_CLASS_INIT: {
3000                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
3001
3002                 g_assert (vtable);
3003                 target = mono_create_class_init_trampoline (vtable);
3004                 break;
3005         }
3006         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3007                 target = mono_create_delegate_trampoline (patch_info->data.klass);
3008                 break;
3009         case MONO_PATCH_INFO_SFLDA: {
3010                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
3011
3012                 if (mono_class_field_is_special_static (patch_info->data.field)) {
3013                         gpointer addr = NULL;
3014
3015                         mono_domain_lock (domain);
3016                         if (domain->special_static_fields)
3017                                 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
3018                         mono_domain_unlock (domain);
3019                         g_assert (addr);
3020                         return addr;
3021                 }
3022
3023                 g_assert (vtable);
3024                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
3025                         /* Done by the generated code */
3026                         ;
3027                 else {
3028                         if (run_cctors)
3029                                 mono_runtime_class_init (vtable);
3030                 }
3031                 target = (char*)vtable->data + patch_info->data.field->offset;
3032                 break;
3033         }
3034         case MONO_PATCH_INFO_RVA: {
3035                 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
3036                 guint32 rva;
3037
3038                 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
3039                 target = mono_image_rva_map (patch_info->data.token->image, rva);
3040                 break;
3041         }
3042         case MONO_PATCH_INFO_R4:
3043         case MONO_PATCH_INFO_R8:
3044                 target = patch_info->data.target;
3045                 break;
3046         case MONO_PATCH_INFO_EXC_NAME:
3047                 target = patch_info->data.name;
3048                 break;
3049         case MONO_PATCH_INFO_LDSTR:
3050                 target =
3051                         mono_ldstr (domain, patch_info->data.token->image, 
3052                                                 mono_metadata_token_index (patch_info->data.token->token));
3053                 break;
3054         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
3055                 gpointer handle;
3056                 MonoClass *handle_class;
3057
3058                 handle = mono_ldtoken (patch_info->data.token->image, 
3059                                                            patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL);
3060                 mono_class_init (handle_class);
3061                 mono_class_init (mono_class_from_mono_type (handle));
3062
3063                 target =
3064                         mono_type_get_object (domain, handle);
3065                 break;
3066         }
3067         case MONO_PATCH_INFO_LDTOKEN: {
3068                 gpointer handle;
3069                 MonoClass *handle_class;
3070                 
3071                 handle = mono_ldtoken (patch_info->data.token->image,
3072                                        patch_info->data.token->token, &handle_class, NULL);
3073                 mono_class_init (handle_class);
3074                 
3075                 target = handle;
3076                 break;
3077         }
3078         case MONO_PATCH_INFO_DECLSEC:
3079                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
3080                 break;
3081         case MONO_PATCH_INFO_ICALL_ADDR:
3082                 /* run_cctors == 0 -> AOT */
3083                 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
3084                         if (run_cctors) {
3085                                 target = mono_lookup_pinvoke_call (patch_info->data.method, NULL, NULL);
3086                                 if (!target)
3087                                         g_error ("Unable to resolve pinvoke method '%s' Re-run with MONO_LOG_LEVEL=debug for more information.\n", mono_method_full_name (patch_info->data.method, TRUE));
3088                         } else {
3089                                 target = NULL;
3090                         }
3091                 } else {
3092                         target = mono_lookup_internal_call (patch_info->data.method);
3093
3094                         if (!target && run_cctors)
3095                                 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
3096                 }
3097                 break;
3098         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3099                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
3100                 if (!mi) {
3101                         g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
3102                         g_assert_not_reached ();
3103                 }
3104                 target = mi->func;
3105                 break;
3106         }
3107         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3108                 target = mono_thread_interruption_request_flag ();
3109                 break;
3110         case MONO_PATCH_INFO_METHOD_RGCTX: {
3111                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
3112                 g_assert (vtable);
3113
3114                 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
3115                 break;
3116         }
3117         case MONO_PATCH_INFO_BB_OVF:
3118         case MONO_PATCH_INFO_EXC_OVF:
3119         case MONO_PATCH_INFO_GOT_OFFSET:
3120         case MONO_PATCH_INFO_NONE:
3121                 break;
3122         case MONO_PATCH_INFO_RGCTX_FETCH: {
3123                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3124                 guint32 slot = -1;
3125
3126                 switch (entry->data->type) {
3127                 case MONO_PATCH_INFO_CLASS:
3128                         slot = mono_method_lookup_or_register_other_info (entry->method, entry->in_mrgctx, &entry->data->data.klass->byval_arg, entry->info_type, mono_method_get_context (entry->method));
3129                         break;
3130                 case MONO_PATCH_INFO_METHOD:
3131                 case MONO_PATCH_INFO_METHODCONST:
3132                         slot = mono_method_lookup_or_register_other_info (entry->method, entry->in_mrgctx, entry->data->data.method, entry->info_type, mono_method_get_context (entry->method));
3133                         break;
3134                 case MONO_PATCH_INFO_FIELD:
3135                         slot = mono_method_lookup_or_register_other_info (entry->method, entry->in_mrgctx, entry->data->data.field, entry->info_type, mono_method_get_context (entry->method));
3136                         break;
3137                 default:
3138                         g_assert_not_reached ();
3139                         break;
3140                 }
3141
3142                 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
3143                 break;
3144         }
3145         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3146                 target = mono_create_generic_class_init_trampoline ();
3147                 break;
3148         case MONO_PATCH_INFO_MONITOR_ENTER:
3149                 target = mono_create_monitor_enter_trampoline ();
3150                 break;
3151         case MONO_PATCH_INFO_MONITOR_EXIT:
3152                 target = mono_create_monitor_exit_trampoline ();
3153                 break;
3154 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3155         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3156                 if (!run_cctors)
3157                         /* AOT, not needed */
3158                         target = NULL;
3159                 else
3160                         target = mono_arch_get_seq_point_info (domain, code);
3161                 break;
3162 #endif
3163         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3164 #ifdef MONO_ARCH_LLVM_SUPPORTED
3165                 g_assert (mono_use_llvm);
3166                 target = mono_create_llvm_imt_trampoline (domain, patch_info->data.imt_tramp->method, patch_info->data.imt_tramp->vt_offset);
3167 #else
3168                 g_assert_not_reached ();
3169 #endif
3170                 break;
3171         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
3172                 int card_table_shift_bits;
3173                 gpointer card_table_mask;
3174
3175                 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3176                 break;
3177         }
3178         default:
3179                 g_assert_not_reached ();
3180         }
3181
3182         return (gpointer)target;
3183 }
3184
3185 void
3186 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
3187 {
3188         ins->inst_offset = native_offset;
3189         g_ptr_array_add (cfg->seq_points, ins);
3190         bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
3191         bb->last_seq_point = ins;
3192 }
3193
3194 #ifndef DISABLE_JIT
3195
3196 static void
3197 mono_compile_create_vars (MonoCompile *cfg)
3198 {
3199         MonoMethodSignature *sig;
3200         MonoMethodHeader *header;
3201         int i;
3202
3203         header = cfg->header;
3204
3205         sig = mono_method_signature (cfg->method);
3206         
3207         if (!MONO_TYPE_IS_VOID (sig->ret)) {
3208                 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
3209                 /* Inhibit optimizations */
3210                 cfg->ret->flags |= MONO_INST_VOLATILE;
3211         }
3212         if (cfg->verbose_level > 2)
3213                 g_print ("creating vars\n");
3214
3215         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
3216
3217         if (sig->hasthis)
3218                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
3219
3220         for (i = 0; i < sig->param_count; ++i) {
3221                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
3222         }
3223
3224         if (cfg->verbose_level > 2) {
3225                 if (cfg->ret) {
3226                         printf ("\treturn : ");
3227                         mono_print_ins (cfg->ret);
3228                 }
3229
3230                 if (sig->hasthis) {
3231                         printf ("\tthis: ");
3232                         mono_print_ins (cfg->args [0]);
3233                 }
3234
3235                 for (i = 0; i < sig->param_count; ++i) {
3236                         printf ("\targ [%d]: ", i);
3237                         mono_print_ins (cfg->args [i + sig->hasthis]);
3238                 }
3239         }
3240
3241         cfg->locals_start = cfg->num_varinfo;
3242         cfg->locals = mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
3243
3244         if (cfg->verbose_level > 2)
3245                 g_print ("creating locals\n");
3246
3247         for (i = 0; i < header->num_locals; ++i)
3248                 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
3249
3250         if (cfg->verbose_level > 2)
3251                 g_print ("locals done\n");
3252
3253         mono_arch_create_vars (cfg);
3254 }
3255
3256 #endif /* #ifndef DISABLE_JIT */
3257
3258 void
3259 mono_print_code (MonoCompile *cfg, const char* msg)
3260 {
3261         MonoBasicBlock *bb;
3262         
3263         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3264                 mono_print_bb (bb, msg);
3265 }
3266
3267 #ifndef DISABLE_JIT
3268
3269 static void
3270 mono_postprocess_patches (MonoCompile *cfg)
3271 {
3272         MonoJumpInfo *patch_info;
3273         int i;
3274
3275         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3276                 switch (patch_info->type) {
3277                 case MONO_PATCH_INFO_ABS: {
3278                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
3279
3280                         /*
3281                          * Change patches of type MONO_PATCH_INFO_ABS into patches describing the 
3282                          * absolute address.
3283                          */
3284                         if (info) {
3285                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
3286                                 // FIXME: CLEAN UP THIS MESS.
3287                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
3288                                         strstr (cfg->method->name, info->name)) {
3289                                         /*
3290                                          * This is an icall wrapper, and this is a call to the
3291                                          * wrapped function.
3292                                          */
3293                                         if (cfg->compile_aot) {
3294                                                 patch_info->type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
3295                                                 patch_info->data.name = info->name;
3296                                         }
3297                                 } else {
3298                                         /* for these array methods we currently register the same function pointer
3299                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
3300                                          * will return the incorrect one depending on the order they are registered.
3301                                          * See tests/test-arr.cs
3302                                          */
3303                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
3304                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
3305                                                 patch_info->data.name = info->name;
3306                                         }
3307                                 }
3308                         }
3309
3310                         if (patch_info->type == MONO_PATCH_INFO_ABS) {
3311                                 if (cfg->abs_patches) {
3312                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
3313                                         if (abs_ji) {
3314                                                 patch_info->type = abs_ji->type;
3315                                                 patch_info->data.target = abs_ji->data.target;
3316                                         }
3317                                 }
3318                         }
3319
3320                         break;
3321                 }
3322                 case MONO_PATCH_INFO_SWITCH: {
3323                         gpointer *table;
3324 #if defined(__native_client__) && defined(__native_client_codegen__)
3325                         /* This memory will leak.  */
3326                         /* TODO: can we free this when  */
3327                         /* making the final jump table? */
3328                         table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
3329 #else
3330                         if (cfg->method->dynamic) {
3331                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
3332                         } else {
3333                                 table = mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
3334                         }
3335 #endif
3336
3337                         for (i = 0; i < patch_info->data.table->table_size; i++) {
3338                                 /* Might be NULL if the switch is eliminated */
3339                                 if (patch_info->data.table->table [i]) {
3340                                         g_assert (patch_info->data.table->table [i]->native_offset);
3341                                         table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
3342                                 } else {
3343                                         table [i] = NULL;
3344                                 }
3345                         }
3346                         patch_info->data.table->table = (MonoBasicBlock**)table;
3347                         break;
3348                 }
3349                 case MONO_PATCH_INFO_METHOD_JUMP: {
3350                         GSList *list;
3351                         MonoDomain *domain = cfg->domain;
3352                         unsigned char *ip = cfg->native_code + patch_info->ip.i;
3353 #if defined(__native_client__) && defined(__native_client_codegen__)
3354                         /* When this jump target gets evaluated, the method */
3355                         /* will be installed in the dynamic code section,   */
3356                         /* not at the location of cfg->native_code.         */
3357                         ip = nacl_inverse_modify_patch_target (cfg->native_code) + patch_info->ip.i;
3358 #endif
3359
3360                         mono_domain_lock (domain);
3361                         if (!domain_jit_info (domain)->jump_target_hash)
3362                                 domain_jit_info (domain)->jump_target_hash = g_hash_table_new (NULL, NULL);
3363                         list = g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
3364                         list = g_slist_prepend (list, ip);
3365                         g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, list);
3366                         mono_domain_unlock (domain);
3367                         break;
3368                 }
3369                 default:
3370                         /* do nothing */
3371                         break;
3372                 }
3373         }
3374 }
3375
3376 static void
3377 collect_pred_seq_points (MonoBasicBlock *bb, MonoInst *ins, GSList **next, int depth)
3378 {
3379         int i;
3380         MonoBasicBlock *in_bb;
3381
3382         for (i = 0; i < bb->in_count; ++i) {
3383                 in_bb = bb->in_bb [i];
3384
3385                 if (in_bb->last_seq_point) {
3386                         next [in_bb->last_seq_point->backend.size] = g_slist_append (next [in_bb->last_seq_point->backend.size], GUINT_TO_POINTER (ins->backend.size));
3387                 } else {
3388                         /* Have to look at its predecessors */
3389                         if (depth < 5)
3390                                 collect_pred_seq_points (in_bb, ins, next, depth + 1);
3391                 }
3392         }
3393 }
3394
3395 static void
3396 mono_save_seq_point_info (MonoCompile *cfg)
3397 {
3398         MonoBasicBlock *bb;
3399         GSList *bb_seq_points, *l;
3400         MonoInst *last;
3401         MonoDomain *domain = cfg->domain;
3402         int i;
3403         MonoSeqPointInfo *info;
3404         GSList **next;
3405
3406         if (!cfg->seq_points)
3407                 return;
3408
3409         info = g_malloc0 (sizeof (MonoSeqPointInfo) + (cfg->seq_points->len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
3410         info->len = cfg->seq_points->len;
3411         for (i = 0; i < cfg->seq_points->len; ++i) {
3412                 SeqPoint *sp = &info->seq_points [i];
3413                 MonoInst *ins = g_ptr_array_index (cfg->seq_points, i);
3414
3415                 sp->il_offset = ins->inst_imm;
3416                 sp->native_offset = ins->inst_offset;
3417
3418                 /* Used below */
3419                 ins->backend.size = i;
3420         }
3421
3422         /*
3423          * For each sequence point, compute the list of sequence points immediately
3424          * following it, this is needed to implement 'step over' in the debugger agent.
3425          */ 
3426         next = g_new0 (GSList*, cfg->seq_points->len);
3427         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3428                 bb_seq_points = g_slist_reverse (bb->seq_points);
3429                 last = NULL;
3430                 for (l = bb_seq_points; l; l = l->next) {
3431                         MonoInst *ins = l->data;
3432
3433                         if (!(ins->flags & MONO_INST_SINGLE_STEP_LOC))
3434                                 continue;
3435
3436                         if (last != NULL) {
3437                                 /* Link with the previous seq point in the same bb */
3438                                 next [last->backend.size] = g_slist_append (next [last->backend.size], GUINT_TO_POINTER (ins->backend.size));
3439                         } else {
3440                                 /* Link with the last bb in the previous bblocks */
3441                                 collect_pred_seq_points (bb, ins, next, 0);
3442                         }
3443
3444                         last = ins;
3445                 }
3446         }
3447
3448         if (cfg->verbose_level > 2) {
3449                 printf ("\nSEQ POINT MAP: \n");
3450         }
3451
3452         for (i = 0; i < cfg->seq_points->len; ++i) {
3453                 SeqPoint *sp = &info->seq_points [i];
3454                 GSList *l;
3455                 int j, next_index;
3456
3457                 sp->next_len = g_slist_length (next [i]);
3458                 sp->next = g_new (int, sp->next_len);
3459                 j = 0;
3460                 if (cfg->verbose_level > 2 && next [i]) {
3461                         printf ("\t0x%x ->", sp->il_offset);
3462                         for (l = next [i]; l; l = l->next) {
3463                                 next_index = GPOINTER_TO_UINT (l->data);
3464                                 printf (" 0x%x", info->seq_points [next_index].il_offset);
3465                         }
3466                         printf ("\n");
3467                 }
3468                 for (l = next [i]; l; l = l->next) {
3469                         next_index = GPOINTER_TO_UINT (l->data);
3470                         sp->next [j ++] = next_index;
3471                 }
3472                 g_slist_free (next [i]);
3473         }
3474         g_free (next);
3475
3476         cfg->seq_point_info = info;
3477
3478         // FIXME: dynamic methods
3479         if (!cfg->compile_aot) {
3480                 mono_domain_lock (domain);
3481                 // FIXME: How can the lookup succeed ?
3482                 if (!g_hash_table_lookup (domain_jit_info (domain)->seq_points, cfg->method_to_register))
3483                         g_hash_table_insert (domain_jit_info (domain)->seq_points, cfg->method_to_register, info);
3484                 mono_domain_unlock (domain);
3485         }
3486
3487         g_ptr_array_free (cfg->seq_points, TRUE);
3488         cfg->seq_points = NULL;
3489 }
3490
3491 void
3492 mono_codegen (MonoCompile *cfg)
3493 {
3494         MonoBasicBlock *bb;
3495         int max_epilog_size;
3496         guint8 *code;
3497
3498 #if defined(__native_client_codegen__) && defined(__native_client__)
3499         void *code_dest;
3500
3501         /* This keeps patch targets from being transformed during
3502          * ordinary method compilation, for local branches and jumps.
3503          */
3504         nacl_allow_target_modification (FALSE);
3505 #endif
3506
3507         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3508                 cfg->spill_count = 0;
3509                 /* we reuse dfn here */
3510                 /* bb->dfn = bb_count++; */
3511
3512                 mono_arch_lowering_pass (cfg, bb);
3513
3514                 if (cfg->opt & MONO_OPT_PEEPHOLE)
3515                         mono_arch_peephole_pass_1 (cfg, bb);
3516
3517                 if (!cfg->globalra)
3518                         mono_local_regalloc (cfg, bb);
3519
3520                 if (cfg->opt & MONO_OPT_PEEPHOLE)
3521                         mono_arch_peephole_pass_2 (cfg, bb);
3522         }
3523
3524         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
3525                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
3526
3527         code = mono_arch_emit_prolog (cfg);
3528
3529         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3530                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
3531
3532         cfg->code_len = code - cfg->native_code;
3533         cfg->prolog_end = cfg->code_len;
3534
3535         mono_debug_open_method (cfg);
3536
3537         /* emit code all basic blocks */
3538         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3539                 bb->native_offset = cfg->code_len;
3540                 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
3541                         mono_arch_output_basic_block (cfg, bb);
3542                 bb->native_length = cfg->code_len - bb->native_offset;
3543
3544                 if (bb == cfg->bb_exit) {
3545                         cfg->epilog_begin = cfg->code_len;
3546
3547                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
3548                                 code = cfg->native_code + cfg->code_len;
3549                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
3550                                 cfg->code_len = code - cfg->native_code;
3551                                 g_assert (cfg->code_len < cfg->code_size);
3552                         }
3553
3554                         mono_arch_emit_epilog (cfg);
3555                 }
3556         }
3557
3558 #ifdef __native_client_codegen__
3559         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
3560 #endif
3561         mono_arch_emit_exceptions (cfg);
3562
3563         max_epilog_size = 0;
3564
3565         code = cfg->native_code + cfg->code_len;
3566
3567         /* we always allocate code in cfg->domain->code_mp to increase locality */
3568         cfg->code_size = cfg->code_len + max_epilog_size;
3569         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
3570
3571         if (cfg->method->dynamic) {
3572                 guint unwindlen = 0;
3573 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3574                 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
3575 #endif
3576                 /* Allocate the code into a separate memory pool so it can be freed */
3577                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
3578                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
3579                 mono_domain_lock (cfg->domain);
3580                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
3581                 mono_domain_unlock (cfg->domain);
3582
3583                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + unwindlen);
3584         } else {
3585                 guint unwindlen = 0;
3586 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3587                 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
3588 #endif
3589                 code = mono_domain_code_reserve (cfg->domain, cfg->code_size + unwindlen);
3590         }
3591 #if defined(__native_client_codegen__) && defined(__native_client__)
3592         nacl_allow_target_modification (TRUE);
3593 #endif
3594
3595         memcpy (code, cfg->native_code, cfg->code_len);
3596 #if defined(__default_codegen__)
3597         g_free (cfg->native_code);
3598 #elif defined(__native_client_codegen__)
3599         if (cfg->native_code_alloc) {
3600                 g_free (cfg->native_code_alloc);
3601                 cfg->native_code_alloc = 0;
3602         }
3603         else if (cfg->native_code) {
3604                 g_free (cfg->native_code);
3605         }
3606 #endif /* __native_client_codegen__ */
3607         cfg->native_code = code;
3608         code = cfg->native_code + cfg->code_len;
3609   
3610         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
3611         mono_postprocess_patches (cfg);
3612
3613 #ifdef VALGRIND_JIT_REGISTER_MAP
3614 if (valgrind_register){
3615                 char* nm = mono_method_full_name (cfg->method, TRUE);
3616                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
3617                 g_free (nm);
3618         }
3619 #endif
3620  
3621         if (cfg->verbose_level > 0) {
3622                 char* nm = mono_method_full_name (cfg->method, TRUE);
3623                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
3624                                  nm, 
3625                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3626                 g_free (nm);
3627         }
3628
3629         {
3630                 gboolean is_generic = FALSE;
3631
3632                 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
3633                                 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
3634                         is_generic = TRUE;
3635                 }
3636
3637                 if (cfg->generic_sharing_context)
3638                         g_assert (is_generic);
3639         }
3640
3641 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
3642         mono_arch_save_unwind_info (cfg);
3643 #endif
3644
3645 #if defined(__native_client_codegen__) && defined(__native_client__)
3646         if (!cfg->compile_aot) {
3647                 if (cfg->method->dynamic) {
3648                         code_dest = nacl_code_manager_get_code_dest(cfg->dynamic_info->code_mp, cfg->native_code);
3649                 } else {
3650                         code_dest = nacl_domain_get_code_dest(cfg->domain, cfg->native_code);
3651                 }
3652         }
3653 #endif
3654
3655 #if defined(__native_client_codegen__)
3656         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
3657 #endif
3658
3659         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
3660
3661         if (cfg->method->dynamic) {
3662                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
3663         } else {
3664                 mono_domain_code_commit (cfg->domain, cfg->native_code, cfg->code_size, cfg->code_len);
3665         }
3666 #if defined(__native_client_codegen__) && defined(__native_client__)
3667         cfg->native_code = code_dest;
3668 #endif
3669         mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
3670         
3671         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
3672
3673         mono_debug_close_method (cfg);
3674
3675 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3676         mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
3677 #endif
3678 }
3679
3680 static void
3681 compute_reachable (MonoBasicBlock *bb)
3682 {
3683         int i;
3684
3685         if (!(bb->flags & BB_VISITED)) {
3686                 bb->flags |= BB_VISITED;
3687                 for (i = 0; i < bb->out_count; ++i)
3688                         compute_reachable (bb->out_bb [i]);
3689         }
3690 }
3691
3692 static void
3693 mono_handle_out_of_line_bblock (MonoCompile *cfg)
3694 {
3695         MonoBasicBlock *bb;
3696         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3697                 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
3698                         MonoInst *ins;
3699                         MONO_INST_NEW (cfg, ins, OP_BR);
3700                         MONO_ADD_INS (bb, ins);
3701                         ins->inst_target_bb = bb->next_bb;
3702                 }
3703         }
3704 }
3705
3706 static MonoJitInfo*
3707 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
3708 {
3709         GSList *tmp;
3710         MonoMethodHeader *header;
3711         MonoJitInfo *jinfo;
3712         int num_clauses;
3713         int generic_info_size;
3714         int holes_size = 0, num_holes = 0;
3715
3716         g_assert (method_to_compile == cfg->method);
3717         header = cfg->header;
3718
3719         if (cfg->generic_sharing_context)
3720                 generic_info_size = sizeof (MonoGenericJitInfo);
3721         else
3722                 generic_info_size = 0;
3723
3724         if (cfg->try_block_holes) {
3725                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3726                         TryBlockHole *hole = tmp->data;
3727                         MonoExceptionClause *ec = hole->clause;
3728                         int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
3729                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3730                         g_assert (clause_last_bb);
3731
3732                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
3733                         if (clause_last_bb->native_offset != hole_end)
3734                                 ++num_holes;
3735                 }
3736                 if (num_holes)
3737                         holes_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
3738                 if (G_UNLIKELY (cfg->verbose_level >= 4))
3739                         printf ("Number of try block holes %d\n", num_holes);
3740         }
3741
3742         if (COMPILE_LLVM (cfg))
3743                 num_clauses = cfg->llvm_ex_info_len;
3744         else
3745                 num_clauses = header->num_clauses;
3746
3747         if (cfg->method->dynamic) {
3748                 jinfo = g_malloc0 (MONO_SIZEOF_JIT_INFO + (num_clauses * sizeof (MonoJitExceptionInfo)) +
3749                                 generic_info_size + holes_size);
3750         } else {
3751                 jinfo = mono_domain_alloc0 (cfg->domain, MONO_SIZEOF_JIT_INFO +
3752                                 (num_clauses * sizeof (MonoJitExceptionInfo)) +
3753                                 generic_info_size + holes_size);
3754         }
3755
3756         jinfo->method = cfg->method_to_register;
3757         jinfo->code_start = cfg->native_code;
3758         jinfo->code_size = cfg->code_len;
3759         jinfo->used_regs = cfg->used_int_regs;
3760         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
3761         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
3762         jinfo->num_clauses = num_clauses;
3763         if (COMPILE_LLVM (cfg))
3764                 jinfo->from_llvm = TRUE;
3765
3766         if (cfg->generic_sharing_context) {
3767                 MonoInst *inst;
3768                 MonoGenericJitInfo *gi;
3769
3770                 jinfo->has_generic_jit_info = 1;
3771
3772                 gi = mono_jit_info_get_generic_jit_info (jinfo);
3773                 g_assert (gi);
3774
3775                 gi->generic_sharing_context = cfg->generic_sharing_context;
3776
3777                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
3778                                 mini_method_get_context (method_to_compile)->method_inst ||
3779                                 method_to_compile->klass->valuetype) {
3780                         g_assert (cfg->rgctx_var);
3781                 }
3782
3783                 gi->has_this = 1;
3784
3785                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
3786                                 mini_method_get_context (method_to_compile)->method_inst ||
3787                                 method_to_compile->klass->valuetype) {
3788                         inst = cfg->rgctx_var;
3789                         if (!COMPILE_LLVM (cfg))
3790                                 g_assert (inst->opcode == OP_REGOFFSET);
3791                 } else {
3792                         inst = cfg->args [0];
3793                 }
3794
3795                 if (COMPILE_LLVM (cfg)) {
3796                         g_assert (cfg->llvm_this_reg != -1);
3797                         gi->this_in_reg = 0;
3798                         gi->this_reg = cfg->llvm_this_reg;
3799                         gi->this_offset = cfg->llvm_this_offset;
3800                 } else if (inst->opcode == OP_REGVAR) {
3801                         gi->this_in_reg = 1;
3802                         gi->this_reg = inst->dreg;
3803                 } else {
3804                         g_assert (inst->opcode == OP_REGOFFSET);
3805 #ifdef TARGET_X86
3806                         g_assert (inst->inst_basereg == X86_EBP);
3807 #elif defined(TARGET_AMD64)
3808                         g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
3809 #endif
3810                         g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
3811
3812                         gi->this_in_reg = 0;
3813                         gi->this_reg = inst->inst_basereg;
3814                         gi->this_offset = inst->inst_offset;
3815                 }
3816         }
3817
3818         if (num_holes) {
3819                 MonoTryBlockHoleTableJitInfo *table;
3820                 int i;
3821
3822                 jinfo->has_try_block_holes = 1;
3823                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3824                 table->num_holes = (guint16)num_holes;
3825                 i = 0;
3826                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3827                         guint32 start_bb_offset;
3828                         MonoTryBlockHoleJitInfo *hole;
3829                         TryBlockHole *hole_data = tmp->data;
3830                         MonoExceptionClause *ec = hole_data->clause;
3831                         int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
3832                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3833                         g_assert (clause_last_bb);
3834
3835                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
3836                         if (clause_last_bb->native_offset == hole_end)
3837                                 continue;
3838
3839                         start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
3840                         hole = &table->holes [i++];
3841                         hole->clause = hole_data->clause - &header->clauses [0];
3842                         hole->offset = (guint32)hole_data->start_offset;
3843                         hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
3844
3845                         if (G_UNLIKELY (cfg->verbose_level >= 4))
3846                                 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
3847                 }
3848                 g_assert (i == num_holes);
3849         }
3850
3851         if (COMPILE_LLVM (cfg)) {
3852                 if (num_clauses)
3853                         memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
3854         } else if (header->num_clauses) {
3855                 int i;
3856
3857                 for (i = 0; i < header->num_clauses; i++) {
3858                         MonoExceptionClause *ec = &header->clauses [i];
3859                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3860                         MonoBasicBlock *tblock;
3861                         MonoInst *exvar;
3862
3863                         ei->flags = ec->flags;
3864
3865                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
3866                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
3867
3868                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3869                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
3870                                 g_assert (tblock);
3871                                 ei->data.filter = cfg->native_code + tblock->native_offset;
3872                         } else {
3873                                 ei->data.catch_class = ec->data.catch_class;
3874                         }
3875
3876                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
3877                         g_assert (tblock);
3878                         g_assert (tblock->native_offset);
3879                         ei->try_start = cfg->native_code + tblock->native_offset;
3880                         if (tblock->extend_try_block) {
3881                                 /*
3882                                  * Extend the try block backwards to include parts of the previous call
3883                                  * instruction.
3884                                  * FIXME: This is arch specific.
3885                                  */
3886                                 ei->try_start = (guint8*)ei->try_start - 1;
3887                         }
3888                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3889                         g_assert (tblock);
3890                         if (!tblock->native_offset) {
3891                                 int j, end;
3892                                 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
3893                                         MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
3894                                         if (bb && bb->native_offset) {
3895                                                 tblock = bb;
3896                                                 break;
3897                                         }
3898                                 }
3899                         }
3900                         ei->try_end = cfg->native_code + tblock->native_offset;
3901                         g_assert (tblock->native_offset);
3902                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
3903                         g_assert (tblock);
3904                         ei->handler_start = cfg->native_code + tblock->native_offset;
3905
3906                         for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3907                                 TryBlockHole *hole = tmp->data;
3908                                 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
3909                                 if (hole->clause == ec && hole_end == ei->try_end) {
3910                                         if (G_UNLIKELY (cfg->verbose_level >= 4))
3911                                                 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
3912
3913                                         ei->try_end = cfg->native_code + hole->start_offset;
3914                                         break;
3915                                 }
3916                         }
3917
3918                         if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
3919                                 int end_offset;
3920                                 if (ec->handler_offset + ec->handler_len < header->code_size) {
3921                                         tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
3922                                         g_assert (tblock);
3923                                         end_offset = tblock->native_offset;
3924                                 } else {
3925                                         end_offset = cfg->epilog_begin;
3926                                 }
3927                                 ei->data.handler_end = cfg->native_code + end_offset;
3928                         }
3929                 }
3930         }
3931
3932         if (G_UNLIKELY (cfg->verbose_level >= 4)) {
3933                 int i;
3934                 for (i = 0; i < jinfo->num_clauses; i++) {
3935                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3936                         int start = (guint8*)ei->try_start - cfg->native_code;
3937                         int end = (guint8*)ei->try_end - cfg->native_code;
3938                         int handler = (guint8*)ei->handler_start - cfg->native_code;
3939
3940                         printf ("JitInfo EH clause %d flags %x try %x-%x handler %x\n", i, ei->flags, start, end, handler);
3941                 }
3942         }
3943
3944         /* 
3945          * Its possible to generate dwarf unwind info for xdebug etc, but not actually
3946          * using it during runtime, hence the define.
3947          */
3948 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3949         if (cfg->encoded_unwind_ops) {
3950                 jinfo->used_regs = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
3951                 g_free (cfg->encoded_unwind_ops);
3952         } else if (cfg->unwind_ops) {
3953                 guint32 info_len;
3954                 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
3955
3956                 jinfo->used_regs = mono_cache_unwind_info (unwind_info, info_len);
3957                 g_free (unwind_info);
3958         }
3959 #endif
3960
3961         return jinfo;
3962 }
3963 #endif
3964
3965 /*
3966  * mini_get_shared_method:
3967  *
3968  *   Return the method which is actually compiled/registered when doing generic sharing.
3969  */
3970 MonoMethod*
3971 mini_get_shared_method (MonoMethod *method)
3972 {
3973         MonoGenericContext shared_context;
3974         MonoMethod *declaring_method, *res;
3975         int i;
3976         gboolean partial = FALSE;
3977
3978         if (method->is_generic || method->klass->generic_container)
3979                 declaring_method = method;
3980         else
3981                 declaring_method = mono_method_get_declaring_generic_method (method);
3982
3983         if (declaring_method->is_generic)
3984                 shared_context = mono_method_get_generic_container (declaring_method)->context;
3985         else
3986                 shared_context = declaring_method->klass->generic_container->context;
3987
3988         /* Handle partial sharing */
3989         if (method != declaring_method && method->is_inflated && !mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
3990                 MonoGenericContext *context = mono_method_get_context (method);
3991                 MonoGenericInst *inst;
3992                 MonoType **type_argv;
3993
3994                 /* 
3995                  * Create the shared context by replacing the ref type arguments with
3996                  * type parameters, and keeping the rest.
3997                  */
3998                 partial = TRUE;
3999                 inst = context->class_inst;
4000                 if (inst) {
4001                         type_argv = g_new0 (MonoType*, inst->type_argc);
4002                         for (i = 0; i < inst->type_argc; ++i) {
4003                                 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4004                                         type_argv [i] = shared_context.class_inst->type_argv [i];
4005                                 else
4006                                         type_argv [i] = inst->type_argv [i];
4007                         }
4008
4009                         shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4010                         g_free (type_argv);
4011                 }
4012
4013                 inst = context->method_inst;
4014                 if (inst) {
4015                         type_argv = g_new0 (MonoType*, inst->type_argc);
4016                         for (i = 0; i < inst->type_argc; ++i) {
4017                                 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4018                                         type_argv [i] = shared_context.method_inst->type_argv [i];
4019                                 else
4020                                         type_argv [i] = inst->type_argv [i];
4021                         }
4022
4023                         shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4024                         g_free (type_argv);
4025                 }
4026         }
4027
4028     res = mono_class_inflate_generic_method (declaring_method, &shared_context);
4029         if (!partial) {
4030                 /* The result should be an inflated method whose parent is not inflated */
4031                 g_assert (!res->klass->is_inflated);
4032         }
4033         return res;
4034 }
4035
4036 #ifndef DISABLE_JIT
4037 /*
4038  * mini_method_compile:
4039  * @method: the method to compile
4040  * @opts: the optimization flags to use
4041  * @domain: the domain where the method will be compiled in
4042  * @run_cctors: whether we should run type ctors if possible
4043  * @compile_aot: whether this is an AOT compilation
4044  * @parts: debug flag
4045  *
4046  * Returns: a MonoCompile* pointer. Caller must check the exception_type
4047  * field in the returned struct to see if compilation succeded.
4048  */
4049 MonoCompile*
4050 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
4051 {
4052         MonoMethodHeader *header;
4053         MonoMethodSignature *sig;
4054         MonoError err;
4055         guint8 *ip;
4056         MonoCompile *cfg;
4057         int dfn, i, code_size_ratio;
4058         gboolean deadce_has_run = FALSE;
4059         gboolean try_generic_shared, try_llvm = FALSE;
4060         MonoMethod *method_to_compile, *method_to_register;
4061
4062         mono_jit_stats.methods_compiled++;
4063         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
4064                 mono_profiler_method_jit (method);
4065         if (MONO_PROBE_METHOD_COMPILE_BEGIN_ENABLED ())
4066                 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
4067
4068         if (compile_aot)
4069                 /* 
4070                  * We might get passed the original generic method definition or
4071                  * instances with type parameters.
4072                  * FIXME: Remove the method->klass->generic_class limitation.
4073                  */
4074                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
4075                         (opts & MONO_OPT_GSHARED) && ((method->is_generic || method->klass->generic_container) || (!method->klass->generic_class && mono_method_is_generic_sharable_impl (method, TRUE)));
4076         else
4077                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
4078                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method, FALSE);
4079
4080         if (opts & MONO_OPT_GSHARED) {
4081                 if (try_generic_shared)
4082                         mono_stats.generics_sharable_methods++;
4083                 else if (mono_method_is_generic_impl (method))
4084                         mono_stats.generics_unsharable_methods++;
4085         }
4086
4087 #ifdef ENABLE_LLVM
4088         try_llvm = mono_use_llvm;
4089 #endif
4090
4091  restart_compile:
4092         if (try_generic_shared) {
4093                 method_to_compile = mini_get_shared_method (method);
4094                 g_assert (method_to_compile);
4095         } else {
4096                 method_to_compile = method;
4097         }
4098
4099         cfg = g_new0 (MonoCompile, 1);
4100         cfg->method = method_to_compile;
4101         cfg->header = mono_method_get_header (cfg->method);
4102         cfg->mempool = mono_mempool_new ();
4103         cfg->opt = opts;
4104         cfg->prof_options = mono_profiler_get_events ();
4105         cfg->run_cctors = run_cctors;
4106         cfg->domain = domain;
4107         cfg->verbose_level = mini_verbose;
4108         cfg->compile_aot = compile_aot;
4109         cfg->skip_visibility = method->skip_visibility;
4110         cfg->orig_method = method;
4111         cfg->gen_seq_points = debug_options.gen_seq_points;
4112         cfg->explicit_null_checks = debug_options.explicit_null_checks;
4113         if (try_generic_shared)
4114                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
4115         cfg->compile_llvm = try_llvm;
4116         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
4117
4118         if (cfg->gen_seq_points)
4119                 cfg->seq_points = g_ptr_array_new ();
4120
4121         if (cfg->compile_aot && !try_generic_shared && (method->is_generic || method->klass->generic_container)) {
4122                 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
4123                 return cfg;
4124         }
4125
4126         if (cfg->generic_sharing_context) {
4127                 method_to_register = method_to_compile;
4128         } else {
4129                 g_assert (method == method_to_compile);
4130                 method_to_register = method;
4131         }
4132         cfg->method_to_register = method_to_register;
4133
4134         mono_error_init (&err);
4135         sig = mono_method_signature_checked (cfg->method, &err);        
4136         if (!sig) {
4137                 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
4138                 cfg->exception_message = g_strdup (mono_error_get_message (&err));
4139                 mono_error_cleanup (&err);
4140                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4141                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4142                 return cfg;
4143         }
4144
4145         header = cfg->header;
4146         if (!header) {
4147                 MonoLoaderError *error;
4148
4149                 if ((error = mono_loader_get_last_error ())) {
4150                         cfg->exception_type = error->exception_type;
4151                 } else {
4152                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4153                         cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
4154                 }
4155                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4156                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4157                 return cfg;
4158         }
4159
4160 #ifdef ENABLE_LLVM
4161         {
4162                 static gboolean inited;
4163
4164                 if (!inited) {
4165                         inited = TRUE;
4166                 }
4167
4168                 /* 
4169                  * Check for methods which cannot be compiled by LLVM early, to avoid
4170                  * the extra compilation pass.
4171                  */
4172                 if (COMPILE_LLVM (cfg)) {
4173                         mono_llvm_check_method_supported (cfg);
4174                         if (cfg->disable_llvm) {
4175                                 if (cfg->verbose_level >= 1) {
4176                                         //nm = mono_method_full_name (cfg->method, TRUE);
4177                                         printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
4178                                         //g_free (nm);
4179                                 }
4180                                 mono_destroy_compile (cfg);
4181                                 try_llvm = FALSE;
4182                                 goto restart_compile;
4183                         }
4184                 }
4185         }
4186 #endif
4187
4188         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
4189         if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
4190                 cfg->disable_reuse_registers = TRUE;
4191                 cfg->disable_reuse_stack_slots = TRUE;
4192                 /* 
4193                  * This decreases the change the debugger will read registers/stack slots which are
4194                  * not yet initialized.
4195                  */
4196                 cfg->disable_initlocals_opt = TRUE;
4197
4198                 cfg->extend_live_ranges = TRUE;
4199
4200                 /* Temporarily disable this when running in the debugger until we have support
4201                  * for this in the debugger. */
4202                 cfg->disable_omit_fp = TRUE;
4203
4204                 /* The debugger needs all locals to be on the stack or in a global register */
4205                 cfg->disable_vreg_to_lvreg = TRUE;
4206
4207                 /* Don't remove unused variables when running inside the debugger since the user
4208                  * may still want to view them. */
4209                 cfg->disable_deadce_vars = TRUE;
4210
4211                 // cfg->opt |= MONO_OPT_SHARED;
4212                 cfg->opt &= ~MONO_OPT_DEADCE;
4213                 cfg->opt &= ~MONO_OPT_INLINE;
4214                 cfg->opt &= ~MONO_OPT_COPYPROP;
4215                 cfg->opt &= ~MONO_OPT_CONSPROP;
4216                 cfg->opt &= ~MONO_OPT_GSHARED;
4217
4218                 /* This is needed for the soft debugger, which doesn't like code after the epilog */
4219                 cfg->disable_out_of_line_bblocks = TRUE;
4220         }
4221
4222         if (mono_using_xdebug) {
4223                 /* 
4224                  * Make each variable use its own register/stack slot and extend 
4225                  * their liveness to cover the whole method, making them displayable
4226                  * in gdb even after they are dead.
4227                  */
4228                 cfg->disable_reuse_registers = TRUE;
4229                 cfg->disable_reuse_stack_slots = TRUE;
4230                 cfg->extend_live_ranges = TRUE;
4231                 cfg->compute_precise_live_ranges = TRUE;
4232         }
4233
4234         mini_gc_init_cfg (cfg);
4235
4236         if (COMPILE_LLVM (cfg)) {
4237                 cfg->opt |= MONO_OPT_ABCREM;
4238         }
4239
4240         if (getenv ("MONO_VERBOSE_METHOD")) {
4241                 char *name = getenv ("MONO_VERBOSE_METHOD");
4242
4243                 if ((strchr (name, '.') > name) || strchr (name, ':')) {
4244                         MonoMethodDesc *desc;
4245                         
4246                         desc = mono_method_desc_new (name, TRUE);
4247                         if (mono_method_desc_full_match (desc, cfg->method)) {
4248                                 cfg->verbose_level = 4;
4249                         }
4250                         mono_method_desc_free (desc);
4251                 } else {
4252                         if (strcmp (cfg->method->name, getenv ("MONO_VERBOSE_METHOD")) == 0)
4253                                 cfg->verbose_level = 4;
4254                 }
4255         }
4256
4257         ip = (guint8 *)header->code;
4258
4259         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
4260
4261         if (cfg->verbose_level > 0) {
4262                 char *method_name;
4263                 if (COMPILE_LLVM (cfg))
4264                         g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
4265                 else if (cfg->generic_sharing_context)
4266                         g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
4267                 else
4268                         g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
4269                 g_free (method_name);
4270         }
4271
4272         if (cfg->opt & (MONO_OPT_ABCREM | MONO_OPT_SSAPRE))
4273                 cfg->opt |= MONO_OPT_SSA;
4274
4275         /* 
4276         if ((cfg->method->klass->image != mono_defaults.corlib) || (strstr (cfg->method->klass->name, "StackOverflowException") && strstr (cfg->method->name, ".ctor")) || (strstr (cfg->method->klass->name, "OutOfMemoryException") && strstr (cfg->method->name, ".ctor")))
4277                 cfg->globalra = TRUE;
4278         */
4279
4280         //cfg->globalra = TRUE;
4281
4282         //if (!strcmp (cfg->method->klass->name, "Tests") && !cfg->method->wrapper_type)
4283         //      cfg->globalra = TRUE;
4284
4285         {
4286                 static int count = 0;
4287                 count ++;
4288
4289                 /*
4290                 if (getenv ("COUNT2")) {
4291                         cfg->globalra = TRUE;
4292                         if (count == atoi (getenv ("COUNT2")))
4293                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4294                         if (count > atoi (getenv ("COUNT2")))
4295                                 cfg->globalra = FALSE;
4296                 }
4297                 */
4298         }
4299
4300         if (header->clauses)
4301                 cfg->globalra = FALSE;
4302
4303         if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
4304                 /* The code in the prolog clobbers caller saved registers */
4305                 cfg->globalra = FALSE;
4306
4307         // FIXME: Disable globalra in case of tracing/profiling
4308
4309         if (cfg->method->save_lmf)
4310                 /* The LMF saving code might clobber caller saved registers */
4311                 cfg->globalra = FALSE;
4312
4313         if (header->code_size > 5000)
4314                 // FIXME:
4315                 /* Too large bblocks could overflow the ins positions */
4316                 cfg->globalra = FALSE;
4317
4318         cfg->rs = mono_regstate_new ();
4319         if (cfg->globalra)
4320                 cfg->rs->next_vreg = MONO_MAX_IREGS + MONO_MAX_FREGS;
4321         cfg->next_vreg = cfg->rs->next_vreg;
4322
4323         /* FIXME: Fix SSA to handle branches inside bblocks */
4324         if (cfg->opt & MONO_OPT_SSA)
4325                 cfg->enable_extended_bblocks = FALSE;
4326
4327         /*
4328          * FIXME: This confuses liveness analysis because variables which are assigned after
4329          * a branch inside a bblock become part of the kill set, even though the assignment
4330          * might not get executed. This causes the optimize_initlocals pass to delete some
4331          * assignments which are needed.
4332          * Also, the mono_if_conversion pass needs to be modified to recognize the code
4333          * created by this.
4334          */
4335         //cfg->enable_extended_bblocks = TRUE;
4336
4337         /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
4338         if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
4339                 if (mini_get_debug_options ()->break_on_unverified)
4340                         G_BREAKPOINT ();
4341                 return cfg;
4342         }
4343
4344         /*
4345          * create MonoInst* which represents arguments and local variables
4346          */
4347         mono_compile_create_vars (cfg);
4348
4349         /* SSAPRE is not supported on linear IR */
4350         cfg->opt &= ~MONO_OPT_SSAPRE;
4351
4352         i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, NULL, 0, FALSE);
4353
4354         if (i < 0) {
4355                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4356                         if (compile_aot) {
4357                                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4358                                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4359                                 return cfg;
4360                         }
4361                         mono_destroy_compile (cfg);
4362                         try_generic_shared = FALSE;
4363                         goto restart_compile;
4364                 }
4365                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
4366
4367                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4368                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4369                 /* cfg contains the details of the failure, so let the caller cleanup */
4370                 return cfg;
4371         }
4372
4373         mono_jit_stats.basic_blocks += cfg->num_bblocks;
4374         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
4375
4376         if (COMPILE_LLVM (cfg)) {
4377                 MonoInst *ins;
4378
4379                 /* The IR has to be in SSA form for LLVM */
4380                 cfg->opt |= MONO_OPT_SSA;
4381
4382                 // FIXME:
4383                 if (cfg->ret) {
4384                         // Allow SSA on the result value
4385                         cfg->ret->flags &= ~MONO_INST_VOLATILE;
4386
4387                         // Add an explicit return instruction referencing the return value
4388                         MONO_INST_NEW (cfg, ins, OP_SETRET);
4389                         ins->sreg1 = cfg->ret->dreg;
4390
4391                         MONO_ADD_INS (cfg->bb_exit, ins);
4392                 }
4393
4394                 cfg->opt &= ~MONO_OPT_LINEARS;
4395
4396                 /* FIXME: */
4397                 cfg->opt &= ~MONO_OPT_BRANCH;
4398         }
4399
4400         /* todo: remove code when we have verified that the liveness for try/catch blocks
4401          * works perfectly 
4402          */
4403         /* 
4404          * Currently, this can't be commented out since exception blocks are not
4405          * processed during liveness analysis.
4406          * It is also needed, because otherwise the local optimization passes would
4407          * delete assignments in cases like this:
4408          * r1 <- 1
4409          * <something which throws>
4410          * r1 <- 2
4411          * This also allows SSA to be run on methods containing exception clauses, since
4412          * SSA will ignore variables marked VOLATILE.
4413          */
4414         mono_liveness_handle_exception_clauses (cfg);
4415
4416         mono_handle_out_of_line_bblock (cfg);
4417
4418         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
4419
4420         if (!COMPILE_LLVM (cfg))
4421                 mono_decompose_long_opts (cfg);
4422
4423         /* Should be done before branch opts */
4424         if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
4425                 mono_local_cprop (cfg);
4426
4427         if (cfg->opt & MONO_OPT_BRANCH)
4428                 mono_optimize_branches (cfg);
4429
4430         /* This must be done _before_ global reg alloc and _after_ decompose */
4431         mono_handle_global_vregs (cfg);
4432         if (cfg->opt & MONO_OPT_DEADCE)
4433                 mono_local_deadce (cfg);
4434         /* Disable this for LLVM to make the IR easier to handle */
4435         if (!COMPILE_LLVM (cfg))
4436                 mono_if_conversion (cfg);
4437
4438         if ((cfg->opt & MONO_OPT_SSAPRE) || cfg->globalra)
4439                 mono_remove_critical_edges (cfg);
4440
4441         /* Depth-first ordering on basic blocks */
4442         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
4443
4444         cfg->max_block_num = cfg->num_bblocks;
4445
4446         dfn = 0;
4447         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
4448         if (cfg->num_bblocks != dfn + 1) {
4449                 MonoBasicBlock *bb;
4450
4451                 cfg->num_bblocks = dfn + 1;
4452
4453                 /* remove unreachable code, because the code in them may be 
4454                  * inconsistent  (access to dead variables for example) */
4455                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4456                         bb->flags &= ~BB_VISITED;
4457                 compute_reachable (cfg->bb_entry);
4458                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4459                         if (bb->flags & BB_EXCEPTION_HANDLER)
4460                                 compute_reachable (bb);
4461                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4462                         if (!(bb->flags & BB_VISITED)) {
4463                                 if (cfg->verbose_level > 1)
4464                                         g_print ("found unreachable code in BB%d\n", bb->block_num);
4465                                 bb->code = bb->last_ins = NULL;
4466                                 while (bb->out_count)
4467                                         mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
4468                         }
4469                 }
4470                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4471                         bb->flags &= ~BB_VISITED;
4472         }
4473
4474         if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
4475                 /* 
4476                  * we disable some optimizations if there are too many variables
4477                  * because JIT time may become too expensive. The actual number needs 
4478                  * to be tweaked and eventually the non-linear algorithms should be fixed.
4479                  */
4480                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
4481                 cfg->disable_ssa = TRUE;
4482         }
4483
4484         if (cfg->opt & MONO_OPT_LOOP) {
4485                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
4486                 mono_compute_natural_loops (cfg);
4487         }
4488
4489         /* after method_to_ir */
4490         if (parts == 1) {
4491                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4492                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4493                 return cfg;
4494         }
4495
4496         /*
4497           if (header->num_clauses)
4498           cfg->disable_ssa = TRUE;
4499         */
4500
4501 //#define DEBUGSSA "logic_run"
4502 #define DEBUGSSA_CLASS "Tests"
4503 #ifdef DEBUGSSA
4504
4505         if (!cfg->disable_ssa) {
4506                 mono_local_cprop (cfg);
4507
4508 #ifndef DISABLE_SSA
4509                 mono_ssa_compute (cfg);
4510 #endif
4511         }
4512 #else 
4513         if (cfg->opt & MONO_OPT_SSA) {
4514                 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
4515 #ifndef DISABLE_SSA
4516                         mono_ssa_compute (cfg);
4517 #endif
4518
4519                         if (cfg->verbose_level >= 2) {
4520                                 print_dfn (cfg);
4521                         }
4522                 }
4523         }
4524 #endif
4525
4526         /* after SSA translation */
4527         if (parts == 2) {
4528                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4529                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4530                 return cfg;
4531         }
4532
4533         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
4534                 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
4535 #ifndef DISABLE_SSA
4536                         mono_ssa_cprop (cfg);
4537 #endif
4538                 }
4539         }
4540
4541 #ifndef DISABLE_SSA
4542         if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
4543                 //mono_ssa_strength_reduction (cfg);
4544
4545                 if (cfg->opt & MONO_OPT_SSAPRE) {
4546                         mono_perform_ssapre (cfg);
4547                         //mono_local_cprop (cfg);
4548                 }
4549
4550                 if (cfg->opt & MONO_OPT_DEADCE) {
4551                         mono_ssa_deadce (cfg);
4552                         deadce_has_run = TRUE;
4553                 }
4554
4555                 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM))
4556                         mono_perform_abc_removal (cfg);
4557
4558                 mono_ssa_remove (cfg);
4559                 mono_local_cprop (cfg);
4560                 mono_handle_global_vregs (cfg);
4561                 if (cfg->opt & MONO_OPT_DEADCE)
4562                         mono_local_deadce (cfg);
4563
4564                 if (cfg->opt & MONO_OPT_BRANCH) {
4565                         MonoBasicBlock *bb;
4566
4567                         mono_optimize_branches (cfg);
4568
4569                         /* Have to recompute cfg->bblocks and bb->dfn */
4570                         if (cfg->globalra) {
4571                                 mono_remove_critical_edges (cfg);
4572
4573                                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4574                                         bb->dfn = 0;
4575
4576                                 /* Depth-first ordering on basic blocks */
4577                                 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
4578
4579                                 dfn = 0;
4580                                 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
4581                                 cfg->num_bblocks = dfn + 1;
4582                         }
4583                 }
4584         }
4585 #endif
4586
4587         if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
4588                 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
4589                 if (cfg->opt & MONO_OPT_ABCREM)
4590                         mono_perform_abc_removal (cfg);
4591         }
4592
4593         /* after SSA removal */
4594         if (parts == 3) {
4595                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4596                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4597                 return cfg;
4598         }
4599
4600 #ifdef MONO_ARCH_SOFT_FLOAT
4601         if (!COMPILE_LLVM (cfg))
4602                 mono_decompose_soft_float (cfg);
4603 #endif
4604         if (!COMPILE_LLVM (cfg))
4605                 mono_decompose_vtype_opts (cfg);
4606         if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
4607                 mono_decompose_array_access_opts (cfg);
4608
4609         if (cfg->got_var) {
4610 #ifndef MONO_ARCH_GOT_REG
4611                 GList *regs;
4612 #endif
4613                 int got_reg;
4614
4615                 g_assert (cfg->got_var_allocated);
4616
4617                 /* 
4618                  * Allways allocate the GOT var to a register, because keeping it
4619                  * in memory will increase the number of live temporaries in some
4620                  * code created by inssel.brg, leading to the well known spills+
4621                  * branches problem. Testcase: mcs crash in 
4622                  * System.MonoCustomAttrs:GetCustomAttributes.
4623                  */
4624 #ifdef MONO_ARCH_GOT_REG
4625                 got_reg = MONO_ARCH_GOT_REG;
4626 #else
4627                 regs = mono_arch_get_global_int_regs (cfg);
4628                 g_assert (regs);
4629                 got_reg = GPOINTER_TO_INT (regs->data);
4630                 g_list_free (regs);
4631 #endif
4632                 cfg->got_var->opcode = OP_REGVAR;
4633                 cfg->got_var->dreg = got_reg;
4634                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
4635         }
4636
4637         /*
4638          * Have to call this again to process variables added since the first call.
4639          */
4640         mono_liveness_handle_exception_clauses (cfg);
4641
4642         if (cfg->globalra) {
4643                 MonoBasicBlock *bb;
4644
4645                 /* Have to do this before regalloc since it can create vregs */
4646                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4647                         mono_arch_lowering_pass (cfg, bb);
4648
4649                 mono_global_regalloc (cfg);
4650         }
4651
4652         if ((cfg->opt & MONO_OPT_LINEARS) && !cfg->globalra) {
4653                 GList *vars, *regs, *l;
4654                 
4655                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
4656                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
4657                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
4658                         mono_analyze_liveness (cfg);
4659
4660                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
4661                         regs = mono_arch_get_global_int_regs (cfg);
4662                         /* Remove the reg reserved for holding the GOT address */
4663                         if (cfg->got_var) {
4664                                 for (l = regs; l; l = l->next) {
4665                                         if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
4666                                                 regs = g_list_delete_link (regs, l);
4667                                                 break;
4668                                         }
4669                                 }
4670                         }
4671                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
4672                 }
4673         }
4674
4675         //mono_print_code (cfg, "");
4676
4677     //print_dfn (cfg);
4678         
4679         /* variables are allocated after decompose, since decompose could create temps */
4680         if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
4681                 mono_arch_allocate_vars (cfg);
4682                 if (cfg->exception_type)
4683                         return cfg;
4684         }
4685
4686         {
4687                 MonoBasicBlock *bb;
4688                 gboolean need_local_opts;
4689
4690                 if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
4691                         mono_spill_global_vars (cfg, &need_local_opts);
4692
4693                         if (need_local_opts || cfg->compile_aot) {
4694                                 /* To optimize code created by spill_global_vars */
4695                                 mono_local_cprop (cfg);
4696                                 if (cfg->opt & MONO_OPT_DEADCE)
4697                                         mono_local_deadce (cfg);
4698                         }
4699                 }
4700
4701                 /* Add branches between non-consecutive bblocks */
4702                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4703                         if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4704                                 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
4705                                 /* we are careful when inverting, since bugs like #59580
4706                                  * could show up when dealing with NaNs.
4707                                  */
4708                                 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
4709                                         MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
4710                                         bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
4711                                         bb->last_ins->inst_false_bb = tmp;
4712
4713                                         bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
4714                                 } else {                        
4715                                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4716                                         inst->opcode = OP_BR;
4717                                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
4718                                         mono_bblock_add_inst (bb, inst);
4719                                 }
4720                         }
4721                 }
4722
4723                 if (cfg->verbose_level >= 4 && !cfg->globalra) {
4724                         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4725                                 MonoInst *tree = bb->code;      
4726                                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
4727                                 if (!tree)
4728                                         continue;
4729                                 for (; tree; tree = tree->next) {
4730                                         mono_print_ins_index (-1, tree);
4731                                 }
4732                         }
4733                 }
4734
4735                 /* FIXME: */
4736                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4737                         bb->max_vreg = cfg->next_vreg;
4738                 }
4739         }
4740
4741         if (COMPILE_LLVM (cfg)) {
4742 #ifdef ENABLE_LLVM
4743                 char *nm;
4744
4745                 /* The IR has to be in SSA form for LLVM */
4746                 if (!(cfg->comp_done & MONO_COMP_SSA)) {
4747                         cfg->exception_message = g_strdup ("SSA disabled.");
4748                         cfg->disable_llvm = TRUE;
4749                 }
4750
4751                 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
4752                         mono_decompose_array_access_opts (cfg);
4753
4754                 if (!cfg->disable_llvm)
4755                         mono_llvm_emit_method (cfg);
4756                 if (cfg->disable_llvm) {
4757                         if (cfg->verbose_level >= 1) {
4758                                 //nm = mono_method_full_name (cfg->method, TRUE);
4759                                 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
4760                                 //g_free (nm);
4761                         }
4762                         mono_destroy_compile (cfg);
4763                         try_llvm = FALSE;
4764                         goto restart_compile;
4765                 }
4766
4767                 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
4768                         nm = mono_method_full_name (cfg->method, TRUE);
4769                         g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n", 
4770                                          nm, 
4771                                          cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
4772                         g_free (nm);
4773                 }
4774 #endif
4775         } else {
4776                 mono_codegen (cfg);
4777         }
4778
4779         if (COMPILE_LLVM (cfg))
4780                 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
4781         else
4782                 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
4783
4784         if (cfg->verbose_level >= 2) {
4785                 char *id =  mono_method_full_name (cfg->method, FALSE);
4786                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
4787                 g_free (id);
4788         }
4789
4790         cfg->jit_info = create_jit_info (cfg, method_to_compile);
4791
4792 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
4793         if (cfg->extend_live_ranges) {
4794                 /* Extend live ranges to cover the whole method */
4795                 for (i = 0; i < cfg->num_varinfo; ++i)
4796                         MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
4797         }
4798 #endif
4799
4800         if (!cfg->compile_aot)
4801                 mono_save_xdebug_info (cfg);
4802
4803         mini_gc_create_gc_map (cfg);
4804  
4805         mono_save_seq_point_info (cfg);
4806
4807         if (!cfg->compile_aot) {
4808                 mono_domain_lock (cfg->domain);
4809                 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
4810
4811                 if (cfg->method->dynamic)
4812                         mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
4813                 mono_domain_unlock (cfg->domain);
4814         }
4815
4816         /* collect statistics */
4817         mono_perfcounters->jit_methods++;
4818         mono_perfcounters->jit_bytes += header->code_size;
4819         mono_jit_stats.allocated_code_size += cfg->code_len;
4820         code_size_ratio = cfg->code_len;
4821         if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
4822                 mono_jit_stats.biggest_method_size = code_size_ratio;
4823                 g_free (mono_jit_stats.biggest_method);
4824                 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4825         }
4826         code_size_ratio = (code_size_ratio * 100) / header->code_size;
4827         if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
4828                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
4829                 g_free (mono_jit_stats.max_ratio_method);
4830                 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4831         }
4832         mono_jit_stats.native_code_size += cfg->code_len;
4833
4834         if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4835                 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4836
4837         return cfg;
4838 }
4839
4840 #else
4841
4842 MonoCompile*
4843 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
4844 {
4845         g_assert_not_reached ();
4846         return NULL;
4847 }
4848
4849 #endif /* DISABLE_JIT */
4850
4851 MonoJitInfo*
4852 mono_domain_lookup_shared_generic (MonoDomain *domain, MonoMethod *method)
4853 {
4854         static gboolean inited = FALSE;
4855         static int lookups = 0;
4856         static int failed_lookups = 0;
4857         MonoJitInfo *ji;
4858
4859         ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, mini_get_shared_method (method));
4860         if (ji && !ji->has_generic_jit_info)
4861                 ji = NULL;
4862
4863         if (!inited) {
4864                 mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
4865                 mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
4866                 inited = TRUE;
4867         }
4868
4869         ++lookups;
4870         if (!ji)
4871                 ++failed_lookups;
4872
4873         return ji;
4874 }
4875
4876 /*
4877  * LOCKING: Assumes domain->jit_code_hash_lock is held.
4878  */
4879 static MonoJitInfo*
4880 lookup_method_inner (MonoDomain *domain, MonoMethod *method)
4881 {
4882         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
4883
4884         if (ji)
4885                 return ji;
4886
4887         if (!mono_method_is_generic_sharable_impl (method, FALSE))
4888                 return NULL;
4889         return mono_domain_lookup_shared_generic (domain, method);
4890 }
4891
4892 static MonoJitInfo*
4893 lookup_method (MonoDomain *domain, MonoMethod *method)
4894 {
4895         MonoJitInfo *info;
4896
4897         mono_loader_lock (); /*FIXME lookup_method_inner acquired it*/
4898         mono_domain_jit_code_hash_lock (domain);
4899         info = lookup_method_inner (domain, method);
4900         mono_domain_jit_code_hash_unlock (domain);
4901         mono_loader_unlock ();
4902
4903         return info;
4904 }
4905
4906 #if ENABLE_JIT_MAP
4907 static FILE* perf_map_file = NULL;
4908
4909 void
4910 mono_enable_jit_map (void)
4911 {
4912         if (!perf_map_file) {
4913                 char name [64];
4914                 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
4915                 unlink (name);
4916                 perf_map_file = fopen (name, "w");
4917         }
4918 }
4919
4920 void
4921 mono_emit_jit_tramp (void *start, int size, const char *desc)
4922 {
4923         if (perf_map_file)
4924                 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
4925 }
4926
4927 void
4928 mono_emit_jit_map (MonoJitInfo *jinfo)
4929 {
4930         if (perf_map_file) {
4931                 char *name = mono_method_full_name (jinfo->method, TRUE);
4932                 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
4933                 g_free (name);
4934         }
4935 }
4936
4937 gboolean
4938 mono_jit_map_is_enabled (void)
4939 {
4940         return perf_map_file != NULL;
4941 }
4942
4943 #endif
4944
4945 static gpointer
4946 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoException **jit_ex)
4947 {
4948         MonoCompile *cfg;
4949         gpointer code = NULL;
4950         MonoJitInfo *jinfo, *info;
4951         MonoVTable *vtable;
4952         MonoException *ex = NULL;
4953         guint32 prof_options;
4954         GTimer *jit_timer;
4955         MonoMethod *prof_method;
4956
4957 #ifdef MONO_USE_AOT_COMPILER
4958         if (opt & MONO_OPT_AOT) {
4959                 MonoDomain *domain = mono_domain_get ();
4960
4961                 mono_class_init (method->klass);
4962
4963                 if ((code = mono_aot_get_method (domain, method))) {
4964                         vtable = mono_class_vtable (domain, method->klass);
4965                         g_assert (vtable);
4966                         mono_runtime_class_init (vtable);
4967
4968                         return code;
4969                 }
4970         }
4971 #endif
4972
4973         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4974             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4975                 MonoMethod *nm;
4976                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
4977
4978                 if (!piinfo->addr) {
4979                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4980                                 piinfo->addr = mono_lookup_internal_call (method);
4981                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
4982 #ifdef HOST_WIN32
4983                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
4984 #else
4985                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
4986 #endif
4987                         else
4988                                 mono_lookup_pinvoke_call (method, NULL, NULL);
4989                 }
4990                 nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc, FALSE);
4991                 code = mono_get_addr_from_ftnptr (mono_compile_method (nm));
4992                 jinfo = mono_jit_info_table_find (target_domain, code);
4993                 if (!jinfo)
4994                         jinfo = mono_jit_info_table_find (mono_domain_get (), code);
4995                 if (jinfo)
4996                         mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4997                 return code;
4998
4999                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
5000                 //mono_debug_add_wrapper (method, nm);
5001         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
5002                 const char *name = method->name;
5003                 char *full_name, *msg;
5004                 MonoMethod *nm;
5005
5006                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
5007                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
5008                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
5009                                 g_assert (mi);
5010                                 /*
5011                                  * We need to make sure this wrapper
5012                                  * is compiled because it might end up
5013                                  * in an (M)RGCTX if generic sharing
5014                                  * is enabled, and would be called
5015                                  * indirectly.  If it were a
5016                                  * trampoline we'd try to patch that
5017                                  * indirect call, which is not
5018                                  * possible.
5019                                  */
5020                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
5021                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
5022 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
5023                                 return mono_create_delegate_trampoline (method->klass);
5024 #else
5025                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
5026                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5027 #endif
5028                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
5029                                 nm = mono_marshal_get_delegate_begin_invoke (method);
5030                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5031                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
5032                                 nm = mono_marshal_get_delegate_end_invoke (method);
5033                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5034                         }
5035                 }
5036
5037                 full_name = mono_method_full_name (method, TRUE);
5038                 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
5039                 *jit_ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
5040                 g_free (full_name);
5041                 g_free (msg);
5042                 return NULL;
5043         }
5044
5045         if (mono_aot_only) {
5046                 char *fullname = mono_method_full_name (method, TRUE);
5047                 char *msg = g_strdup_printf ("Attempting to JIT compile method '%s' while running with --aot-only.\n", fullname);
5048
5049                 *jit_ex = mono_get_exception_execution_engine (msg);
5050                 g_free (fullname);
5051                 g_free (msg);
5052                 
5053                 return NULL;
5054         }
5055
5056         jit_timer = g_timer_new ();
5057
5058         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
5059         prof_method = cfg->method;
5060
5061         g_timer_stop (jit_timer);
5062         mono_jit_stats.jit_time += g_timer_elapsed (jit_timer, NULL);
5063         g_timer_destroy (jit_timer);
5064
5065         switch (cfg->exception_type) {
5066         case MONO_EXCEPTION_NONE:
5067                 break;
5068         case MONO_EXCEPTION_TYPE_LOAD:
5069         case MONO_EXCEPTION_MISSING_FIELD:
5070         case MONO_EXCEPTION_MISSING_METHOD:
5071         case MONO_EXCEPTION_FILE_NOT_FOUND:
5072         case MONO_EXCEPTION_BAD_IMAGE: {
5073                 /* Throw a type load exception if needed */
5074                 MonoLoaderError *error = mono_loader_get_last_error ();
5075
5076                 if (error) {
5077                         ex = mono_loader_error_prepare_exception (error);
5078                 } else {
5079                         if (cfg->exception_ptr) {
5080                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
5081                         } else {
5082                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
5083                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
5084                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
5085                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
5086                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
5087                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
5088                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
5089                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
5090                                 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
5091                                         ex = mono_get_exception_bad_image_format (cfg->exception_message);
5092                                 else
5093                                         g_assert_not_reached ();
5094                         }
5095                 }
5096                 break;
5097         }
5098         case MONO_EXCEPTION_INVALID_PROGRAM:
5099                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
5100                 break;
5101         case MONO_EXCEPTION_UNVERIFIABLE_IL:
5102                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
5103                 break;
5104         case MONO_EXCEPTION_METHOD_ACCESS:
5105                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
5106                 break;
5107         case MONO_EXCEPTION_FIELD_ACCESS:
5108                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
5109                 break;
5110         /* this can only be set if the security manager is active */
5111         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
5112                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
5113                 MonoObject *exc = NULL;
5114                 gpointer args [2];
5115
5116                 args [0] = &cfg->exception_data;
5117                 args [1] = &method;
5118                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
5119
5120                 ex = (MonoException*)exc;
5121                 break;
5122         }
5123         case MONO_EXCEPTION_OBJECT_SUPPLIED: {
5124                 MonoException *exp = cfg->exception_ptr;
5125                 MONO_GC_UNREGISTER_ROOT (cfg->exception_ptr);
5126
5127                 ex = exp;
5128                 break;
5129         }
5130         case MONO_EXCEPTION_OUT_OF_MEMORY:
5131                 ex = mono_domain_get ()->out_of_memory_ex;
5132                 break;
5133         default:
5134                 g_assert_not_reached ();
5135         }
5136
5137         if (ex) {
5138                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
5139                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
5140
5141                 mono_destroy_compile (cfg);
5142                 *jit_ex = ex;
5143
5144                 return NULL;
5145         }
5146
5147         mono_loader_lock (); /*FIXME lookup_method_inner requires the loader lock*/
5148         mono_domain_lock (target_domain);
5149
5150         /* Check if some other thread already did the job. In this case, we can
5151        discard the code this thread generated. */
5152
5153         mono_domain_jit_code_hash_lock (target_domain);
5154
5155         info = lookup_method_inner (target_domain, method);
5156         if (info) {
5157                 /* We can't use a domain specific method in another domain */
5158                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
5159                         code = info->code_start;
5160 //                      printf("Discarding code for method %s\n", method->name);
5161                 }
5162         }
5163         
5164         if (code == NULL) {
5165                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->method, cfg->jit_info);
5166                 mono_domain_jit_code_hash_unlock (target_domain);
5167                 code = cfg->native_code;
5168
5169                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method, FALSE))
5170                         mono_stats.generics_shared_methods++;
5171         } else {
5172                 mono_domain_jit_code_hash_unlock (target_domain);
5173         }
5174
5175         jinfo = cfg->jit_info;
5176
5177         prof_options = cfg->prof_options;
5178
5179         mono_destroy_compile (cfg);
5180
5181 #ifndef DISABLE_JIT
5182         if (domain_jit_info (target_domain)->jump_target_hash) {
5183                 MonoJumpInfo patch_info;
5184                 GSList *list, *tmp;
5185                 list = g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
5186                 if (list) {
5187                         patch_info.next = NULL;
5188                         patch_info.ip.i = 0;
5189                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
5190                         patch_info.data.method = method;
5191                         g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
5192                 }
5193                 for (tmp = list; tmp; tmp = tmp->next)
5194                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
5195                 g_slist_free (list);
5196         }
5197
5198         mono_emit_jit_map (jinfo);
5199 #endif
5200         mono_domain_unlock (target_domain);
5201         mono_loader_unlock ();
5202
5203         vtable = mono_class_vtable (target_domain, method->klass);
5204         if (!vtable) {
5205                 ex = mono_class_get_exception_for_failure (method->klass);
5206                 g_assert (ex);
5207                 *jit_ex = ex;
5208                 return NULL;
5209         }
5210
5211         if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
5212                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5213                         if (mono_marshal_method_from_wrapper (method)) {
5214                                 /* Native func wrappers have no method */
5215                                 /* The profiler doesn't know about wrappers, so pass the original icall method */
5216                                 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
5217                         }
5218                 }
5219                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
5220                 if (prof_method != method) {
5221                         mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
5222                 }
5223         }
5224
5225         ex = mono_runtime_class_init_full (vtable, FALSE);
5226         if (ex) {
5227                 *jit_ex = ex;
5228                 return NULL;
5229         }
5230         return code;
5231 }
5232
5233 static gpointer
5234 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex)
5235 {
5236         MonoDomain *target_domain, *domain = mono_domain_get ();
5237         MonoJitInfo *info;
5238         gpointer code, p;
5239         MonoJitICallInfo *callinfo = NULL;
5240
5241         /*
5242          * ICALL wrappers are handled specially, since there is only one copy of them
5243          * shared by all appdomains.
5244          */
5245         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
5246                 const char *icall_name;
5247
5248                 icall_name = method->name + strlen ("__icall_wrapper_");
5249                 g_assert (icall_name);
5250                 callinfo = mono_find_jit_icall_by_name (icall_name);
5251                 g_assert (callinfo);
5252
5253                 /* Must be domain neutral since there is only one copy */
5254                 opt |= MONO_OPT_SHARED;
5255         }
5256
5257         if (opt & MONO_OPT_SHARED)
5258                 target_domain = mono_get_root_domain ();
5259         else 
5260                 target_domain = domain;
5261
5262         info = lookup_method (target_domain, method);
5263         if (info) {
5264                 /* We can't use a domain specific method in another domain */
5265                 if (! ((domain != target_domain) && !info->domain_neutral)) {
5266                         MonoVTable *vtable;
5267                         MonoException *tmpEx;
5268
5269                         mono_jit_stats.methods_lookups++;
5270                         vtable = mono_class_vtable (domain, method->klass);
5271                         g_assert (vtable);
5272                         tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
5273                         if (tmpEx) {
5274                                 *ex = tmpEx;
5275                                 return NULL;
5276                         }
5277                         return mono_create_ftnptr (target_domain, info->code_start);
5278                 }
5279         }
5280
5281         code = mono_jit_compile_method_inner (method, target_domain, opt, ex);
5282         if (!code)
5283                 return NULL;
5284
5285         p = mono_create_ftnptr (target_domain, code);
5286
5287         if (callinfo) {
5288                 mono_jit_lock ();
5289                 if (!callinfo->wrapper) {
5290                         callinfo->wrapper = p;
5291                         mono_register_jit_icall_wrapper (callinfo, p);
5292                         mono_debug_add_icall_wrapper (method, callinfo);
5293                 }
5294                 mono_jit_unlock ();
5295         }
5296
5297         return p;
5298 }
5299
5300 gpointer
5301 mono_jit_compile_method (MonoMethod *method)
5302 {
5303         MonoException *ex = NULL;
5304         gpointer code;
5305
5306         code = mono_jit_compile_method_with_opt (method, default_opt, &ex);
5307         if (!code) {
5308                 g_assert (ex);
5309                 mono_raise_exception (ex);
5310         }
5311
5312         return code;
5313 }
5314
5315 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
5316 static void
5317 invalidated_delegate_trampoline (char *desc)
5318 {
5319         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
5320                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
5321                  desc);
5322 }
5323 #endif
5324
5325 /*
5326  * mono_jit_free_method:
5327  *
5328  *  Free all memory allocated by the JIT for METHOD.
5329  */
5330 static void
5331 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
5332 {
5333         MonoJitDynamicMethodInfo *ji;
5334         gboolean destroy = TRUE;
5335
5336         g_assert (method->dynamic);
5337
5338         mono_domain_lock (domain);
5339         ji = mono_dynamic_code_hash_lookup (domain, method);
5340         mono_domain_unlock (domain);
5341
5342         if (!ji)
5343                 return;
5344         mono_domain_lock (domain);
5345         g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
5346         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
5347         g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
5348         g_hash_table_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
5349         mono_domain_unlock (domain);
5350
5351 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
5352         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
5353                 /*
5354                  * Instead of freeing the code, change it to call an error routine
5355                  * so people can fix their code.
5356                  */
5357                 char *type = mono_type_full_name (&method->klass->byval_arg);
5358                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
5359
5360                 g_free (type);
5361                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
5362                 destroy = FALSE;
5363         }
5364 #endif
5365
5366         /* 
5367          * This needs to be done before freeing code_mp, since the code address is the
5368          * key in the table, so if we free the code_mp first, another thread can grab the
5369          * same code address and replace our entry in the table.
5370          */
5371         mono_jit_info_table_remove (domain, ji->ji);
5372
5373         if (destroy)
5374                 mono_code_manager_destroy (ji->code_mp);
5375         g_free (ji);
5376 }
5377
5378 gpointer
5379 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
5380 {
5381         MonoDomain *target_domain;
5382         MonoJitInfo *info;
5383
5384         if (default_opt & MONO_OPT_SHARED)
5385                 target_domain = mono_get_root_domain ();
5386         else 
5387                 target_domain = domain;
5388
5389         info = lookup_method (target_domain, method);
5390         if (info) {
5391                 /* We can't use a domain specific method in another domain */
5392                 if (! ((domain != target_domain) && !info->domain_neutral)) {
5393                         mono_jit_stats.methods_lookups++;
5394                         if (ji)
5395                                 *ji = info;
5396                         return info->code_start;
5397                 }
5398         }
5399
5400         if (ji)
5401                 *ji = NULL;
5402         return NULL;
5403 }
5404
5405 gpointer
5406 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
5407 {
5408         return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
5409 }
5410
5411 typedef struct {
5412         MonoMethod *method;
5413         gpointer compiled_method;
5414         gpointer runtime_invoke;
5415         MonoVTable *vtable;
5416         MonoDynCallInfo *dyn_call_info;
5417         MonoClass *ret_box_class;
5418 } RuntimeInvokeInfo;
5419
5420 /**
5421  * mono_jit_runtime_invoke:
5422  * @method: the method to invoke
5423  * @obj: this pointer
5424  * @params: array of parameter values.
5425  * @exc: used to catch exceptions objects
5426  */
5427 static MonoObject*
5428 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
5429 {
5430         MonoMethod *invoke;
5431         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
5432         MonoDomain *domain = mono_domain_get ();
5433         MonoJitDomainInfo *domain_info;
5434         RuntimeInvokeInfo *info, *info2;
5435         
5436         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
5437                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
5438                 return NULL;
5439         }
5440
5441         domain_info = domain_jit_info (domain);
5442
5443         mono_domain_lock (domain);
5444         info = g_hash_table_lookup (domain_info->runtime_invoke_hash, method);
5445         mono_domain_unlock (domain);            
5446
5447         if (!info) {
5448                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5449                         /* 
5450                          * This might be redundant since mono_class_vtable () already does this,
5451                          * but keep it just in case for moonlight.
5452                          */
5453                         mono_class_setup_vtable (method->klass);
5454                         if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
5455                                 if (exc)
5456                                         *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
5457                                 else
5458                                         mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
5459                                 return NULL;
5460                         }
5461                 }
5462
5463                 info = g_new0 (RuntimeInvokeInfo, 1);
5464
5465                 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
5466                 info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
5467                 g_assert (info->vtable);
5468
5469                 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
5470                         (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
5471                         /* 
5472                          * Array Get/Set/Address methods. The JIT implements them using inline code 
5473                          * inside the runtime invoke wrappers, so no need to compile them.
5474                          */
5475                         info->compiled_method = NULL;
5476                 } else {
5477                         MonoException *jit_ex = NULL;
5478
5479                         info->compiled_method = mono_jit_compile_method_with_opt (method, default_opt, &jit_ex);
5480                         if (!info->compiled_method) {
5481                                 g_free (info);
5482                                 g_assert (jit_ex);
5483                                 if (exc) {
5484                                         *exc = (MonoObject*)jit_ex;
5485                                         return NULL;
5486                                 } else {
5487                                         mono_raise_exception (jit_ex);
5488                                 }
5489                         }
5490
5491                         if (mono_method_needs_static_rgctx_invoke (method, FALSE))
5492                                 info->compiled_method = mono_create_static_rgctx_trampoline (method, info->compiled_method);
5493                 }
5494
5495                 /*
5496                  * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
5497                  * in full-aot mode, so we use a slower, but more generic wrapper if
5498                  * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
5499                  */
5500 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5501                 if (mono_aot_only || debug_options.dyn_runtime_invoke) {
5502                         MonoMethodSignature *sig = mono_method_signature (method);
5503                         gboolean supported = TRUE;
5504                         int i;
5505
5506                         if (method->string_ctor)
5507                                 sig = mono_marshal_get_string_ctor_signature (method);
5508
5509                         for (i = 0; i < sig->param_count; ++i) {
5510                                 MonoType *t = sig->params [i];
5511
5512                                 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
5513                                         supported = FALSE;
5514                         }
5515
5516                         if (method->klass->contextbound || !info->compiled_method)
5517                                 supported = FALSE;
5518
5519                         if (supported)
5520                                 info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
5521
5522                         if (info->dyn_call_info) {
5523                                 switch (sig->ret->type) {
5524                                 case MONO_TYPE_VOID:
5525                                         break;
5526                                 case MONO_TYPE_I1:
5527                                 case MONO_TYPE_U1:
5528                                 case MONO_TYPE_I2:
5529                                 case MONO_TYPE_U2:
5530                                 case MONO_TYPE_I4:
5531                                 case MONO_TYPE_U4:
5532                                 case MONO_TYPE_I:
5533                                 case MONO_TYPE_U:
5534                                 case MONO_TYPE_I8:
5535                                 case MONO_TYPE_U8:
5536                                 case MONO_TYPE_BOOLEAN:
5537                                 case MONO_TYPE_CHAR:
5538                                 case MONO_TYPE_R4:
5539                                 case MONO_TYPE_R8:
5540                                         info->ret_box_class = mono_class_from_mono_type (sig->ret);
5541                                         break;
5542                                 case MONO_TYPE_PTR:
5543                                         info->ret_box_class = mono_defaults.int_class;
5544                                         break;
5545                                 case MONO_TYPE_STRING:
5546                                 case MONO_TYPE_CLASS:  
5547                                 case MONO_TYPE_ARRAY:
5548                                 case MONO_TYPE_SZARRAY:
5549                                 case MONO_TYPE_OBJECT:
5550                                         break;
5551                                 case MONO_TYPE_GENERICINST:
5552                                         if (!MONO_TYPE_IS_REFERENCE (sig->ret))
5553                                                 info->ret_box_class = mono_class_from_mono_type (sig->ret);
5554                                         break;
5555                                 case MONO_TYPE_VALUETYPE:
5556                                         info->ret_box_class = mono_class_from_mono_type (sig->ret);
5557                                         break;
5558                                 default:
5559                                         g_assert_not_reached ();
5560                                         break;
5561                                 }
5562                         }
5563                 }
5564 #endif
5565
5566                 if (!info->dyn_call_info)
5567                         info->runtime_invoke = mono_jit_compile_method (invoke);
5568
5569                 mono_domain_lock (domain);
5570                 info2 = g_hash_table_lookup (domain_info->runtime_invoke_hash, method);
5571                 if (info2) {
5572                         g_free (info);
5573                         info = info2;
5574                 } else {
5575                         g_hash_table_insert (domain_info->runtime_invoke_hash, method, info);
5576                 }
5577                 mono_domain_unlock (domain);
5578         }
5579
5580         runtime_invoke = info->runtime_invoke;
5581
5582         /*
5583          * We need this here because mono_marshal_get_runtime_invoke can place 
5584          * the helper method in System.Object and not the target class.
5585          */
5586         if (exc) {
5587                 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
5588                 if (*exc)
5589                         return NULL;
5590         } else {
5591                 mono_runtime_class_init (info->vtable);
5592         }
5593
5594         /* The wrappers expect this to be initialized to NULL */
5595         if (exc)
5596                 *exc = NULL;
5597
5598 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5599         if (info->dyn_call_info) {
5600                 MonoMethodSignature *sig = mono_method_signature (method);
5601                 gpointer *args;
5602                 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
5603                 int i, pindex;
5604                 guint8 buf [128];
5605                 guint8 retval [128];
5606
5607                 if (!dyn_runtime_invoke) {
5608                         invoke = mono_marshal_get_runtime_invoke_dynamic ();
5609                         dyn_runtime_invoke = mono_jit_compile_method (invoke);
5610                 }
5611
5612                 /* Convert the arguments to the format expected by start_dyn_call () */
5613                 args = g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
5614                 pindex = 0;
5615                 if (sig->hasthis)
5616                         args [pindex ++] = &obj;
5617                 for (i = 0; i < sig->param_count; ++i) {
5618                         MonoType *t = sig->params [i];
5619
5620                         if (t->byref) {
5621                                 args [pindex ++] = &params [i];
5622                         } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
5623                                 args [pindex ++] = &params [i];
5624                         } else {
5625                                 args [pindex ++] = params [i];
5626                         }
5627                 }
5628
5629                 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
5630
5631                 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
5632
5633                 dyn_runtime_invoke (buf, exc, info->compiled_method);
5634
5635                 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
5636
5637                 if (info->ret_box_class)
5638                         return mono_value_box (domain, info->ret_box_class, retval);
5639                 else
5640                         return *(MonoObject**)retval;
5641         }
5642 #endif
5643
5644         return runtime_invoke (obj, params, exc, info->compiled_method);
5645 }
5646
5647 void
5648 SIG_HANDLER_SIGNATURE (mono_sigfpe_signal_handler)
5649 {
5650         MonoException *exc = NULL;
5651         MonoJitInfo *ji;
5652 #if !(defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32))
5653         void *info = NULL;
5654 #endif
5655         GET_CONTEXT;
5656
5657         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
5658
5659 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
5660         if (mono_arch_is_int_overflow (ctx, info))
5661                 /*
5662                  * The spec says this throws ArithmeticException, but MS throws the derived
5663                  * OverflowException.
5664                  */
5665                 exc = mono_get_exception_overflow ();
5666         else
5667                 exc = mono_get_exception_divide_by_zero ();
5668 #else
5669         exc = mono_get_exception_divide_by_zero ();
5670 #endif
5671
5672         if (!ji) {
5673                 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5674                         return;
5675
5676                 mono_handle_native_sigsegv (SIGSEGV, ctx);
5677         }
5678         
5679         mono_arch_handle_exception (ctx, exc, FALSE);
5680 }
5681
5682 void
5683 SIG_HANDLER_SIGNATURE (mono_sigill_signal_handler)
5684 {
5685         MonoException *exc;
5686         GET_CONTEXT;
5687
5688         exc = mono_get_exception_execution_engine ("SIGILL");
5689         
5690         mono_arch_handle_exception (ctx, exc, FALSE);
5691 }
5692
5693 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
5694 #define HAVE_SIG_INFO
5695 #endif
5696
5697 void
5698 SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
5699 {
5700         MonoJitInfo *ji;
5701         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
5702         gpointer fault_addr = NULL;
5703
5704         GET_CONTEXT;
5705
5706 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
5707         if (mono_arch_is_single_step_event (info, ctx)) {
5708                 mono_debugger_agent_single_step_event (ctx);
5709                 return;
5710         } else if (mono_arch_is_breakpoint_event (info, ctx)) {
5711                 mono_debugger_agent_breakpoint_hit (ctx);
5712                 return;
5713         }
5714 #endif
5715
5716 #if !defined(HOST_WIN32) && defined(HAVE_SIG_INFO)
5717         fault_addr = info->si_addr;
5718         if (mono_aot_is_pagefault (info->si_addr)) {
5719                 mono_aot_handle_pagefault (info->si_addr);
5720                 return;
5721         }
5722 #endif
5723
5724         /* The thread might no be registered with the runtime */
5725         if (!mono_domain_get () || !jit_tls) {
5726                 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5727                         return;
5728                 mono_handle_native_sigsegv (SIGSEGV, ctx);
5729         }
5730
5731         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
5732
5733 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
5734         if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr))
5735                 return;
5736
5737 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
5738         /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
5739         fault_addr = info->si_addr;
5740         if (fault_addr == NULL) {
5741                 MonoContext mctx;
5742
5743                 mono_arch_sigctx_to_monoctx (ctx, &mctx);
5744
5745                 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
5746         }
5747 #endif
5748
5749         /* The hard-guard page has been hit: there is not much we can do anymore
5750          * Print a hopefully clear message and abort.
5751          */
5752         if (jit_tls->stack_size && 
5753                 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
5754                 const char *method;
5755                 /* we don't do much now, but we can warn the user with a useful message */
5756                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
5757                 if (ji && ji->method)
5758                         method = mono_method_full_name (ji->method, TRUE);
5759                 else
5760                         method = "Unmanaged";
5761                 fprintf (stderr, "At %s\n", method);
5762                 _exit (1);
5763         } else {
5764                 /* The original handler might not like that it is executed on an altstack... */
5765                 if (!ji && mono_chain_signal (SIG_HANDLER_PARAMS))
5766                         return;
5767
5768                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
5769         }
5770 #else
5771
5772         if (!ji) {
5773                 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5774                         return;
5775
5776                 mono_handle_native_sigsegv (SIGSEGV, ctx);
5777         }
5778                         
5779         mono_arch_handle_exception (ctx, NULL, FALSE);
5780 #endif
5781 }
5782
5783 void
5784 SIG_HANDLER_SIGNATURE (mono_sigint_signal_handler)
5785 {
5786         MonoException *exc;
5787         GET_CONTEXT;
5788
5789         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
5790         
5791         mono_arch_handle_exception (ctx, exc, FALSE);
5792 }
5793
5794 /* mono_jit_create_remoting_trampoline:
5795  * @method: pointer to the method info
5796  *
5797  * Creates a trampoline which calls the remoting functions. This
5798  * is used in the vtable of transparent proxies.
5799  * 
5800  * Returns: a pointer to the newly created code 
5801  */
5802 static gpointer
5803 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
5804 {
5805         MonoMethod *nm;
5806         guint8 *addr = NULL;
5807
5808         if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
5809                 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
5810                         domain, NULL);
5811         }
5812
5813         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
5814             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
5815                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
5816                 addr = mono_compile_method (nm);
5817         } else {
5818                 addr = mono_compile_method (method);
5819         }
5820         return mono_get_addr_from_ftnptr (addr);
5821 }
5822
5823 static gpointer *vtable_trampolines;
5824 static int vtable_trampolines_size;
5825
5826 gpointer
5827 mini_get_vtable_trampoline (int slot_index)
5828 {
5829         int index = slot_index + MONO_IMT_SIZE;
5830
5831         g_assert (slot_index >= - MONO_IMT_SIZE);
5832         if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
5833                 mono_jit_lock ();
5834                 if (!vtable_trampolines || index >= vtable_trampolines_size) {
5835                         int new_size;
5836                         gpointer new_table;
5837
5838                         new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
5839                         while (new_size <= index)
5840                                 new_size *= 2;
5841                         new_table = g_new0 (gpointer, new_size);
5842
5843                         if (vtable_trampolines)
5844                                 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
5845                         g_free (vtable_trampolines);
5846                         mono_memory_barrier ();
5847                         vtable_trampolines = new_table;
5848                         vtable_trampolines_size = new_size;
5849                 }
5850                 mono_jit_unlock ();
5851         }
5852
5853         if (!vtable_trampolines [index])
5854                 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
5855         return vtable_trampolines [index];
5856 }
5857
5858 static gpointer
5859 mini_get_imt_trampoline (int slot_index)
5860 {
5861         return mini_get_vtable_trampoline (slot_index - MONO_IMT_SIZE);
5862 }
5863
5864 static void
5865 mini_parse_debug_options (void)
5866 {
5867         char *options = getenv ("MONO_DEBUG");
5868         gchar **args, **ptr;
5869         
5870         if (!options)
5871                 return;
5872
5873         args = g_strsplit (options, ",", -1);
5874
5875         for (ptr = args; ptr && *ptr; ptr++) {
5876                 const char *arg = *ptr;
5877
5878                 if (!strcmp (arg, "handle-sigint"))
5879                         debug_options.handle_sigint = TRUE;
5880                 else if (!strcmp (arg, "keep-delegates"))
5881                         debug_options.keep_delegates = TRUE;
5882                 else if (!strcmp (arg, "reverse-pinvoke-exceptions"))
5883                         debug_options.reverse_pinvoke_exceptions = TRUE;
5884                 else if (!strcmp (arg, "collect-pagefault-stats"))
5885                         debug_options.collect_pagefault_stats = TRUE;
5886                 else if (!strcmp (arg, "break-on-unverified"))
5887                         debug_options.break_on_unverified = TRUE;
5888                 else if (!strcmp (arg, "no-gdb-backtrace"))
5889                         debug_options.no_gdb_backtrace = TRUE;
5890                 else if (!strcmp (arg, "suspend-on-sigsegv"))
5891                         debug_options.suspend_on_sigsegv = TRUE;
5892                 else if (!strcmp (arg, "dont-free-domains"))
5893                         mono_dont_free_domains = TRUE;
5894                 else if (!strcmp (arg, "dyn-runtime-invoke"))
5895                         debug_options.dyn_runtime_invoke = TRUE;
5896                 else if (!strcmp (arg, "gdb"))
5897                         debug_options.gdb = TRUE;
5898                 else if (!strcmp (arg, "explicit-null-checks"))
5899                         debug_options.explicit_null_checks = TRUE;
5900                 else if (!strcmp (arg, "gen-seq-points"))
5901                         debug_options.gen_seq_points = TRUE;
5902                 else if (!strcmp (arg, "init-stacks"))
5903                         debug_options.init_stacks = TRUE;
5904                 else if (!strcmp (arg, "casts"))
5905                         debug_options.better_cast_details = TRUE;
5906                 else {
5907                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
5908                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains', 'suspend-on-sigsegv', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks'\n");
5909                         exit (1);
5910                 }
5911         }
5912
5913         g_strfreev (args);
5914 }
5915
5916 MonoDebugOptions *
5917 mini_get_debug_options (void)
5918 {
5919         return &debug_options;
5920 }
5921
5922 static gpointer
5923 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
5924 {
5925 #ifdef __ia64__
5926         gpointer *desc;
5927
5928         desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
5929
5930         desc [0] = addr;
5931         desc [1] = NULL;
5932
5933         return desc;
5934 #elif defined(__ppc64__) || defined(__powerpc64__)
5935         gpointer *desc;
5936
5937         desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
5938
5939         desc [0] = addr;
5940         desc [1] = NULL;
5941         desc [2] = NULL;
5942
5943         return desc;
5944 #else
5945         return addr;
5946 #endif
5947 }
5948
5949 static gpointer
5950 mini_get_addr_from_ftnptr (gpointer descr)
5951 {
5952 #if defined(__ia64__) || defined(__ppc64__) || defined(__powerpc64__)
5953         return *(gpointer*)descr;
5954 #else
5955         return descr;
5956 #endif
5957 }       
5958
5959 static void
5960 register_jit_stats (void)
5961 {
5962         mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_compiled);
5963         mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_aot);
5964         mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);   
5965         mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
5966         mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
5967 }
5968
5969 static void runtime_invoke_info_free (gpointer value);
5970  
5971 static void
5972 mini_create_jit_domain_info (MonoDomain *domain)
5973 {
5974         MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
5975
5976         info->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5977         info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5978         info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5979         info->delegate_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5980         info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5981         info->runtime_invoke_hash = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
5982         info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, g_free);
5983         info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
5984
5985         domain->runtime_info = info;
5986 }
5987
5988 static void
5989 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
5990 {
5991         g_slist_free (value);
5992 }
5993
5994 static void
5995 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
5996 {
5997         MonoJitDynamicMethodInfo *di = value;
5998         mono_code_manager_destroy (di->code_mp);
5999         g_free (di);
6000 }
6001
6002 static void
6003 runtime_invoke_info_free (gpointer value)
6004 {
6005         RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
6006
6007 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
6008         if (info->dyn_call_info)
6009                 mono_arch_dyn_call_free (info->dyn_call_info);
6010 #endif
6011         g_free (info);
6012 }
6013
6014 static void
6015 mini_free_jit_domain_info (MonoDomain *domain)
6016 {
6017         MonoJitDomainInfo *info = domain_jit_info (domain);
6018
6019         if (info->jump_target_hash) {
6020                 g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
6021                 g_hash_table_destroy (info->jump_target_hash);
6022         }
6023         if (info->jump_target_got_slot_hash) {
6024                 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_jump_list, NULL);
6025                 g_hash_table_destroy (info->jump_target_got_slot_hash);
6026         }
6027         if (info->dynamic_code_hash) {
6028                 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
6029                 g_hash_table_destroy (info->dynamic_code_hash);
6030         }
6031         if (info->method_code_hash)
6032                 g_hash_table_destroy (info->method_code_hash);
6033         g_hash_table_destroy (info->class_init_trampoline_hash);
6034         g_hash_table_destroy (info->jump_trampoline_hash);
6035         g_hash_table_destroy (info->jit_trampoline_hash);
6036         g_hash_table_destroy (info->delegate_trampoline_hash);
6037         if (info->static_rgctx_trampoline_hash)
6038                 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
6039         g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
6040         g_hash_table_destroy (info->runtime_invoke_hash);
6041         g_hash_table_destroy (info->seq_points);
6042         g_hash_table_destroy (info->arch_seq_points);
6043
6044         if (info->agent_info)
6045                 mono_debugger_agent_free_domain_info (domain);
6046
6047         g_free (domain->runtime_info);
6048         domain->runtime_info = NULL;
6049 }
6050
6051 MonoDomain *
6052 mini_init (const char *filename, const char *runtime_version)
6053 {
6054         MonoDomain *domain;
6055         MonoRuntimeCallbacks callbacks;
6056
6057         MONO_PROBE_VES_INIT_BEGIN ();
6058
6059 #if defined(__linux__) && !defined(__native_client__)
6060         if (access ("/proc/self/maps", F_OK) != 0) {
6061                 g_print ("Mono requires /proc to be mounted.\n");
6062                 exit (1);
6063         }
6064 #endif
6065
6066         /* Happens when using the embedding interface */
6067         if (!default_opt_set)
6068                 default_opt = mono_parse_default_optimizations (NULL);
6069
6070         InitializeCriticalSection (&jit_mutex);
6071
6072 #ifdef MONO_DEBUGGER_SUPPORTED
6073         if (mini_debug_running_inside_mdb ())
6074                 mini_debugger_init ();
6075 #endif
6076
6077 #ifdef MINI_HAVE_FAST_TLS
6078         MINI_FAST_TLS_INIT (mono_jit_tls);
6079         MINI_FAST_TLS_INIT (mono_lmf_addr);
6080 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
6081         MINI_FAST_TLS_INIT (mono_lmf);
6082 #endif
6083 #endif
6084
6085 #ifdef MONO_ARCH_HAVE_TLS_GET
6086         mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
6087 #else
6088         mono_runtime_set_has_tls_get (FALSE);
6089 #endif
6090
6091         if (!global_codeman)
6092                 global_codeman = mono_code_manager_new ();
6093         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6094
6095         memset (&callbacks, 0, sizeof (callbacks));
6096         callbacks.create_ftnptr = mini_create_ftnptr;
6097         callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
6098         callbacks.get_runtime_build_info = mono_get_runtime_build_info;
6099
6100 #ifdef MONO_ARCH_HAVE_IMT
6101         if (mono_use_imt) {
6102                 callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
6103                 callbacks.get_imt_trampoline = mini_get_imt_trampoline;
6104         }
6105 #endif
6106
6107         mono_install_callbacks (&callbacks);
6108
6109         if (getenv ("MONO_DEBUG") != NULL)
6110                 mini_parse_debug_options ();
6111         
6112         mono_arch_cpu_init ();
6113
6114         mono_arch_init ();
6115
6116         mono_unwind_init ();
6117
6118         mini_gc_init ();
6119
6120         if (getenv ("MONO_XDEBUG")) {
6121                 char *xdebug_opts = getenv ("MONO_XDEBUG");
6122                 mono_xdebug_init (xdebug_opts);
6123                 /* So methods for multiple domains don't have the same address */
6124                 mono_dont_free_domains = TRUE;
6125                 mono_using_xdebug = TRUE;
6126         } else if (mini_get_debug_options ()->gdb) {
6127                 mono_xdebug_init ((char*)"gdb");
6128                 mono_dont_free_domains = TRUE;
6129                 mono_using_xdebug = TRUE;
6130         }
6131
6132 #ifdef ENABLE_LLVM
6133         if (mono_use_llvm) {
6134                 if (!mono_llvm_load (NULL)) {
6135                         mono_use_llvm = FALSE;
6136                         fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
6137                 }
6138         }
6139         if (mono_use_llvm)
6140                 mono_llvm_init ();
6141 #endif
6142
6143         mono_trampolines_init ();
6144
6145         if (!g_thread_supported ())
6146                 g_thread_init (NULL);
6147
6148         mono_jit_tls_id = TlsAlloc ();
6149         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
6150
6151         if (default_opt & MONO_OPT_AOT)
6152                 mono_aot_init ();
6153
6154         mono_debugger_agent_init ();
6155
6156 #ifdef MONO_ARCH_GSHARED_SUPPORTED
6157         mono_set_generic_sharing_supported (TRUE);
6158 #endif
6159
6160 #ifndef MONO_CROSS_COMPILE
6161         mono_runtime_install_handlers ();
6162 #endif
6163         mono_threads_install_cleanup (mini_thread_cleanup);
6164
6165 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
6166         // This is experimental code so provide an env var to switch it off
6167         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
6168                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
6169         } else {
6170                 check_for_pending_exc = FALSE;
6171                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
6172         }
6173 #endif
6174
6175 #define JIT_TRAMPOLINES_WORK
6176 #ifdef JIT_TRAMPOLINES_WORK
6177         mono_install_compile_method (mono_jit_compile_method);
6178         mono_install_free_method (mono_jit_free_method);
6179         mono_install_trampoline (mono_create_jit_trampoline);
6180         mono_install_jump_trampoline (mono_create_jump_trampoline);
6181         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6182         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
6183         mono_install_create_domain_hook (mini_create_jit_domain_info);
6184         mono_install_free_domain_hook (mini_free_jit_domain_info);
6185 #endif
6186 #define JIT_INVOKE_WORKS
6187 #ifdef JIT_INVOKE_WORKS
6188         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6189 #endif
6190         mono_install_stack_walk (mono_jit_walk_stack);
6191         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
6192         mono_install_get_class_from_name (mono_aot_get_class_from_name);
6193         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
6194
6195         if (debug_options.collect_pagefault_stats) {
6196                 mono_aot_set_make_unreadable (TRUE);
6197         }
6198
6199         if (runtime_version)
6200                 domain = mono_init_version (filename, runtime_version);
6201         else
6202                 domain = mono_init_from_assembly (filename, filename);
6203
6204         if (mono_aot_only) {
6205                 /* This helps catch code allocation requests */
6206                 mono_code_manager_set_read_only (domain->code_mp);
6207         }
6208
6209 #ifdef MONO_ARCH_HAVE_IMT
6210         if (mono_use_imt) {
6211                 if (mono_aot_only)
6212                         mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
6213                 else
6214                         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
6215         }
6216 #endif
6217
6218         /* This must come after mono_init () in the aot-only case */
6219         mono_exceptions_init ();
6220         mono_install_handler (mono_get_throw_exception ());
6221
6222         mono_icall_init ();
6223
6224         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6225                                 ves_icall_get_frame_info);
6226         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6227                                 ves_icall_get_trace);
6228         mono_add_internal_call ("System.Exception::get_trace", 
6229                                 ves_icall_System_Exception_get_trace);
6230         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
6231                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
6232         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
6233                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
6234         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6235                                 mono_runtime_install_handlers);
6236
6237         mono_create_helper_signatures ();
6238
6239         register_jit_stats ();
6240
6241 #define JIT_CALLS_WORK
6242 #ifdef JIT_CALLS_WORK
6243         /* Needs to be called here since register_jit_icall depends on it */
6244         mono_marshal_init ();
6245
6246         mono_arch_register_lowlevel_calls ();
6247         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6248         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6249         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
6250         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
6251         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
6252         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
6253         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
6254
6255         register_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
6256         register_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
6257         register_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
6258                                  "void ptr", TRUE);
6259         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
6260         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
6261         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
6262         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
6263         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
6264
6265 #if defined(__native_client__) || defined(__native_client_codegen__)
6266         register_icall (mono_nacl_gc, "mono_nacl_gc", "void", TRUE);
6267 #endif
6268         /* 
6269          * NOTE, NOTE, NOTE, NOTE:
6270          * when adding emulation for some opcodes, remember to also add a dummy
6271          * rule to the burg files, because we need the arity information to be correct.
6272          */
6273 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
6274         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
6275         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
6276         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
6277         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
6278         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
6279         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
6280         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
6281 #endif
6282
6283 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
6284         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
6285         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
6286         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
6287 #endif
6288
6289 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
6290         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
6291         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
6292         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
6293         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
6294         mono_register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, FALSE);
6295         mono_register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
6296         mono_register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, FALSE);
6297         mono_register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
6298 #endif
6299
6300 #ifdef MONO_ARCH_EMULATE_MUL_DIV
6301         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
6302         mono_register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, TRUE);
6303 #endif
6304
6305 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
6306         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
6307         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
6308         mono_register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
6309         mono_register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
6310 #endif
6311
6312 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
6313         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
6314 #endif
6315
6316         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
6317         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
6318         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
6319         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
6320
6321 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
6322         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
6323 #endif
6324 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
6325         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
6326         mono_register_opcode_emulation (OP_ICONV_TO_R_UN, "__emul_iconv_to_r_un", "double int32", mono_conv_to_r8_un, FALSE);
6327 #endif
6328 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
6329         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
6330 #endif
6331 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
6332         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
6333 #endif
6334 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
6335         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
6336 #endif
6337 #ifdef MONO_ARCH_EMULATE_FREM
6338 #if defined(__default_codegen__)
6339         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
6340 #elif defined(__native_client_codegen__)
6341         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, FALSE);
6342 #endif
6343 #endif
6344
6345 #ifdef MONO_ARCH_SOFT_FLOAT
6346         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
6347         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
6348         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
6349         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
6350         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
6351         mono_register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, FALSE);
6352         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
6353         mono_register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, FALSE);
6354         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
6355         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
6356         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
6357         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
6358         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
6359         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
6360 #if SIZEOF_VOID_P == 4
6361         mono_register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, FALSE);
6362 #endif
6363
6364         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
6365         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
6366         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
6367         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
6368         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
6369         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
6370         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
6371         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
6372         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
6373         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
6374
6375         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
6376         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
6377         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
6378         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
6379         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
6380
6381         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
6382         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
6383         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
6384         register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
6385 #endif
6386
6387 #ifdef COMPRESSED_INTERFACE_BITMAP
6388         register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
6389 #endif
6390
6391 #if SIZEOF_REGISTER == 4
6392         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
6393 #endif
6394
6395         /* other jit icalls */
6396         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
6397         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6398                                  "ptr ptr ptr", FALSE);
6399         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
6400         register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
6401                 "ptr ptr ptr ptr", FALSE);
6402         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
6403         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
6404         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
6405         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
6406         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
6407         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
6408         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
6409         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
6410         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
6411         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
6412         register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
6413         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr", FALSE);
6414         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
6415         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
6416         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
6417         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
6418         register_icall (mono_object_castclass, "mono_object_castclass", "object object ptr", FALSE);
6419         register_icall (mono_break, "mono_break", NULL, TRUE);
6420         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
6421         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
6422         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
6423         register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
6424         register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
6425         register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
6426         register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
6427         register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
6428
6429         register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
6430
6431         register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
6432         register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
6433
6434 #endif
6435
6436         mono_generic_sharing_init ();
6437
6438 #ifdef MONO_ARCH_SIMD_INTRINSICS
6439         mono_simd_intrinsics_init ();
6440 #endif
6441
6442 #if MONO_SUPPORT_TASKLETS
6443         mono_tasklets_init ();
6444 #endif
6445
6446         if (mono_compile_aot)
6447                 /* 
6448                  * Avoid running managed code when AOT compiling, since the platform
6449                  * might only support aot-only execution.
6450                  */
6451                 mono_runtime_set_no_exec (TRUE);
6452
6453 #define JIT_RUNTIME_WORKS
6454 #ifdef JIT_RUNTIME_WORKS
6455         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
6456         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
6457         mono_thread_attach (domain);
6458 #endif
6459
6460         mono_profiler_runtime_initialized ();
6461
6462         MONO_PROBE_VES_INIT_END ();
6463         
6464         return domain;
6465 }
6466
6467 MonoJitStats mono_jit_stats = {0};
6468
6469 static void 
6470 print_jit_stats (void)
6471 {
6472         if (mono_jit_stats.enabled) {
6473                 g_print ("Mono Jit statistics\n");
6474                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
6475                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
6476                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
6477                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
6478                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
6479                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
6480                 g_print ("Max code size ratio:    %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6481                                  mono_jit_stats.max_ratio_method);
6482                 g_print ("Biggest method:         %ld (%s)\n", mono_jit_stats.biggest_method_size,
6483                                  mono_jit_stats.biggest_method);
6484                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
6485                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
6486                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
6487                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
6488                 g_print ("Regvars:                %ld\n", mono_jit_stats.regvars);
6489                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
6490
6491                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
6492                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
6493                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
6494                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
6495                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
6496                 g_print ("Methods:                %ld\n", mono_stats.method_count);
6497                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
6498                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
6499                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
6500
6501                 g_print ("\nInitialized classes:    %ld\n", mono_stats.generic_class_count);
6502                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
6503                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
6504
6505                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
6506                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
6507                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
6508
6509                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
6510                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
6511                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
6512
6513                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
6514                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
6515                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
6516                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
6517                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
6518                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
6519                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
6520                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
6521
6522                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
6523                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
6524                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
6525
6526                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
6527                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
6528                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
6529                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
6530                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
6531                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6532                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
6533                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
6534                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
6535                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
6536                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
6537                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
6538                 }
6539
6540                 g_free (mono_jit_stats.max_ratio_method);
6541                 mono_jit_stats.max_ratio_method = NULL;
6542                 g_free (mono_jit_stats.biggest_method);
6543                 mono_jit_stats.biggest_method = NULL;
6544         }
6545 }
6546
6547 void
6548 mini_cleanup (MonoDomain *domain)
6549 {
6550         mono_runtime_shutdown_stat_profiler ();
6551         
6552 #ifndef DISABLE_COM
6553         cominterop_release_all_rcws ();
6554 #endif
6555
6556 #ifndef MONO_CROSS_COMPILE      
6557         mono_runtime_shutdown ();
6558         /* 
6559          * mono_runtime_cleanup() and mono_domain_finalize () need to
6560          * be called early since they need the execution engine still
6561          * fully working (mono_domain_finalize may invoke managed finalizers
6562          * and mono_runtime_cleanup will wait for other threads to finish).
6563          */
6564         mono_domain_finalize (domain, 2000);
6565 #endif
6566
6567         /* This accesses metadata so needs to be called before runtime shutdown */
6568         print_jit_stats ();
6569
6570         mono_profiler_shutdown ();
6571
6572 #ifndef MONO_CROSS_COMPILE
6573         mono_runtime_cleanup (domain);
6574 #endif
6575
6576         free_jit_tls_data (TlsGetValue (mono_jit_tls_id));
6577
6578         mono_icall_cleanup ();
6579
6580         mono_runtime_cleanup_handlers ();
6581
6582         mono_domain_free (domain, TRUE);
6583
6584         mono_debugger_cleanup ();
6585
6586 #ifdef ENABLE_LLVM
6587         if (mono_use_llvm)
6588                 mono_llvm_cleanup ();
6589 #endif
6590
6591         mono_aot_cleanup ();
6592
6593         mono_trampolines_cleanup ();
6594
6595         mono_unwind_cleanup ();
6596
6597         if (!mono_dont_free_global_codeman)
6598                 mono_code_manager_destroy (global_codeman);
6599         g_hash_table_destroy (jit_icall_name_hash);
6600         g_free (emul_opcode_map);
6601         g_free (emul_opcode_opcodes);
6602         g_free (vtable_trampolines);
6603
6604         mono_arch_cleanup ();
6605
6606         mono_generic_sharing_cleanup ();
6607
6608         mono_cleanup ();
6609
6610         mono_trace_cleanup ();
6611
6612         mono_counters_dump (-1, stdout);
6613
6614         if (mono_inject_async_exc_method)
6615                 mono_method_desc_free (mono_inject_async_exc_method);
6616
6617         TlsFree(mono_jit_tls_id);
6618
6619         DeleteCriticalSection (&jit_mutex);
6620
6621         DeleteCriticalSection (&mono_delegate_section);
6622 }
6623
6624 void
6625 mono_set_defaults (int verbose_level, guint32 opts)
6626 {
6627         mini_verbose = verbose_level;
6628         default_opt = opts;
6629         default_opt_set = TRUE;
6630 }
6631
6632 void
6633 mono_disable_optimizations (guint32 opts)
6634 {
6635         default_opt &= ~opts;
6636 }
6637
6638 /*
6639  * mono_get_runtime_build_info:
6640  *
6641  *   Return the runtime version + build date in string format.
6642  * The returned string is owned by the caller.
6643  */
6644 char*
6645 mono_get_runtime_build_info (void)
6646 {
6647         if (mono_build_date)
6648                 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
6649         else
6650                 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
6651 }
6652
6653 static void
6654 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
6655 {
6656         GHashTable *assemblies = (GHashTable*)user_data;
6657         MonoImage *image = mono_assembly_get_image (ass);
6658         MonoMethod *method, *invoke;
6659         int i, count = 0;
6660
6661         if (g_hash_table_lookup (assemblies, ass))
6662                 return;
6663
6664         g_hash_table_insert (assemblies, ass, ass);
6665
6666         if (mini_verbose > 0)
6667                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
6668
6669         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
6670                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
6671                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
6672                         continue;
6673
6674                 count++;
6675                 if (mini_verbose > 1) {
6676                         char * desc = mono_method_full_name (method, TRUE);
6677                         g_print ("Compiling %d %s\n", count, desc);
6678                         g_free (desc);
6679                 }
6680                 mono_compile_method (method);
6681                 if (strcmp (method->name, "Finalize") == 0) {
6682                         invoke = mono_marshal_get_runtime_invoke (method, FALSE);
6683                         mono_compile_method (invoke);
6684                 }
6685                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
6686                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
6687                         mono_compile_method (invoke);
6688                 }
6689         }
6690
6691         /* Load and precompile referenced assemblies as well */
6692         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
6693                 mono_assembly_load_reference (image, i);
6694                 if (image->references [i])
6695                         mono_precompile_assembly (image->references [i], assemblies);
6696         }
6697 }
6698
6699 void mono_precompile_assemblies ()
6700 {
6701         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
6702
6703         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
6704
6705         g_hash_table_destroy (assemblies);
6706 }
6707
6708 #ifndef DISABLE_JIT
6709
6710 void*
6711 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) {
6712         return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
6713 }
6714
6715 void
6716 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
6717 {
6718         TryBlockHole *hole = mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
6719         hole->clause = clause;
6720         hole->start_offset = start - cfg->native_code;
6721         hole->basic_block = bb;
6722
6723         cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
6724 }
6725
6726 void
6727 mono_cfg_set_exception (MonoCompile *cfg, int type)
6728 {
6729         cfg->exception_type = type;
6730 }
6731
6732 #endif