[aot] Allow the redirection of output messages from the AOT compiler to a logfile.
[mono.git] / mono / mini / aot-compiler.c
1 /*
2  * aot-compiler.c: mono Ahead of Time compiler
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Zoltan Varga (vargaz@gmail.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  * Copyright 2003-2011 Novell, Inc 
10  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
11  */
12
13 /* Remaining AOT-only work:
14  * - optimize the trampolines, generate more code in the arch files.
15  * - make things more consistent with how elf works, for example, use ELF 
16  *   relocations.
17  * Remaining generics sharing work:
18  * - optimize the size of the data which is encoded.
19  * - optimize the runtime loading of data:
20  *   - the trampoline code calls mono_jit_info_table_find () to find the rgctx, 
21  *     which loads the debugging+exception handling info for the method. This is a 
22  *     huge waste of time and code, since the rgctx structure is currently empty.
23  */
24 #include "config.h"
25 #include <sys/types.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #ifdef HAVE_STDINT_H
30 #include <stdint.h>
31 #endif
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <string.h>
35 #ifndef HOST_WIN32
36 #include <sys/time.h>
37 #else
38 #include <winsock2.h>
39 #include <windows.h>
40 #endif
41
42 #include <errno.h>
43 #include <sys/stat.h>
44
45
46 #include <mono/metadata/abi-details.h>
47 #include <mono/metadata/tabledefs.h>
48 #include <mono/metadata/class.h>
49 #include <mono/metadata/object.h>
50 #include <mono/metadata/tokentype.h>
51 #include <mono/metadata/appdomain.h>
52 #include <mono/metadata/debug-helpers.h>
53 #include <mono/metadata/assembly.h>
54 #include <mono/metadata/metadata-internals.h>
55 #include <mono/metadata/marshal.h>
56 #include <mono/metadata/gc-internal.h>
57 #include <mono/metadata/monitor.h>
58 #include <mono/metadata/mempool-internals.h>
59 #include <mono/metadata/mono-endian.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/utils/mono-logger-internal.h>
62 #include <mono/utils/mono-compiler.h>
63 #include <mono/utils/mono-time.h>
64 #include <mono/utils/mono-mmap.h>
65
66 #include "mini.h"
67 #include "image-writer.h"
68 #include "dwarfwriter.h"
69 #include "mini-gc.h"
70
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72
73 #if defined(__linux__) || defined(__native_client_codegen__)
74 #define RODATA_SECT ".rodata"
75 #elif defined(TARGET_MACH)
76 #define RODATA_SECT ".section __TEXT, __const"
77 #else
78 #define RODATA_SECT ".text"
79 #endif
80
81 #define TV_DECLARE(name) gint64 name
82 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
83 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
84
85 #ifdef TARGET_WIN32
86 #define SHARED_EXT ".dll"
87 #elif defined(__ppc__) && defined(TARGET_MACH)
88 #define SHARED_EXT ".dylib"
89 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
90 #define SHARED_EXT ".dylib"
91 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
92 #define SHARED_EXT ".dylib"
93 #else
94 #define SHARED_EXT ".so"
95 #endif
96
97 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
98 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
99 #define ROUND_DOWN(VALUE,SIZE)  ((VALUE) & ~((SIZE) - 1))
100
101 /* predefined values for static readonly fields without needed to run the .cctor */
102 typedef struct _ReadOnlyValue ReadOnlyValue;
103 struct _ReadOnlyValue {
104         ReadOnlyValue *next;
105         char *name;
106         int type; /* to be used later for typechecking to prevent user errors */
107         union {
108                 guint8 i1;
109                 guint16 i2;
110                 guint32 i4;
111                 guint64 i8;
112                 gpointer ptr;
113         } value;
114 };
115 static ReadOnlyValue *readonly_values;
116
117 typedef struct MonoAotOptions {
118         char *outfile;
119         gboolean save_temps;
120         gboolean write_symbols;
121         gboolean metadata_only;
122         gboolean bind_to_runtime_version;
123         gboolean full_aot;
124         gboolean no_dlsym;
125         gboolean static_link;
126         gboolean asm_only;
127         gboolean asm_writer;
128         gboolean nodebug;
129         gboolean dwarf_debug;
130         gboolean soft_debug;
131         gboolean log_generics;
132         gboolean log_instances;
133         gboolean direct_pinvoke;
134         gboolean direct_icalls;
135         gboolean no_direct_calls;
136         gboolean use_trampolines_page;
137         gboolean no_instances;
138         gboolean gnu_asm;
139         int nthreads;
140         int ntrampolines;
141         int nrgctx_trampolines;
142         int nimt_trampolines;
143         int ngsharedvt_arg_trampolines;
144         int nrgctx_fetch_trampolines;
145         gboolean print_skipped_methods;
146         gboolean stats;
147         char *tool_prefix;
148         gboolean autoreg;
149         char *mtriple;
150         char *llvm_path;
151         char *instances_logfile_path;
152         char *logfile;
153 } MonoAotOptions;
154
155 typedef struct MonoAotStats {
156         int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
157         int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
158         int methods_without_got_slots, direct_calls, all_calls, llvm_count;
159         int got_slots, offsets_size;
160         int got_slot_types [MONO_PATCH_INFO_NONE];
161         int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
162         int jit_time, gen_time, link_time;
163 } MonoAotStats;
164
165 typedef struct MonoAotCompile {
166         MonoImage *image;
167         GPtrArray *methods;
168         GHashTable *method_indexes;
169         GHashTable *method_depth;
170         MonoCompile **cfgs;
171         int cfgs_size;
172         GHashTable **patch_to_plt_entry;
173         GHashTable *plt_offset_to_entry;
174         GHashTable *patch_to_got_offset;
175         GHashTable **patch_to_got_offset_by_type;
176         GPtrArray *got_patches;
177         GHashTable *image_hash;
178         GHashTable *method_to_cfg;
179         GHashTable *token_info_hash;
180         GHashTable *method_to_pinvoke_import;
181         GPtrArray *extra_methods;
182         GPtrArray *image_table;
183         GPtrArray *globals;
184         GPtrArray *method_order;
185         GHashTable *export_names;
186         /* Maps MonoClass* -> blob offset */
187         GHashTable *klass_blob_hash;
188         /* Maps MonoMethod* -> blob offset */
189         GHashTable *method_blob_hash;
190         guint32 *plt_got_info_offsets;
191         guint32 got_offset, plt_offset, plt_got_offset_base;
192         guint32 final_got_size;
193         /* Number of GOT entries reserved for trampolines */
194         guint32 num_trampoline_got_entries;
195         guint32 tramp_page_size;
196
197         guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
198         guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
199         guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
200         guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
201
202         MonoAotOptions aot_opts;
203         guint32 nmethods;
204         guint32 opts;
205         guint32 simd_opts;
206         MonoMemPool *mempool;
207         MonoAotStats stats;
208         int method_index;
209         char *static_linking_symbol;
210         mono_mutex_t mutex;
211         gboolean use_bin_writer;
212         gboolean gas_line_numbers;
213         MonoImageWriter *w;
214         MonoDwarfWriter *dwarf;
215         FILE *fp;
216         char *tmpbasename;
217         char *tmpfname;
218         GSList *cie_program;
219         GHashTable *unwind_info_offsets;
220         GPtrArray *unwind_ops;
221         guint32 unwind_info_offset;
222         char *got_symbol_base;
223         char *got_symbol;
224         char *plt_symbol;
225         char *methods_symbol;
226         GHashTable *method_label_hash;
227         const char *temp_prefix;
228         const char *user_symbol_prefix;
229         const char *llvm_label_prefix;
230         const char *inst_directive;
231         guint32 label_generator;
232         gboolean llvm;
233         MonoAotFileFlags flags;
234         MonoDynamicStream blob;
235         MonoClass **typespec_classes;
236         GString *llc_args;
237         GString *as_args;
238         char *assembly_name_sym;
239         GHashTable *plt_entry_debug_sym_cache;
240         gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
241         GHashTable *ginst_hash;
242         GHashTable *dwarf_ln_filenames;
243         gboolean global_symbols;
244         gboolean direct_method_addresses;
245         int objc_selector_index, objc_selector_index_2;
246         GPtrArray *objc_selectors;
247         GHashTable *objc_selector_to_index;
248         FILE *logfile;
249         FILE *instances_logfile;
250 } MonoAotCompile;
251
252 typedef struct {
253         int plt_offset;
254         char *symbol, *llvm_symbol, *debug_sym;
255         MonoJumpInfo *ji;
256         gboolean jit_used, llvm_used;
257 } MonoPltEntry;
258
259 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
260 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
261
262 /* This points to the current acfg in LLVM mode */
263 static MonoAotCompile *llvm_acfg;
264
265 #ifdef HAVE_ARRAY_ELEM_INIT
266 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
267 #define MSGSTRFIELD1(line) str##line
268 static const struct msgstr_t {
269 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
270 #include "patch-info.h"
271 #undef PATCH_INFO
272 } opstr = {
273 #define PATCH_INFO(a,b) b,
274 #include "patch-info.h"
275 #undef PATCH_INFO
276 };
277 static const gint16 opidx [] = {
278 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
279 #include "patch-info.h"
280 #undef PATCH_INFO
281 };
282
283 static G_GNUC_UNUSED const char*
284 get_patch_name (int info)
285 {
286         return (const char*)&opstr + opidx [info];
287 }
288
289 #else
290 #define PATCH_INFO(a,b) b,
291 static const char* const
292 patch_types [MONO_PATCH_INFO_NUM + 1] = {
293 #include "patch-info.h"
294         NULL
295 };
296
297 static G_GNUC_UNUSED const char*
298 get_patch_name (int info)
299 {
300         return patch_types [info];
301 }
302
303 #endif
304
305 static char*
306 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
307
308 static void
309 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
310 {
311         char *msg;
312         va_list args;
313
314         va_start (args, format);
315         if (vasprintf (&msg, format, args) < 0)
316                 return;
317         va_end (args);
318
319         if (acfg->logfile)
320                 fprintf (acfg->logfile, "%s", msg);
321         else
322                 printf ("%s", msg);
323
324         free (msg);
325 }
326
327 /* Wrappers around the image writer functions */
328
329 static inline void
330 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
331 {
332         img_writer_emit_section_change (acfg->w, section_name, subsection_index);
333 }
334
335 static inline void
336 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
337 {
338         img_writer_emit_push_section (acfg->w, section_name, subsection);
339 }
340
341 static inline void
342 emit_pop_section (MonoAotCompile *acfg)
343 {
344         img_writer_emit_pop_section (acfg->w);
345 }
346
347 static inline void
348 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func) 
349
350         img_writer_emit_local_symbol (acfg->w, name, end_label, func); 
351 }
352
353 static inline void
354 emit_label (MonoAotCompile *acfg, const char *name) 
355
356         img_writer_emit_label (acfg->w, name); 
357 }
358
359 static inline void
360 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size) 
361
362         img_writer_emit_bytes (acfg->w, buf, size); 
363 }
364
365 static inline void
366 emit_string (MonoAotCompile *acfg, const char *value) 
367
368         img_writer_emit_string (acfg->w, value); 
369 }
370
371 static inline void
372 emit_line (MonoAotCompile *acfg) 
373
374         img_writer_emit_line (acfg->w); 
375 }
376
377 static inline void
378 emit_alignment (MonoAotCompile *acfg, int size) 
379
380         img_writer_emit_alignment (acfg->w, size); 
381 }
382
383 static inline void
384 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target) 
385
386         img_writer_emit_pointer_unaligned (acfg->w, target); 
387 }
388
389 static inline void
390 emit_pointer (MonoAotCompile *acfg, const char *target) 
391
392         img_writer_emit_pointer (acfg->w, target); 
393 }
394
395 static inline void
396 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target) 
397
398         if (prefix [0] != '\0') {
399                 char *s = g_strdup_printf ("%s%s", prefix, target);
400                 img_writer_emit_pointer (acfg->w, s);
401                 g_free (s);
402         } else {
403                 img_writer_emit_pointer (acfg->w, target);
404         }
405 }
406
407 static inline void
408 emit_int16 (MonoAotCompile *acfg, int value) 
409
410         img_writer_emit_int16 (acfg->w, value); 
411 }
412
413 static inline void
414 emit_int32 (MonoAotCompile *acfg, int value) 
415
416         img_writer_emit_int32 (acfg->w, value); 
417 }
418
419 static inline void
420 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset) 
421
422         img_writer_emit_symbol_diff (acfg->w, end, start, offset); 
423 }
424
425 static inline void
426 emit_zero_bytes (MonoAotCompile *acfg, int num) 
427
428         img_writer_emit_zero_bytes (acfg->w, num); 
429 }
430
431 static inline void
432 emit_byte (MonoAotCompile *acfg, guint8 val) 
433
434         img_writer_emit_byte (acfg->w, val); 
435 }
436
437 #ifdef __native_client_codegen__
438 static inline void
439 emit_nacl_call_alignment (MonoAotCompile *acfg)
440 {
441         img_writer_emit_nacl_call_alignment (acfg->w);
442 }
443 #endif
444
445 static G_GNUC_UNUSED void
446 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
447 {
448         img_writer_emit_global (acfg->w, name, func);
449 }
450
451 static void
452 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
453 {
454         if (acfg->aot_opts.no_dlsym) {
455                 g_ptr_array_add (acfg->globals, g_strdup (name));
456                 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
457         } else {
458                 img_writer_emit_global (acfg->w, name, func);
459         }
460 }
461
462 static void
463 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
464 {
465         img_writer_emit_symbol_size (acfg->w, name, end_label);
466 }
467
468 static void
469 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
470 {
471         img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
472 #ifdef TARGET_MACH
473         /* On apple, all symbols need to be aligned to avoid warnings from ld */
474         emit_alignment (acfg, 4);
475 #endif
476         img_writer_emit_label (acfg->w, name);
477         img_writer_emit_string (acfg->w, value);
478 }
479
480 static G_GNUC_UNUSED void
481 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
482 {
483         do {
484                 guint8 b = value & 0x7f;
485                 value >>= 7;
486                 if (value != 0) /* more bytes to come */
487                         b |= 0x80;
488                 emit_byte (acfg, b);
489         } while (value);
490 }
491
492 static G_GNUC_UNUSED void
493 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
494 {
495         gboolean more = 1;
496         gboolean negative = (value < 0);
497         guint32 size = 64;
498         guint8 byte;
499
500         while (more) {
501                 byte = value & 0x7f;
502                 value >>= 7;
503                 /* the following is unnecessary if the
504                  * implementation of >>= uses an arithmetic rather
505                  * than logical shift for a signed left operand
506                  */
507                 if (negative)
508                         /* sign extend */
509                         value |= - ((gint64)1 <<(size - 7));
510                 /* sign bit of byte is second high order bit (0x40) */
511                 if ((value == 0 && !(byte & 0x40)) ||
512                         (value == -1 && (byte & 0x40)))
513                         more = 0;
514                 else
515                         byte |= 0x80;
516                 emit_byte (acfg, byte);
517         }
518 }
519
520 static G_GNUC_UNUSED void
521 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
522 {
523         guint8 *p = buf;
524
525         do {
526                 guint8 b = value & 0x7f;
527                 value >>= 7;
528                 if (value != 0) /* more bytes to come */
529                         b |= 0x80;
530                 *p ++ = b;
531         } while (value);
532
533         *endbuf = p;
534 }
535
536 static G_GNUC_UNUSED void
537 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
538 {
539         gboolean more = 1;
540         gboolean negative = (value < 0);
541         guint32 size = 32;
542         guint8 byte;
543         guint8 *p = buf;
544
545         while (more) {
546                 byte = value & 0x7f;
547                 value >>= 7;
548                 /* the following is unnecessary if the
549                  * implementation of >>= uses an arithmetic rather
550                  * than logical shift for a signed left operand
551                  */
552                 if (negative)
553                         /* sign extend */
554                         value |= - (1 <<(size - 7));
555                 /* sign bit of byte is second high order bit (0x40) */
556                 if ((value == 0 && !(byte & 0x40)) ||
557                         (value == -1 && (byte & 0x40)))
558                         more = 0;
559                 else
560                         byte |= 0x80;
561                 *p ++= byte;
562         }
563
564         *endbuf = p;
565 }
566
567 static void
568 emit_unset_mode (MonoAotCompile *acfg)
569 {
570         img_writer_emit_unset_mode (acfg->w);
571 }
572
573 static G_GNUC_UNUSED void
574 emit_set_thumb_mode (MonoAotCompile *acfg)
575 {
576         emit_unset_mode (acfg);
577         fprintf (acfg->fp, ".code 16\n");
578 }
579
580 static G_GNUC_UNUSED void
581 emit_set_arm_mode (MonoAotCompile *acfg)
582 {
583         emit_unset_mode (acfg);
584         fprintf (acfg->fp, ".code 32\n");
585 }
586
587 static inline void
588 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
589 {
590 #ifdef TARGET_ARM64
591         int i;
592
593         g_assert (size % 4 == 0);
594         emit_unset_mode (acfg);
595         for (i = 0; i < size; i += 4)
596                 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
597 #else
598         emit_bytes (acfg, buf, size);
599 #endif
600 }
601
602 /* ARCHITECTURE SPECIFIC CODE */
603
604 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
605 #define EMIT_DWARF_INFO 1
606 #endif
607
608 #if defined(TARGET_ARM)
609 #define AOT_FUNC_ALIGNMENT 4
610 #else
611 #define AOT_FUNC_ALIGNMENT 16
612 #endif
613 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
614 #undef AOT_FUNC_ALIGNMENT
615 #define AOT_FUNC_ALIGNMENT 32
616 #endif
617  
618 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
619 #define PPC_LD_OP "ld"
620 #define PPC_LDX_OP "ldx"
621 #else
622 #define PPC_LD_OP "lwz"
623 #define PPC_LDX_OP "lwzx"
624 #endif
625
626 #ifdef TARGET_AMD64
627 #define AOT_TARGET_STR "AMD64"
628 #endif
629
630 #ifdef TARGET_ARM
631 #ifdef TARGET_MACH
632 #define AOT_TARGET_STR "ARM (MACH)"
633 #else
634 #define AOT_TARGET_STR "ARM (!MACH)"
635 #endif
636 #endif
637
638 #ifdef TARGET_ARM64
639 #ifdef TARGET_MACH
640 #define AOT_TARGET_STR "ARM64 (MACH)"
641 #else
642 #define AOT_TARGET_STR "ARM64 (!MACH)"
643 #endif
644 #endif
645
646 #ifdef TARGET_POWERPC64
647 #ifdef __mono_ilp32__
648 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
649 #else
650 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
651 #endif
652 #else
653 #ifdef TARGET_POWERPC
654 #ifdef __mono_ilp32__
655 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
656 #else
657 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
658 #endif
659 #endif
660 #endif
661
662 #ifdef TARGET_X86
663 #ifdef TARGET_WIN32
664 #define AOT_TARGET_STR "X86 (WIN32)"
665 #elif defined(__native_client_codegen__)
666 #define AOT_TARGET_STR "X86 (native client codegen)"
667 #else
668 #define AOT_TARGET_STR "X86 (!native client codegen)"
669 #endif
670 #endif
671
672 #ifndef AOT_TARGET_STR
673 #define AOT_TARGET_STR ""
674 #endif
675
676 static void
677 arch_init (MonoAotCompile *acfg)
678 {
679         acfg->llc_args = g_string_new ("");
680         acfg->as_args = g_string_new ("");
681
682         /*
683          * The prefix LLVM likes to put in front of symbol names on darwin.
684          * The mach-os specs require this for globals, but LLVM puts them in front of all
685          * symbols. We need to handle this, since we need to refer to LLVM generated
686          * symbols.
687          */
688         acfg->llvm_label_prefix = "";
689         acfg->user_symbol_prefix = "";
690
691 #if defined(TARGET_AMD64)
692         g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
693 #endif
694
695 #ifdef TARGET_ARM
696         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
697                 g_string_append (acfg->llc_args, "-mattr=+v6");
698         } else {
699 #ifdef ARM_FPU_VFP
700                 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
701                 g_string_append (acfg->as_args, " -mfpu=vfp3");
702 #else
703                 g_string_append (acfg->llc_args, " -soft-float");
704 #endif
705         }
706         if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
707                 acfg->thumb_mixed = TRUE;
708
709         if (acfg->aot_opts.mtriple)
710                 mono_arch_set_target (acfg->aot_opts.mtriple);
711 #endif
712
713 #ifdef TARGET_ARM64
714         acfg->inst_directive = ".inst";
715         if (acfg->aot_opts.mtriple)
716                 mono_arch_set_target (acfg->aot_opts.mtriple);
717 #endif
718
719 #ifdef TARGET_MACH
720         acfg->user_symbol_prefix = "_";
721         acfg->llvm_label_prefix = "_";
722         acfg->inst_directive = ".word";
723         acfg->need_no_dead_strip = TRUE;
724         acfg->aot_opts.gnu_asm = TRUE;
725 #endif
726
727 #if defined(__linux__) && !defined(TARGET_ARM)
728         acfg->need_pt_gnu_stack = TRUE;
729 #endif
730
731 #ifdef MONOTOUCH
732         acfg->direct_method_addresses = TRUE;
733         acfg->global_symbols = TRUE;
734 #endif
735 }
736
737 #ifdef TARGET_ARM64
738
739 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
740
741 #endif
742
743 #ifdef MONO_ARCH_AOT_SUPPORTED
744 /*
745  * arch_emit_direct_call:
746  *
747  *   Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
748  * calling code.
749  */
750 static void
751 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
752 {
753 #if defined(TARGET_X86) || defined(TARGET_AMD64)
754         /* Need to make sure this is exactly 5 bytes long */
755         if (external && !acfg->use_bin_writer) {
756                 emit_unset_mode (acfg);
757                 fprintf (acfg->fp, "call %s\n", target);
758         } else {
759                 emit_byte (acfg, '\xe8');
760                 emit_symbol_diff (acfg, target, ".", -4);
761         }
762         *call_size = 5;
763 #elif defined(TARGET_ARM)
764         if (acfg->use_bin_writer) {
765                 guint8 buf [4];
766                 guint8 *code;
767
768                 code = buf;
769                 ARM_BL (code, 0);
770
771                 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
772                 emit_bytes (acfg, buf, 4);
773         } else {
774                 emit_unset_mode (acfg);
775                 if (thumb)
776                         fprintf (acfg->fp, "blx %s\n", target);
777                 else
778                         fprintf (acfg->fp, "bl %s\n", target);
779         }
780         *call_size = 4;
781 #elif defined(TARGET_ARM64)
782         arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
783 #elif defined(TARGET_POWERPC)
784         if (acfg->use_bin_writer) {
785                 g_assert_not_reached ();
786         } else {
787                 emit_unset_mode (acfg);
788                 fprintf (acfg->fp, "bl %s\n", target);
789                 *call_size = 4;
790         }
791 #else
792         g_assert_not_reached ();
793 #endif
794 }
795 #endif
796
797 /*
798  * PPC32 design:
799  * - we use an approach similar to the x86 abi: reserve a register (r30) to hold 
800  *   the GOT pointer.
801  * - The full-aot trampolines need access to the GOT of mscorlib, so we store
802  *   in in the 2. slot of every GOT, and require every method to place the GOT
803  *   address in r30, even when it doesn't access the GOT otherwise. This way,
804  *   the trampolines can compute the mscorlib GOT address by loading 4(r30).
805  */
806
807 /*
808  * PPC64 design:
809  * PPC64 uses function descriptors which greatly complicate all code, since
810  * these are used very inconsistently in the runtime. Some functions like 
811  * mono_compile_method () return ftn descriptors, while others like the
812  * trampoline creation functions do not.
813  * We assume that all GOT slots contain function descriptors, and create 
814  * descriptors in aot-runtime.c when needed.
815  * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
816  * from function descriptors, we could do the same, but it would require 
817  * rewriting all the ppc/aot code to handle function descriptors properly.
818  * So instead, we use the same approach as on PPC32.
819  * This is a horrible mess, but fixing it would probably lead to an even bigger
820  * one.
821  */
822
823 /*
824  * X86 design:
825  * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
826  */
827
828 #ifdef MONO_ARCH_AOT_SUPPORTED
829 /*
830  * arch_emit_got_offset:
831  *
832  *   The memory pointed to by CODE should hold native code for computing the GOT
833  * address. Emit this code while patching it with the offset between code and
834  * the GOT. CODE_SIZE is set to the number of bytes emitted.
835  */
836 static void
837 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
838 {
839 #if defined(TARGET_POWERPC64)
840         g_assert (!acfg->use_bin_writer);
841         emit_unset_mode (acfg);
842         /* 
843          * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
844          * unsupported relocations. So we store the got address into the .Lgot_addr
845          * symbol which is in the text segment, compute its address, and load it.
846          */
847         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
848         fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
849         fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
850         fprintf (acfg->fp, "add 30, 30, 0\n");
851         fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
852         acfg->label_generator ++;
853         *code_size = 16;
854 #elif defined(TARGET_POWERPC)
855         g_assert (!acfg->use_bin_writer);
856         emit_unset_mode (acfg);
857         fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
858         fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
859         fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
860         acfg->label_generator ++;
861         *code_size = 8;
862 #else
863         guint32 offset = mono_arch_get_patch_offset (code);
864         emit_bytes (acfg, code, offset);
865         emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
866
867         *code_size = offset + 4;
868 #endif
869 }
870
871 /*
872  * arch_emit_got_access:
873  *
874  *   The memory pointed to by CODE should hold native code for loading a GOT
875  * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
876  * CODE_SIZE is set to the number of bytes emitted.
877  */
878 static void
879 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
880 {
881         /* Emit beginning of instruction */
882         emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
883
884         /* Emit the offset */
885 #ifdef TARGET_AMD64
886         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
887         *code_size = mono_arch_get_patch_offset (code) + 4;
888 #elif defined(TARGET_X86)
889         emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
890         *code_size = mono_arch_get_patch_offset (code) + 4;
891 #elif defined(TARGET_ARM)
892         emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
893         *code_size = mono_arch_get_patch_offset (code) + 4;
894 #elif defined(TARGET_ARM64)
895         arm64_emit_got_access (acfg, code, got_slot, code_size);
896 #elif defined(TARGET_POWERPC)
897         {
898                 guint8 buf [32];
899                 guint8 *code;
900
901                 code = buf;
902                 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
903                 g_assert (code - buf == 8);
904                 emit_bytes (acfg, buf, code - buf);
905                 *code_size = code - buf;
906         }
907 #else
908         g_assert_not_reached ();
909 #endif
910 }
911
912 #endif
913
914 #ifdef MONO_ARCH_AOT_SUPPORTED
915 /*
916  * arch_emit_objc_selector_ref:
917  *
918  *   Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
919  */
920 static void
921 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
922 {
923 #if defined(TARGET_ARM)
924         char symbol1 [256];
925         char symbol2 [256];
926         int lindex = acfg->objc_selector_index_2 ++;
927
928         /* Emit ldr.imm/b */
929         emit_bytes (acfg, code, 8);
930
931         sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
932         sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
933
934         emit_label (acfg, symbol1);
935         img_writer_emit_unset_mode (acfg->w);
936         fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
937
938         *code_size = 12;
939 #elif defined(TARGET_ARM64)
940         arm64_emit_objc_selector_ref (acfg, code, index, code_size);
941 #else
942         g_assert_not_reached ();
943 #endif
944 }
945 #endif
946
947 /*
948  * arch_emit_plt_entry:
949  *
950  *   Emit code for the PLT entry with index INDEX.
951  */
952 static void
953 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
954 {
955 #if defined(TARGET_X86)
956                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
957 #if defined(__default_codegen__)
958                 /* jmp *<offset>(%ebx) */
959                 emit_byte (acfg, 0xff);
960                 emit_byte (acfg, 0xa3);
961                 emit_int32 (acfg, offset);
962                 /* Used by mono_aot_get_plt_info_offset */
963                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
964 #elif defined(__native_client_codegen__)
965                 const guint8 kSizeOfNaClJmp = 11;
966                 guint8 bytes[kSizeOfNaClJmp];
967                 guint8 *pbytes = &bytes[0];
968                 
969                 x86_jump_membase32 (pbytes, X86_EBX, offset);
970                 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
971                 /* four bytes of data, used by mono_arch_patch_plt_entry              */
972                 /* For Native Client, make this work with data embedded in push.      */
973                 emit_byte (acfg, 0x68);  /* hide data in a push */
974                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
975                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
976 #endif /*__native_client_codegen__*/
977 #elif defined(TARGET_AMD64)
978 #if defined(__default_codegen__)
979                 /*
980                  * We can't emit jumps because they are 32 bits only so they can't be patched.
981                  * So we make indirect calls through GOT entries which are patched by the AOT 
982                  * loader to point to .Lpd entries. 
983                  */
984                 /* jmpq *<offset>(%rip) */
985                 emit_byte (acfg, '\xff');
986                 emit_byte (acfg, '\x25');
987                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
988                 /* Used by mono_aot_get_plt_info_offset */
989                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
990                 acfg->stats.plt_size += 10;
991 #elif defined(__native_client_codegen__)
992                 guint8 buf [256];
993                 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
994                 guint8 *code = buf_aligned;
995
996                 /* mov <OFFSET>(%rip), %r11d */
997                 emit_byte (acfg, '\x45');
998                 emit_byte (acfg, '\x8b');
999                 emit_byte (acfg, '\x1d');
1000                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
1001
1002                 amd64_jump_reg (code, AMD64_R11);
1003                 /* This should be constant for the plt patch */
1004                 g_assert ((size_t)(code-buf_aligned) == 10);
1005                 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1006
1007                 /* Hide data in a push imm32 so it passes validation */
1008                 emit_byte (acfg, 0x68);  /* push */
1009                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1010                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1011 #endif /*__native_client_codegen__*/
1012 #elif defined(TARGET_ARM)
1013                 guint8 buf [256];
1014                 guint8 *code;
1015
1016                 code = buf;
1017                 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1018                 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1019                 emit_bytes (acfg, buf, code - buf);
1020                 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1021                 /* Used by mono_aot_get_plt_info_offset */
1022                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1023 #elif defined(TARGET_ARM64)
1024                 arm64_emit_plt_entry (acfg, index);
1025 #elif defined(TARGET_POWERPC)
1026                 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1027
1028                 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1029                 g_assert (!acfg->use_bin_writer);
1030                 emit_unset_mode (acfg);
1031                 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1032                 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1033                 fprintf (acfg->fp, "add 11, 11, 30\n");
1034                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1035 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1036                 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1037                 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1038 #endif
1039                 fprintf (acfg->fp, "mtctr 11\n");
1040                 fprintf (acfg->fp, "bctr\n");
1041                 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1042 #else
1043                 g_assert_not_reached ();
1044 #endif
1045 }
1046
1047 static void
1048 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1049 {
1050 #if defined(TARGET_ARM)
1051 #if 0
1052         /* LLVM calls the PLT entries using bl, so emit a stub */
1053         /* FIXME: Too much overhead on every call */
1054         fprintf (acfg->fp, ".thumb_func\n");
1055         fprintf (acfg->fp, "bx pc\n");
1056         fprintf (acfg->fp, "nop\n");
1057         fprintf (acfg->fp, ".arm\n");
1058 #endif
1059         /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1060         /* The caller already transitioned to thumb */
1061         /* The code below should be 12 bytes long */
1062         /* clang has trouble encoding these instructions, so emit the binary */
1063 #if 0
1064         fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1065         /* thumb can't encode ld pc, [pc, ip] */
1066         fprintf (acfg->fp, "add ip, pc, ip\n");
1067         fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1068         fprintf (acfg->fp, "bx ip\n");
1069 #endif
1070         emit_set_thumb_mode (acfg);
1071         fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1072         fprintf (acfg->fp, ".2byte 0x44fc\n");
1073         fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1074         fprintf (acfg->fp, ".2byte 0x4760\n");
1075         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1076         emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1077         emit_unset_mode (acfg);
1078         emit_set_arm_mode (acfg);
1079 #else
1080         g_assert_not_reached ();
1081 #endif
1082 }
1083
1084 /*
1085  * arch_emit_specific_trampoline_pages:
1086  *
1087  * Emits a page full of trampolines: each trampoline uses its own address to
1088  * lookup both the generic trampoline code and the data argument.
1089  * This page can be remapped in process multiple times so we can get an
1090  * unlimited number of trampolines.
1091  * Specifically this implementation uses the following trick: two memory pages
1092  * are allocated, with the first containing the data and the second containing the trampolines.
1093  * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1094  * implementation does all the lifting.
1095  * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1096  * on the arm 32 bit system.
1097  */
1098 static void
1099 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1100 {
1101 #if defined(TARGET_ARM)
1102         guint8 buf [128];
1103         guint8 *code;
1104         guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1105         int i;
1106 #define COMMON_TRAMP_SIZE 16
1107         int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1108         int imm8, rot_amount;
1109         char symbol [128];
1110
1111         if (!acfg->aot_opts.use_trampolines_page)
1112                 return;
1113
1114         acfg->tramp_page_size = mono_pagesize ();
1115
1116         sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1117         emit_alignment (acfg, mono_pagesize ());
1118         emit_global (acfg, symbol, TRUE);
1119         emit_label (acfg, symbol);
1120
1121         /* emit the generic code first, the trampoline address + 8 is in the lr register */
1122         code = buf;
1123         imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1124         ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1125         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1126         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1127         ARM_NOP (code);
1128         g_assert (code - buf == COMMON_TRAMP_SIZE);
1129
1130         /* Emit it */
1131         emit_bytes (acfg, buf, code - buf);
1132
1133         for (i = 0; i < count; ++i) {
1134                 code = buf;
1135                 ARM_PUSH (code, 0x5fff);
1136                 ARM_BL (code, 0);
1137                 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1138                 g_assert (code - buf == 8);
1139                 emit_bytes (acfg, buf, code - buf);
1140         }
1141
1142         /* now the rgctx trampolines: each specific trampolines puts in the ip register
1143          * the instruction pointer address, so the generic trampoline at the start of the page
1144          * subtracts 4096 to get to the data page and loads the values
1145          * We again fit the generic trampiline in 16 bytes.
1146          */
1147         sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1148         emit_global (acfg, symbol, TRUE);
1149         emit_label (acfg, symbol);
1150         code = buf;
1151         imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1152         ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1153         ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1154         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1155         ARM_NOP (code);
1156         g_assert (code - buf == COMMON_TRAMP_SIZE);
1157
1158         /* Emit it */
1159         emit_bytes (acfg, buf, code - buf);
1160
1161         for (i = 0; i < count; ++i) {
1162                 code = buf;
1163                 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1164                 ARM_B (code, 0);
1165                 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1166                 g_assert (code - buf == 8);
1167                 emit_bytes (acfg, buf, code - buf);
1168         }
1169
1170         /*
1171          * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1172          */
1173         sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1174         emit_global (acfg, symbol, TRUE);
1175         emit_label (acfg, symbol);
1176         code = buf;
1177         ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1178         imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1179         ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1180         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1181         ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1182         g_assert (code - buf == COMMON_TRAMP_SIZE);
1183         /* Emit it */
1184         emit_bytes (acfg, buf, code - buf);
1185
1186         for (i = 0; i < count; ++i) {
1187                 code = buf;
1188                 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1189                 ARM_B (code, 0);
1190                 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1191                 g_assert (code - buf == 8);
1192                 emit_bytes (acfg, buf, code - buf);
1193         }
1194
1195         /* now the imt trampolines: each specific trampolines puts in the ip register
1196          * the instruction pointer address, so the generic trampoline at the start of the page
1197          * subtracts 4096 to get to the data page and loads the values
1198          * We again fit the generic trampiline in 16 bytes.
1199          */
1200 #define IMT_TRAMP_SIZE 72
1201         sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1202         emit_global (acfg, symbol, TRUE);
1203         emit_label (acfg, symbol);
1204         code = buf;
1205         /* Need at least two free registers, plus a slot for storing the pc */
1206         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1207
1208         imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1209         ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1210         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1211
1212         /* The IMT method is in v5, r0 has the imt array address */
1213
1214         loop_start = code;
1215         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1216         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1217         imt_found_check = code;
1218         ARM_B_COND (code, ARMCOND_EQ, 0);
1219
1220         /* End-of-loop check */
1221         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1222         loop_end_check = code;
1223         ARM_B_COND (code, ARMCOND_EQ, 0);
1224
1225         /* Loop footer */
1226         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1227         loop_branch_back = code;
1228         ARM_B (code, 0);
1229         arm_patch (loop_branch_back, loop_start);
1230
1231         /* Match */
1232         arm_patch (imt_found_check, code);
1233         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1234         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1235         /* Save it to the third stack slot */
1236         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1237         /* Restore the registers and branch */
1238         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1239
1240         /* No match */
1241         arm_patch (loop_end_check, code);
1242         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1243         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1244         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1245         ARM_NOP (code);
1246
1247         /* Emit it */
1248         g_assert (code - buf == IMT_TRAMP_SIZE);
1249         emit_bytes (acfg, buf, code - buf);
1250
1251         for (i = 0; i < count; ++i) {
1252                 code = buf;
1253                 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1254                 ARM_B (code, 0);
1255                 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1256                 g_assert (code - buf == 8);
1257                 emit_bytes (acfg, buf, code - buf);
1258         }
1259 #elif defined(TARGET_ARM64)
1260         arm64_emit_specific_trampoline_pages (acfg);
1261 #endif
1262 }
1263
1264 /*
1265  * arch_emit_specific_trampoline:
1266  *
1267  *   Emit code for a specific trampoline. OFFSET is the offset of the first of
1268  * two GOT slots which contain the generic trampoline address and the trampoline
1269  * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1270  */
1271 static void
1272 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1273 {
1274         /*
1275          * The trampolines created here are variations of the specific 
1276          * trampolines created in mono_arch_create_specific_trampoline (). The 
1277          * differences are:
1278          * - the generic trampoline address is taken from a got slot.
1279          * - the offset of the got slot where the trampoline argument is stored
1280          *   is embedded in the instruction stream, and the generic trampoline
1281          *   can load the argument by loading the offset, adding it to the
1282          *   address of the trampoline to get the address of the got slot, and
1283          *   loading the argument from there.
1284          * - all the trampolines should be of the same length.
1285          */
1286 #if defined(TARGET_AMD64)
1287 #if defined(__default_codegen__)
1288         /* This should be exactly 16 bytes long */
1289         *tramp_size = 16;
1290         /* call *<offset>(%rip) */
1291         emit_byte (acfg, '\x41');
1292         emit_byte (acfg, '\xff');
1293         emit_byte (acfg, '\x15');
1294         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1295         /* This should be relative to the start of the trampoline */
1296         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1297         emit_zero_bytes (acfg, 5);
1298 #elif defined(__native_client_codegen__)
1299         guint8 buf [256];
1300         guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1301         guint8 *code = buf_aligned;
1302         guint8 *call_start;
1303         size_t call_len;
1304         int got_offset;
1305
1306         /* Emit this call in 'code' so we can find out how long it is. */
1307         amd64_call_reg (code, AMD64_R11);
1308         call_start = mono_arch_nacl_skip_nops (buf_aligned);
1309         call_len = code - call_start;
1310
1311         /* The tramp_size is twice the NaCl alignment because it starts with */ 
1312         /* a call which needs to be aligned to the end of the boundary.      */
1313         *tramp_size = kNaClAlignment*2;
1314         {
1315                 /* Emit nops to align call site below which is 7 bytes plus */
1316                 /* the length of the call sequence emitted above.           */
1317                 /* Note: this requires the specific trampoline starts on a  */
1318                 /* kNaclAlignedment aligned address, which it does because  */
1319                 /* it's its own function that is aligned.                   */
1320                 guint8 nop_buf[256];
1321                 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1322                 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1323                 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1324         }
1325         /* The trampoline is stored at the offset'th pointer, the -4 is  */
1326         /* present because RIP relative addressing starts at the end of  */
1327         /* the current instruction, while the label "." is relative to   */
1328         /* the beginning of the current asm location, which in this case */
1329         /* is not the mov instruction, but the offset itself, due to the */
1330         /* way the bytes and ints are emitted here.                      */
1331         got_offset = (offset * sizeof(gpointer)) - 4;
1332
1333         /* mov <OFFSET>(%rip), %r11d */
1334         emit_byte (acfg, '\x45');
1335         emit_byte (acfg, '\x8b');
1336         emit_byte (acfg, '\x1d');
1337         emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1338
1339         /* naclcall %r11 */
1340         emit_bytes (acfg, call_start, call_len);
1341
1342         /* The arg is stored at the offset+1 pointer, relative to beginning */
1343         /* of trampoline: 7 for mov, plus the call length, and 1 for push.  */
1344         got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1345
1346         /* We can't emit this data directly, hide in a "push imm32" */
1347         emit_byte (acfg, '\x68'); /* push */
1348         emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1349         emit_alignment (acfg, kNaClAlignment);
1350 #endif /*__native_client_codegen__*/
1351 #elif defined(TARGET_ARM)
1352         guint8 buf [128];
1353         guint8 *code;
1354
1355         /* This should be exactly 20 bytes long */
1356         *tramp_size = 20;
1357         code = buf;
1358         ARM_PUSH (code, 0x5fff);
1359         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1360         /* Load the value from the GOT */
1361         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1362         /* Branch to it */
1363         ARM_BLX_REG (code, ARMREG_R1);
1364
1365         g_assert (code - buf == 16);
1366
1367         /* Emit it */
1368         emit_bytes (acfg, buf, code - buf);
1369         /* 
1370          * Only one offset is needed, since the second one would be equal to the
1371          * first one.
1372          */
1373         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1374         //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1375 #elif defined(TARGET_ARM64)
1376         arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1377 #elif defined(TARGET_POWERPC)
1378         guint8 buf [128];
1379         guint8 *code;
1380
1381         *tramp_size = 4;
1382         code = buf;
1383
1384         g_assert (!acfg->use_bin_writer);
1385
1386         /*
1387          * PPC has no ip relative addressing, so we need to compute the address
1388          * of the mscorlib got. That is slow and complex, so instead, we store it
1389          * in the second got slot of every aot image. The caller already computed
1390          * the address of its got and placed it into r30.
1391          */
1392         emit_unset_mode (acfg);
1393         /* Load mscorlib got address */
1394         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1395         /* Load generic trampoline address */
1396         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1397         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1398         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1399 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1400         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1401 #endif
1402         fprintf (acfg->fp, "mtctr 11\n");
1403         /* Load trampoline argument */
1404         /* On ppc, we pass it normally to the generic trampoline */
1405         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1406         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1407         fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1408         /* Branch to generic trampoline */
1409         fprintf (acfg->fp, "bctr\n");
1410
1411 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1412         *tramp_size = 10 * 4;
1413 #else
1414         *tramp_size = 9 * 4;
1415 #endif
1416 #elif defined(TARGET_X86)
1417         guint8 buf [128];
1418         guint8 *code;
1419
1420         /* Similar to the PPC code above */
1421
1422         /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1423
1424         /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1425 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1426         g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1427 #endif
1428
1429         code = buf;
1430         /* Load mscorlib got address */
1431         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1432         /* Push trampoline argument */
1433         x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1434         /* Load generic trampoline address */
1435         x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1436         /* Branch to generic trampoline */
1437         x86_jump_reg (code, X86_ECX);
1438
1439 #ifdef __native_client_codegen__
1440         {
1441                 /* emit nops to next 32 byte alignment */
1442                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1443                 while (code < (buf + a)) x86_nop(code);
1444         }
1445 #endif
1446         emit_bytes (acfg, buf, code - buf);
1447
1448         *tramp_size = NACL_SIZE(17, kNaClAlignment);
1449         g_assert (code - buf == *tramp_size);
1450 #else
1451         g_assert_not_reached ();
1452 #endif
1453 }
1454
1455 /*
1456  * arch_emit_unbox_trampoline:
1457  *
1458  *   Emit code for the unbox trampoline for METHOD used in the full-aot case.
1459  * CALL_TARGET is the symbol pointing to the native code of METHOD.
1460  */
1461 static void
1462 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1463 {
1464 #if defined(TARGET_AMD64)
1465         guint8 buf [32];
1466         guint8 *code;
1467         int this_reg;
1468
1469         this_reg = mono_arch_get_this_arg_reg (NULL);
1470         code = buf;
1471         amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1472
1473         emit_bytes (acfg, buf, code - buf);
1474         /* jump <method> */
1475         emit_byte (acfg, '\xe9');
1476         emit_symbol_diff (acfg, call_target, ".", -4);
1477 #elif defined(TARGET_X86)
1478         guint8 buf [32];
1479         guint8 *code;
1480         int this_pos = 4;
1481
1482         code = buf;
1483
1484         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1485
1486         emit_bytes (acfg, buf, code - buf);
1487
1488         /* jump <method> */
1489         emit_byte (acfg, '\xe9');
1490         emit_symbol_diff (acfg, call_target, ".", -4);
1491 #elif defined(TARGET_ARM)
1492         guint8 buf [128];
1493         guint8 *code;
1494
1495         if (acfg->thumb_mixed && cfg->compile_llvm) {
1496                 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1497                 fprintf (acfg->fp, "b %s\n", call_target);
1498                 fprintf (acfg->fp, ".arm\n");
1499                 fprintf (acfg->fp, ".align 2\n");
1500                 return;
1501         }
1502
1503         code = buf;
1504
1505         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1506
1507         emit_bytes (acfg, buf, code - buf);
1508         /* jump to method */
1509         if (acfg->use_bin_writer) {
1510                 guint8 buf [4];
1511                 guint8 *code;
1512
1513                 code = buf;
1514                 ARM_B (code, 0);
1515
1516                 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1517                 emit_bytes (acfg, buf, 4);
1518         } else {
1519                 if (acfg->thumb_mixed && cfg->compile_llvm)
1520                         fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1521                 else
1522                         fprintf (acfg->fp, "\n\tb %s\n", call_target);
1523         }
1524 #elif defined(TARGET_ARM64)
1525         arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1526 #elif defined(TARGET_POWERPC)
1527         int this_pos = 3;
1528
1529         g_assert (!acfg->use_bin_writer);
1530
1531         fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1532         fprintf (acfg->fp, "\n\tb %s\n", call_target);
1533 #else
1534         g_assert_not_reached ();
1535 #endif
1536 }
1537
1538 /*
1539  * arch_emit_static_rgctx_trampoline:
1540  *
1541  *   Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1542  * two GOT slots which contain the rgctx argument, and the method to jump to.
1543  * TRAMP_SIZE is set to the size of the emitted trampoline.
1544  * These kinds of trampolines cannot be enumerated statically, since there could
1545  * be one trampoline per method instantiation, so we emit the same code for all
1546  * trampolines, and parameterize them using two GOT slots.
1547  */
1548 static void
1549 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1550 {
1551 #if defined(TARGET_AMD64)
1552 #if defined(__default_codegen__)
1553         /* This should be exactly 13 bytes long */
1554         *tramp_size = 13;
1555
1556         /* mov <OFFSET>(%rip), %r10 */
1557         emit_byte (acfg, '\x4d');
1558         emit_byte (acfg, '\x8b');
1559         emit_byte (acfg, '\x15');
1560         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1561
1562         /* jmp *<offset>(%rip) */
1563         emit_byte (acfg, '\xff');
1564         emit_byte (acfg, '\x25');
1565         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1566 #elif defined(__native_client_codegen__)
1567         guint8 buf [128];
1568         guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1569         guint8 *code = buf_aligned;
1570
1571         /* mov <OFFSET>(%rip), %r10d */
1572         emit_byte (acfg, '\x45');
1573         emit_byte (acfg, '\x8b');
1574         emit_byte (acfg, '\x15');
1575         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1576
1577         /* mov <OFFSET>(%rip), %r11d */
1578         emit_byte (acfg, '\x45');
1579         emit_byte (acfg, '\x8b');
1580         emit_byte (acfg, '\x1d');
1581         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1582
1583         /* nacljmp *%r11 */
1584         amd64_jump_reg (code, AMD64_R11);
1585         emit_bytes (acfg, buf_aligned, code - buf_aligned);
1586
1587         emit_alignment (acfg, kNaClAlignment);
1588         *tramp_size = kNaClAlignment;
1589 #endif /*__native_client_codegen__*/
1590
1591 #elif defined(TARGET_ARM)
1592         guint8 buf [128];
1593         guint8 *code;
1594
1595         /* This should be exactly 24 bytes long */
1596         *tramp_size = 24;
1597         code = buf;
1598         /* Load rgctx value */
1599         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1600         ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1601         /* Load branch addr + branch */
1602         ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1603         ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1604
1605         g_assert (code - buf == 16);
1606
1607         /* Emit it */
1608         emit_bytes (acfg, buf, code - buf);
1609         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1610         emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1611 #elif defined(TARGET_ARM64)
1612         arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1613 #elif defined(TARGET_POWERPC)
1614         guint8 buf [128];
1615         guint8 *code;
1616
1617         *tramp_size = 4;
1618         code = buf;
1619
1620         g_assert (!acfg->use_bin_writer);
1621
1622         /*
1623          * PPC has no ip relative addressing, so we need to compute the address
1624          * of the mscorlib got. That is slow and complex, so instead, we store it
1625          * in the second got slot of every aot image. The caller already computed
1626          * the address of its got and placed it into r30.
1627          */
1628         emit_unset_mode (acfg);
1629         /* Load mscorlib got address */
1630         fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1631         /* Load rgctx */
1632         fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1633         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1634         fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1635         /* Load target address */
1636         fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1637         fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1638         fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1639 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1640         fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1641         fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1642 #endif
1643         fprintf (acfg->fp, "mtctr 11\n");
1644         /* Branch to the target address */
1645         fprintf (acfg->fp, "bctr\n");
1646
1647 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1648         *tramp_size = 11 * 4;
1649 #else
1650         *tramp_size = 9 * 4;
1651 #endif
1652
1653 #elif defined(TARGET_X86)
1654         guint8 buf [128];
1655         guint8 *code;
1656
1657         /* Similar to the PPC code above */
1658
1659         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1660
1661         code = buf;
1662         /* Load mscorlib got address */
1663         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1664         /* Load arg */
1665         x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1666         /* Branch to the target address */
1667         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1668
1669 #ifdef __native_client_codegen__
1670         {
1671                 /* emit nops to next 32 byte alignment */
1672                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1673                 while (code < (buf + a)) x86_nop(code);
1674         }
1675 #endif
1676
1677         emit_bytes (acfg, buf, code - buf);
1678
1679         *tramp_size = NACL_SIZE (15, kNaClAlignment);
1680         g_assert (code - buf == *tramp_size);
1681 #else
1682         g_assert_not_reached ();
1683 #endif
1684 }       
1685
1686 /*
1687  * arch_emit_imt_thunk:
1688  *
1689  *   Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1690  * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1691  * key is the IMT key, and ptr holds the address of a memory location holding
1692  * the address to branch to if the IMT arg matches the key. The array is 
1693  * terminated by a pair whose key is NULL, and whose ptr is the address of the 
1694  * fail_tramp.
1695  * TRAMP_SIZE is set to the size of the emitted trampoline.
1696  */
1697 static void
1698 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1699 {
1700 #if defined(TARGET_AMD64)
1701         guint8 *buf, *code;
1702 #if defined(__native_client_codegen__)
1703         guint8 *buf_alloc;
1704 #endif
1705         guint8 *labels [16];
1706         guint8 mov_buf[3];
1707         guint8 *mov_buf_ptr = mov_buf;
1708
1709         const int kSizeOfMove = 7;
1710 #if defined(__default_codegen__)
1711         code = buf = g_malloc (256);
1712 #elif defined(__native_client_codegen__)
1713         buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1714         buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1715         /* The RIP relative move below is emitted first */
1716         buf += kSizeOfMove;
1717         code = buf;
1718 #endif
1719
1720         /* FIXME: Optimize this, i.e. use binary search etc. */
1721         /* Maybe move the body into a separate function (slower, but much smaller) */
1722
1723         /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1724
1725         labels [0] = code;
1726         amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1727         labels [1] = code;
1728         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1729
1730         /* Check key */
1731         amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1732         labels [2] = code;
1733         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1734
1735         /* Loop footer */
1736         amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1737         amd64_jump_code (code, labels [0]);
1738
1739         /* Match */
1740         mono_amd64_patch (labels [2], code);
1741         amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1742         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1743
1744         /* No match */
1745         mono_amd64_patch (labels [1], code);
1746         /* Load fail tramp */
1747         amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1748         /* Check if there is a fail tramp */
1749         amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1750         labels [3] = code;
1751         amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1752         /* Jump to fail tramp */
1753         amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1754
1755         /* Fail */
1756         mono_amd64_patch (labels [3], code);
1757         x86_breakpoint (code);
1758
1759         /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1760         amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1761         *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1762         x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1763         emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1764         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1765
1766         emit_bytes (acfg, buf, code - buf);
1767         
1768         *tramp_size = code - buf + kSizeOfMove;
1769 #if defined(__native_client_codegen__)
1770         /* The tramp will be padded to the next kNaClAlignment bundle. */
1771         *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1772 #endif
1773
1774 #if defined(__default_codegen__)
1775         g_free (buf);
1776 #elif defined(__native_client_codegen__)
1777         g_free (buf_alloc); 
1778 #endif
1779
1780 #elif defined(TARGET_X86)
1781         guint8 *buf, *code;
1782 #ifdef __native_client_codegen__
1783         guint8 *buf_alloc;
1784 #endif
1785         guint8 *labels [16];
1786
1787 #if defined(__default_codegen__)
1788         code = buf = g_malloc (256);
1789 #elif defined(__native_client_codegen__)
1790         buf_alloc = g_malloc (256 + kNaClAlignment);
1791         code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1792 #endif
1793
1794         /* Allocate a temporary stack slot */
1795         x86_push_reg (code, X86_EAX);
1796         /* Save EAX */
1797         x86_push_reg (code, X86_EAX);
1798
1799         /* Load mscorlib got address */
1800         x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1801         /* Load arg */
1802         x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1803
1804         labels [0] = code;
1805         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1806         labels [1] = code;
1807         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1808
1809         /* Check key */
1810         x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1811         labels [2] = code;
1812         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1813
1814         /* Loop footer */
1815         x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1816         x86_jump_code (code, labels [0]);
1817
1818         /* Match */
1819         mono_x86_patch (labels [2], code);
1820         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1821         x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1822         /* Save the target address to the temporary stack location */
1823         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1824         /* Restore EAX */
1825         x86_pop_reg (code, X86_EAX);
1826         /* Jump to the target address */
1827         x86_ret (code);
1828
1829         /* No match */
1830         mono_x86_patch (labels [1], code);
1831         /* Load fail tramp */
1832         x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1833         x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1834         labels [3] = code;
1835         x86_branch8 (code, X86_CC_Z, FALSE, 0);
1836         /* Jump to fail tramp */
1837         x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1838         x86_pop_reg (code, X86_EAX);
1839         x86_ret (code);
1840
1841         /* Fail */
1842         mono_x86_patch (labels [3], code);
1843         x86_breakpoint (code);
1844
1845 #ifdef __native_client_codegen__
1846         {
1847                 /* emit nops to next 32 byte alignment */
1848                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1849                 while (code < (buf + a)) x86_nop(code);
1850         }
1851 #endif
1852         emit_bytes (acfg, buf, code - buf);
1853         
1854         *tramp_size = code - buf;
1855
1856 #if defined(__default_codegen__)
1857         g_free (buf);
1858 #elif defined(__native_client_codegen__)
1859         g_free (buf_alloc); 
1860 #endif
1861
1862 #elif defined(TARGET_ARM)
1863         guint8 buf [128];
1864         guint8 *code, *code2, *labels [16];
1865
1866         code = buf;
1867
1868         /* The IMT method is in v5 */
1869
1870         /* Need at least two free registers, plus a slot for storing the pc */
1871         ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1872         labels [0] = code;
1873         /* Load the parameter from the GOT */
1874         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1875         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1876
1877         labels [1] = code;
1878         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1879         ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1880         labels [2] = code;
1881         ARM_B_COND (code, ARMCOND_EQ, 0);
1882
1883         /* End-of-loop check */
1884         ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1885         labels [3] = code;
1886         ARM_B_COND (code, ARMCOND_EQ, 0);
1887
1888         /* Loop footer */
1889         ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1890         labels [4] = code;
1891         ARM_B (code, 0);
1892         arm_patch (labels [4], labels [1]);
1893
1894         /* Match */
1895         arm_patch (labels [2], code);
1896         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1897         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1898         /* Save it to the third stack slot */
1899         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1900         /* Restore the registers and branch */
1901         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1902
1903         /* No match */
1904         arm_patch (labels [3], code);
1905         ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1906         ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1907         ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1908
1909         /* Fixup offset */
1910         code2 = labels [0];
1911         ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1912
1913         emit_bytes (acfg, buf, code - buf);
1914         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1915
1916         *tramp_size = code - buf + 4;
1917 #elif defined(TARGET_ARM64)
1918         arm64_emit_imt_thunk (acfg, offset, tramp_size);
1919 #elif defined(TARGET_POWERPC)
1920         guint8 buf [128];
1921         guint8 *code, *labels [16];
1922
1923         code = buf;
1924
1925         /* Load the mscorlib got address */
1926         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1927         /* Load the parameter from the GOT */
1928         ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1929         ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1930
1931         /* Load and check key */
1932         labels [1] = code;
1933         ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1934         ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1935         labels [2] = code;
1936         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1937
1938         /* End-of-loop check */
1939         ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1940         labels [3] = code;
1941         ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1942
1943         /* Loop footer */
1944         ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1945         labels [4] = code;
1946         ppc_b (code, 0);
1947         mono_ppc_patch (labels [4], labels [1]);
1948
1949         /* Match */
1950         mono_ppc_patch (labels [2], code);
1951         ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1952         /* r11 now contains the value of the vtable slot */
1953         /* this is not a function descriptor on ppc64 */
1954         ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1955         ppc_mtctr (code, ppc_r11);
1956         ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1957
1958         /* Fail */
1959         mono_ppc_patch (labels [3], code);
1960         /* FIXME: */
1961         ppc_break (code);
1962
1963         *tramp_size = code - buf;
1964
1965         emit_bytes (acfg, buf, code - buf);
1966 #else
1967         g_assert_not_reached ();
1968 #endif
1969 }
1970
1971 /*
1972  * arch_emit_gsharedvt_arg_trampoline:
1973  *
1974  *   Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1975  * two GOT slots which contain the argument, and the code to jump to.
1976  * TRAMP_SIZE is set to the size of the emitted trampoline.
1977  * These kinds of trampolines cannot be enumerated statically, since there could
1978  * be one trampoline per method instantiation, so we emit the same code for all
1979  * trampolines, and parameterize them using two GOT slots.
1980  */
1981 static void
1982 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1983 {
1984 #if defined(TARGET_X86)
1985         guint8 buf [128];
1986         guint8 *code;
1987
1988         /* Similar to the PPC code above */
1989
1990         g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1991
1992         code = buf;
1993         /* Load mscorlib got address */
1994         x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1995         /* Load arg */
1996         x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1997         /* Branch to the target address */
1998         x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1999
2000 #ifdef __native_client_codegen__
2001         {
2002                 /* emit nops to next 32 byte alignment */
2003                 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2004                 while (code < (buf + a)) x86_nop(code);
2005         }
2006 #endif
2007
2008         emit_bytes (acfg, buf, code - buf);
2009
2010         *tramp_size = NACL_SIZE (15, kNaClAlignment);
2011         g_assert (code - buf == *tramp_size);
2012 #elif defined(TARGET_ARM)
2013         guint8 buf [128];
2014         guint8 *code;
2015
2016         /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2017         /* Similar to arch_emit_specific_trampoline () */
2018         *tramp_size = 24;
2019         code = buf;
2020         ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2021         ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2022         /* Load the arg value from the GOT */
2023         ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2024         /* Load the addr from the GOT */
2025         ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2026         /* Branch to it */
2027         ARM_BX (code, ARMREG_R1);
2028
2029         g_assert (code - buf == 20);
2030
2031         /* Emit it */
2032         emit_bytes (acfg, buf, code - buf);
2033         emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2034 #elif defined(TARGET_ARM64)
2035         arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2036 #else
2037         g_assert_not_reached ();
2038 #endif
2039 }       
2040
2041 static void
2042 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2043 {
2044 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2045         /* Based on code generated by gcc */
2046         emit_unset_mode (acfg);
2047
2048         fprintf (acfg->fp,
2049 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
2050                          ".section      .ctors,\"aw\",@progbits\n"
2051                          ".align 2\n"
2052                          ".globl        %s\n"
2053                          ".long %s\n"
2054                          ".section      .opd,\"aw\"\n"
2055                          ".align 2\n"
2056                          "%s:\n"
2057                          ".long .%s,.TOC.@tocbase32\n"
2058                          ".size %s,.-%s\n"
2059                          ".section .text\n"
2060                          ".type .%s,@function\n"
2061                          ".align 2\n"
2062                          ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2063 #else
2064                          ".section      .ctors,\"aw\",@progbits\n"
2065                          ".align 2\n"
2066                          ".globl        %1$s\n"
2067                          ".long %1$s\n"
2068                          ".section      .opd,\"aw\"\n"
2069                          ".align 2\n"
2070                          "%1$s:\n"
2071                          ".long .%1$s,.TOC.@tocbase32\n"
2072                          ".size %1$s,.-%1$s\n"
2073                          ".section .text\n"
2074                          ".type .%1$s,@function\n"
2075                          ".align 2\n"
2076                          ".%1$s:\n", symbol);
2077 #endif
2078
2079
2080         fprintf (acfg->fp,
2081                          "stdu 1,-128(1)\n"
2082                          "mflr 0\n"
2083                          "std 31,120(1)\n"
2084                          "std 0,144(1)\n"
2085
2086                          ".Lautoreg:\n"
2087                          "lis 3, .Lglobals@h\n"
2088                          "ori 3, 3, .Lglobals@l\n"
2089                          "bl .mono_aot_register_module\n"
2090                          "ld 11,0(1)\n"
2091                          "ld 0,16(11)\n"
2092                          "mtlr 0\n"
2093                          "ld 31,-8(11)\n"
2094                          "mr 1,11\n"
2095                          "blr\n"
2096                          );
2097 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE) 
2098                 fprintf (acfg->fp,
2099                          ".size .%s,.-.%s\n", symbol, symbol);
2100 #else
2101         fprintf (acfg->fp,
2102                          ".size .%1$s,.-.%1$s\n", symbol);
2103 #endif
2104 #else
2105 #endif
2106 }
2107
2108 /* END OF ARCH SPECIFIC CODE */
2109
2110 static guint32
2111 mono_get_field_token (MonoClassField *field) 
2112 {
2113         MonoClass *klass = field->parent;
2114         int i;
2115
2116         for (i = 0; i < klass->field.count; ++i) {
2117                 if (field == &klass->fields [i])
2118                         return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2119         }
2120
2121         g_assert_not_reached ();
2122         return 0;
2123 }
2124
2125 static inline void
2126 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2127 {
2128         guint8 *p = buf;
2129
2130         //printf ("ENCODE: %d 0x%x.\n", value, value);
2131
2132         /* 
2133          * Same encoding as the one used in the metadata, extended to handle values
2134          * greater than 0x1fffffff.
2135          */
2136         if ((value >= 0) && (value <= 127))
2137                 *p++ = value;
2138         else if ((value >= 0) && (value <= 16383)) {
2139                 p [0] = 0x80 | (value >> 8);
2140                 p [1] = value & 0xff;
2141                 p += 2;
2142         } else if ((value >= 0) && (value <= 0x1fffffff)) {
2143                 p [0] = (value >> 24) | 0xc0;
2144                 p [1] = (value >> 16) & 0xff;
2145                 p [2] = (value >> 8) & 0xff;
2146                 p [3] = value & 0xff;
2147                 p += 4;
2148         }
2149         else {
2150                 p [0] = 0xff;
2151                 p [1] = (value >> 24) & 0xff;
2152                 p [2] = (value >> 16) & 0xff;
2153                 p [3] = (value >> 8) & 0xff;
2154                 p [4] = value & 0xff;
2155                 p += 5;
2156         }
2157         if (endbuf)
2158                 *endbuf = p;
2159 }
2160
2161 static void
2162 stream_init (MonoDynamicStream *sh)
2163 {
2164         sh->index = 0;
2165         sh->alloc_size = 4096;
2166         sh->data = g_malloc (4096);
2167
2168         /* So offsets are > 0 */
2169         sh->data [0] = 0;
2170         sh->index ++;
2171 }
2172
2173 static void
2174 make_room_in_stream (MonoDynamicStream *stream, int size)
2175 {
2176         if (size <= stream->alloc_size)
2177                 return;
2178         
2179         while (stream->alloc_size <= size) {
2180                 if (stream->alloc_size < 4096)
2181                         stream->alloc_size = 4096;
2182                 else
2183                         stream->alloc_size *= 2;
2184         }
2185         
2186         stream->data = g_realloc (stream->data, stream->alloc_size);
2187 }
2188
2189 static guint32
2190 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2191 {
2192         guint32 idx;
2193         
2194         make_room_in_stream (stream, stream->index + len);
2195         memcpy (stream->data + stream->index, data, len);
2196         idx = stream->index;
2197         stream->index += len;
2198         return idx;
2199 }
2200
2201 /*
2202  * add_to_blob:
2203  *
2204  *   Add data to the binary blob inside the aot image. Returns the offset inside the
2205  * blob where the data was stored.
2206  */
2207 static guint32
2208 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2209 {
2210         if (acfg->blob.alloc_size == 0)
2211                 stream_init (&acfg->blob);
2212
2213         return add_stream_data (&acfg->blob, (char*)data, data_len);
2214 }
2215
2216 static guint32
2217 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2218 {
2219         char buf [4] = {0};
2220         guint32 count;
2221
2222         if (acfg->blob.alloc_size == 0)
2223                 stream_init (&acfg->blob);
2224
2225         count = acfg->blob.index % align;
2226
2227         /* we assume the stream data will be aligned */
2228         if (count)
2229                 add_stream_data (&acfg->blob, buf, 4 - count);
2230
2231         return add_stream_data (&acfg->blob, (char*)data, data_len);
2232 }
2233
2234 /*
2235  * emit_offset_table:
2236  *
2237  *   Emit a table of increasing offsets in a compact form using differential encoding.
2238  * There is an index entry for each GROUP_SIZE number of entries. The greater the
2239  * group size, the more compact the table becomes, but the slower it becomes to compute
2240  * a given entry. Returns the size of the table.
2241  */
2242 static guint32
2243 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2244 {
2245         gint32 current_offset;
2246         int i, buf_size, ngroups, index_entry_size;
2247         guint8 *p, *buf;
2248         guint32 *index_offsets;
2249
2250         ngroups = (noffsets + (group_size - 1)) / group_size;
2251
2252         index_offsets = g_new0 (guint32, ngroups);
2253
2254         buf_size = noffsets * 4;
2255         p = buf = g_malloc0 (buf_size);
2256
2257         current_offset = 0;
2258         for (i = 0; i < noffsets; ++i) {
2259                 //printf ("D: %d -> %d\n", i, offsets [i]);
2260                 if ((i % group_size) == 0) {
2261                         index_offsets [i / group_size] = p - buf;
2262                         /* Emit the full value for these entries */
2263                         encode_value (offsets [i], p, &p);
2264                 } else {
2265                         /* The offsets are allowed to be non-increasing */
2266                         //g_assert (offsets [i] >= current_offset);
2267                         encode_value (offsets [i] - current_offset, p, &p);
2268                 }
2269                 current_offset = offsets [i];
2270         }
2271
2272         if (ngroups && index_offsets [ngroups - 1] < 65000)
2273                 index_entry_size = 2;
2274         else
2275                 index_entry_size = 4;
2276
2277         /* Emit the header */
2278         emit_int32 (acfg, noffsets);
2279         emit_int32 (acfg, group_size);
2280         emit_int32 (acfg, ngroups);
2281         emit_int32 (acfg, index_entry_size);
2282
2283         /* Emit the index */
2284         for (i = 0; i < ngroups; ++i) {
2285                 if (index_entry_size == 2)
2286                         emit_int16 (acfg, index_offsets [i]);
2287                 else
2288                         emit_int32 (acfg, index_offsets [i]);
2289         }
2290
2291         /* Emit the data */
2292         emit_bytes (acfg, buf, p - buf);
2293
2294     return (int)(p - buf) + (ngroups * 4);
2295 }
2296
2297 static guint32
2298 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2299 {
2300         guint32 index;
2301
2302         index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2303         if (index)
2304                 return index - 1;
2305         else {
2306                 index = g_hash_table_size (cfg->image_hash);
2307                 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2308                 g_ptr_array_add (cfg->image_table, image);
2309                 return index;
2310         }
2311 }
2312
2313 static guint32
2314 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2315 {
2316         int i;
2317         int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2318
2319         /* FIXME: Search referenced images as well */
2320         if (!acfg->typespec_classes) {
2321                 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2322                 for (i = 0; i < len; ++i) {
2323                         acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2324                 }
2325         }
2326         for (i = 0; i < len; ++i) {
2327                 if (acfg->typespec_classes [i] == klass)
2328                         break;
2329         }
2330
2331         if (i < len)
2332                 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2333         else
2334                 return 0;
2335 }
2336
2337 static void
2338 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2339
2340 static void
2341 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2342
2343 static void
2344 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2345
2346 static void
2347 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2348
2349 static void
2350 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2351 {
2352         guint8 *p = buf;
2353
2354         /*
2355          * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2356          * information.
2357          */
2358
2359         if (klass->generic_class) {
2360                 guint32 token;
2361                 g_assert (klass->type_token);
2362
2363                 /* Find a typespec for a class if possible */
2364                 token = find_typespec_for_class (acfg, klass);
2365                 if (token) {
2366                         encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2367                         encode_value (token, p, &p);
2368                 } else {
2369                         MonoClass *gclass = klass->generic_class->container_class;
2370                         MonoGenericInst *inst = klass->generic_class->context.class_inst;
2371                         static int count = 0;
2372                         guint8 *p1 = p;
2373
2374                         encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2375                         encode_klass_ref (acfg, gclass, p, &p);
2376                         encode_ginst (acfg, inst, p, &p);
2377
2378                         count += p - p1;
2379                 }
2380         } else if (klass->type_token) {
2381                 int iindex = get_image_index (acfg, klass->image);
2382
2383                 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2384                 if (iindex == 0) {
2385                         encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2386                         encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2387                 } else {
2388                         encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2389                         encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2390                         encode_value (get_image_index (acfg, klass->image), p, &p);
2391                 }
2392         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2393                 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2394                 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2395
2396                 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2397                 encode_value (klass->byval_arg.type, p, &p);
2398                 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2399
2400                 encode_value (container ? 1 : 0, p, &p);
2401                 if (container) {
2402                         encode_value (container->is_method, p, &p);
2403                         g_assert (par->serial == 0);
2404                         if (container->is_method)
2405                                 encode_method_ref (acfg, container->owner.method, p, &p);
2406                         else
2407                                 encode_klass_ref (acfg, container->owner.klass, p, &p);
2408                 } else {
2409                         encode_value (par->serial, p, &p);
2410                 }
2411         } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2412                 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2413                 encode_type (acfg, &klass->byval_arg, p, &p);
2414         } else {
2415                 /* Array class */
2416                 g_assert (klass->rank > 0);
2417                 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2418                 encode_value (klass->rank, p, &p);
2419                 encode_klass_ref (acfg, klass->element_class, p, &p);
2420         }
2421         *endbuf = p;
2422 }
2423
2424 /*
2425  * encode_klass_ref:
2426  *
2427  *   Encode a reference to KLASS. We use our home-grown encoding instead of the
2428  * standard metadata encoding.
2429  */
2430 static void
2431 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2432 {
2433         gboolean shared = FALSE;
2434
2435         /* 
2436          * The encoding of generic instances is large so emit them only once.
2437          */
2438         if (klass->generic_class) {
2439                 guint32 token;
2440                 g_assert (klass->type_token);
2441
2442                 /* Find a typespec for a class if possible */
2443                 token = find_typespec_for_class (acfg, klass);
2444                 if (!token)
2445                         shared = TRUE;
2446         } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2447                 shared = TRUE;
2448         }
2449
2450         if (shared) {
2451                 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2452                 guint8 *buf2, *p;
2453
2454                 if (!offset) {
2455                         buf2 = g_malloc (1024);
2456                         p = buf2;
2457
2458                         encode_klass_ref_inner (acfg, klass, p, &p);
2459                         g_assert (p - buf2 < 1024);
2460
2461                         offset = add_to_blob (acfg, buf2, p - buf2);
2462                         g_free (buf2);
2463
2464                         g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2465                 } else {
2466                         offset --;
2467                 }
2468
2469                 p = buf;
2470                 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2471                 encode_value (offset, p, &p);
2472                 *endbuf = p;
2473                 return;
2474         }
2475
2476         encode_klass_ref_inner (acfg, klass, buf, endbuf);
2477 }
2478
2479 static void
2480 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2481 {
2482         guint32 token = mono_get_field_token (field);
2483         guint8 *p = buf;
2484
2485         encode_klass_ref (cfg, field->parent, p, &p);
2486         g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2487         encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2488         *endbuf = p;
2489 }
2490
2491 static void
2492 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2493 {
2494         guint8 *p = buf;
2495         int i;
2496
2497         encode_value (inst->type_argc, p, &p);
2498         for (i = 0; i < inst->type_argc; ++i)
2499                 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2500         *endbuf = p;
2501 }
2502
2503 static void
2504 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2505 {
2506         guint8 *p = buf;
2507         MonoGenericInst *inst;
2508
2509         inst = context->class_inst;
2510         if (inst) {
2511                 g_assert (inst->type_argc);
2512                 encode_ginst (acfg, inst, p, &p);
2513         } else {
2514                 encode_value (0, p, &p);
2515         }
2516         inst = context->method_inst;
2517         if (inst) {
2518                 g_assert (inst->type_argc);
2519                 encode_ginst (acfg, inst, p, &p);
2520         } else {
2521                 encode_value (0, p, &p);
2522         }
2523         *endbuf = p;
2524 }
2525
2526 static void
2527 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2528 {
2529         guint8 *p = buf;
2530
2531         g_assert (t->num_mods == 0);
2532         /* t->attrs can be ignored */
2533         //g_assert (t->attrs == 0);
2534
2535         if (t->pinned) {
2536                 *p = MONO_TYPE_PINNED;
2537                 ++p;
2538         }
2539         if (t->byref) {
2540                 *p = MONO_TYPE_BYREF;
2541                 ++p;
2542         }
2543
2544         *p = t->type;
2545         p ++;
2546
2547         switch (t->type) {
2548         case MONO_TYPE_VOID:
2549         case MONO_TYPE_BOOLEAN:
2550         case MONO_TYPE_CHAR:
2551         case MONO_TYPE_I1:
2552         case MONO_TYPE_U1:
2553         case MONO_TYPE_I2:
2554         case MONO_TYPE_U2:
2555         case MONO_TYPE_I4:
2556         case MONO_TYPE_U4:
2557         case MONO_TYPE_I8:
2558         case MONO_TYPE_U8:
2559         case MONO_TYPE_R4:
2560         case MONO_TYPE_R8:
2561         case MONO_TYPE_I:
2562         case MONO_TYPE_U:
2563         case MONO_TYPE_STRING:
2564         case MONO_TYPE_OBJECT:
2565         case MONO_TYPE_TYPEDBYREF:
2566                 break;
2567         case MONO_TYPE_VALUETYPE:
2568         case MONO_TYPE_CLASS:
2569                 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2570                 break;
2571         case MONO_TYPE_SZARRAY:
2572                 encode_klass_ref (acfg, t->data.klass, p, &p);
2573                 break;
2574         case MONO_TYPE_PTR:
2575                 encode_type (acfg, t->data.type, p, &p);
2576                 break;
2577         case MONO_TYPE_GENERICINST: {
2578                 MonoClass *gclass = t->data.generic_class->container_class;
2579                 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2580
2581                 encode_klass_ref (acfg, gclass, p, &p);
2582                 encode_ginst (acfg, inst, p, &p);
2583                 break;
2584         }
2585         case MONO_TYPE_ARRAY: {
2586                 MonoArrayType *array = t->data.array;
2587                 int i;
2588
2589                 encode_klass_ref (acfg, array->eklass, p, &p);
2590                 encode_value (array->rank, p, &p);
2591                 encode_value (array->numsizes, p, &p);
2592                 for (i = 0; i < array->numsizes; ++i)
2593                         encode_value (array->sizes [i], p, &p);
2594                 encode_value (array->numlobounds, p, &p);
2595                 for (i = 0; i < array->numlobounds; ++i)
2596                         encode_value (array->lobounds [i], p, &p);
2597                 break;
2598         }
2599         case MONO_TYPE_VAR:
2600         case MONO_TYPE_MVAR:
2601                 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2602                 break;
2603         default:
2604                 g_assert_not_reached ();
2605         }
2606
2607         *endbuf = p;
2608 }
2609
2610 static void
2611 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2612 {
2613         guint8 *p = buf;
2614         guint32 flags = 0;
2615         int i;
2616
2617         /* Similar to the metadata encoding */
2618         if (sig->generic_param_count)
2619                 flags |= 0x10;
2620         if (sig->hasthis)
2621                 flags |= 0x20;
2622         if (sig->explicit_this)
2623                 flags |= 0x40;
2624         flags |= (sig->call_convention & 0x0F);
2625
2626         *p = flags;
2627         ++p;
2628         if (sig->generic_param_count)
2629                 encode_value (sig->generic_param_count, p, &p);
2630         encode_value (sig->param_count, p, &p);
2631
2632         encode_type (acfg, sig->ret, p, &p);
2633         for (i = 0; i < sig->param_count; ++i) {
2634                 if (sig->sentinelpos == i) {
2635                         *p = MONO_TYPE_SENTINEL;
2636                         ++p;
2637                 }
2638                 encode_type (acfg, sig->params [i], p, &p);
2639         }
2640
2641         *endbuf = p;
2642 }
2643
2644 #define MAX_IMAGE_INDEX 250
2645
2646 static void
2647 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2648 {
2649         guint32 image_index = get_image_index (acfg, method->klass->image);
2650         guint32 token = method->token;
2651         MonoJumpInfoToken *ji;
2652         guint8 *p = buf;
2653
2654         /*
2655          * The encoding for most methods is as follows:
2656          * - image index encoded as a leb128
2657          * - token index encoded as a leb128
2658          * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2659          * types of method encodings.
2660          */
2661
2662         /* Mark methods which can't use aot trampolines because they need the further 
2663          * processing in mono_magic_trampoline () which requires a MonoMethod*.
2664          */
2665         if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2666                 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2667                 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2668
2669         if (method->wrapper_type) {
2670                 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2671
2672                 encode_value (method->wrapper_type, p, &p);
2673
2674                 switch (method->wrapper_type) {
2675                 case MONO_WRAPPER_REMOTING_INVOKE:
2676                 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2677                 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2678                         MonoMethod *m;
2679
2680                         m = mono_marshal_method_from_wrapper (method);
2681                         g_assert (m);
2682                         encode_method_ref (acfg, m, p, &p);
2683                         break;
2684                 }
2685                 case MONO_WRAPPER_PROXY_ISINST:
2686                 case MONO_WRAPPER_LDFLD:
2687                 case MONO_WRAPPER_LDFLDA:
2688                 case MONO_WRAPPER_STFLD:
2689                 case MONO_WRAPPER_ISINST: {
2690                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2691
2692                         g_assert (info);
2693                         encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2694                         break;
2695                 }
2696                 case MONO_WRAPPER_LDFLD_REMOTE:
2697                 case MONO_WRAPPER_STFLD_REMOTE:
2698                         break;
2699                 case MONO_WRAPPER_ALLOC: {
2700                         AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2701
2702                         /* The GC name is saved once in MonoAotFileInfo */
2703                         g_assert (info->alloc_type != -1);
2704                         encode_value (info->alloc_type, p, &p);
2705                         break;
2706                 }
2707                 case MONO_WRAPPER_WRITE_BARRIER:
2708                         break;
2709                 case MONO_WRAPPER_STELEMREF: {
2710                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2711
2712                         g_assert (info);
2713                         encode_value (info->subtype, p, &p);
2714                         if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2715                                 encode_value (info->d.virtual_stelemref.kind, p, &p);
2716                         break;
2717                 }
2718                 case MONO_WRAPPER_UNKNOWN: {
2719                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2720
2721                         g_assert (info);
2722                         encode_value (info->subtype, p, &p);
2723                         if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2724                                 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2725                                 encode_klass_ref (acfg, method->klass, p, &p);
2726                         else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2727                                 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2728                         else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2729                                 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2730                         break;
2731                 }
2732                 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2733                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2734
2735                         g_assert (info);
2736                         encode_value (info->subtype, p, &p);
2737                         if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2738                                 strcpy ((char*)p, method->name);
2739                                 p += strlen (method->name) + 1;
2740                         } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2741                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2742                         } else {
2743                                 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2744                                 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2745                         }
2746                         break;
2747                 }
2748                 case MONO_WRAPPER_SYNCHRONIZED: {
2749                         MonoMethod *m;
2750
2751                         m = mono_marshal_method_from_wrapper (method);
2752                         g_assert (m);
2753                         g_assert (m != method);
2754                         encode_method_ref (acfg, m, p, &p);
2755                         break;
2756                 }
2757                 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2758                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2759
2760                         g_assert (info);
2761                         encode_value (info->subtype, p, &p);
2762
2763                         if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2764                                 encode_value (info->d.element_addr.rank, p, &p);
2765                                 encode_value (info->d.element_addr.elem_size, p, &p);
2766                         } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2767                                 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2768                         } else {
2769                                 g_assert_not_reached ();
2770                         }
2771                         break;
2772                 }
2773                 case MONO_WRAPPER_CASTCLASS: {
2774                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2775
2776                         g_assert (info);
2777                         encode_value (info->subtype, p, &p);
2778                         break;
2779                 }
2780                 case MONO_WRAPPER_RUNTIME_INVOKE: {
2781                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2782
2783                         g_assert (info);
2784                         encode_value (info->subtype, p, &p);
2785                         if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2786                                 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2787                         else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2788                                 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2789                         break;
2790                 }
2791                 case MONO_WRAPPER_DELEGATE_INVOKE:
2792                 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2793                 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2794                         if (method->is_inflated) {
2795                                 /* These wrappers are identified by their class */
2796                                 encode_value (1, p, &p);
2797                                 encode_klass_ref (acfg, method->klass, p, &p);
2798                         } else {
2799                                 MonoMethodSignature *sig = mono_method_signature (method);
2800                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2801
2802                                 encode_value (0, p, &p);
2803                                 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2804                                         encode_value (info ? info->subtype : 0, p, &p);
2805                                 encode_signature (acfg, sig, p, &p);
2806                         }
2807                         break;
2808                 }
2809                 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2810                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2811
2812                         g_assert (info);
2813                         encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2814                         encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2815                         break;
2816                 }
2817                 default:
2818                         g_assert_not_reached ();
2819                 }
2820         } else if (mono_method_signature (method)->is_inflated) {
2821                 /* 
2822                  * This is a generic method, find the original token which referenced it and
2823                  * encode that.
2824                  * Obtain the token from information recorded by the JIT.
2825                  */
2826                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2827                 if (ji) {
2828                         image_index = get_image_index (acfg, ji->image);
2829                         g_assert (image_index < MAX_IMAGE_INDEX);
2830                         token = ji->token;
2831
2832                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2833                         encode_value (image_index, p, &p);
2834                         encode_value (token, p, &p);
2835                 } else {
2836                         MonoMethod *declaring;
2837                         MonoGenericContext *context = mono_method_get_context (method);
2838
2839                         g_assert (method->is_inflated);
2840                         declaring = ((MonoMethodInflated*)method)->declaring;
2841
2842                         /*
2843                          * This might be a non-generic method of a generic instance, which 
2844                          * doesn't have a token since the reference is generated by the JIT 
2845                          * like Nullable:Box/Unbox, or by generic sharing.
2846                          */
2847                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2848                         /* Encode the klass */
2849                         encode_klass_ref (acfg, method->klass, p, &p);
2850                         /* Encode the method */
2851                         image_index = get_image_index (acfg, method->klass->image);
2852                         g_assert (image_index < MAX_IMAGE_INDEX);
2853                         g_assert (declaring->token);
2854                         token = declaring->token;
2855                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2856                         encode_value (image_index, p, &p);
2857                         encode_value (token, p, &p);
2858                         encode_generic_context (acfg, context, p, &p);
2859                 }
2860         } else if (token == 0) {
2861                 /* This might be a method of a constructed type like int[,].Set */
2862                 /* Obtain the token from information recorded by the JIT */
2863                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2864                 if (ji) {
2865                         image_index = get_image_index (acfg, ji->image);
2866                         g_assert (image_index < MAX_IMAGE_INDEX);
2867                         token = ji->token;
2868
2869                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2870                         encode_value (image_index, p, &p);
2871                         encode_value (token, p, &p);
2872                 } else {
2873                         /* Array methods */
2874                         g_assert (method->klass->rank);
2875
2876                         /* Encode directly */
2877                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2878                         encode_klass_ref (acfg, method->klass, p, &p);
2879                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2880                                 encode_value (0, p, &p);
2881                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2882                                 encode_value (1, p, &p);
2883                         else if (!strcmp (method->name, "Get"))
2884                                 encode_value (2, p, &p);
2885                         else if (!strcmp (method->name, "Address"))
2886                                 encode_value (3, p, &p);
2887                         else if (!strcmp (method->name, "Set"))
2888                                 encode_value (4, p, &p);
2889                         else
2890                                 g_assert_not_reached ();
2891                 }
2892         } else {
2893                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2894
2895                 if (image_index >= MONO_AOT_METHODREF_MIN) {
2896                         encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2897                         encode_value (image_index, p, &p);
2898                         encode_value (mono_metadata_token_index (token), p, &p);
2899                 } else {
2900                         encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2901                 }
2902         }
2903         *endbuf = p;
2904 }
2905
2906 static gint
2907 compare_patches (gconstpointer a, gconstpointer b)
2908 {
2909         int i, j;
2910
2911         i = (*(MonoJumpInfo**)a)->ip.i;
2912         j = (*(MonoJumpInfo**)b)->ip.i;
2913
2914         if (i < j)
2915                 return -1;
2916         else
2917                 if (i > j)
2918                         return 1;
2919         else
2920                 return 0;
2921 }
2922
2923 static G_GNUC_UNUSED char*
2924 patch_to_string (MonoJumpInfo *patch_info)
2925 {
2926         GString *str;
2927
2928         str = g_string_new ("");
2929
2930         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2931
2932         switch (patch_info->type) {
2933         case MONO_PATCH_INFO_VTABLE:
2934                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2935                 break;
2936         default:
2937                 break;
2938         }
2939         g_string_append_printf (str, ")");
2940         return g_string_free (str, FALSE);
2941 }
2942
2943 /*
2944  * is_plt_patch:
2945  *
2946  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
2947  * PLT entry.
2948  */
2949 static inline gboolean
2950 is_plt_patch (MonoJumpInfo *patch_info)
2951 {
2952         switch (patch_info->type) {
2953         case MONO_PATCH_INFO_METHOD:
2954         case MONO_PATCH_INFO_INTERNAL_METHOD:
2955         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2956         case MONO_PATCH_INFO_ICALL_ADDR:
2957         case MONO_PATCH_INFO_CLASS_INIT:
2958         case MONO_PATCH_INFO_RGCTX_FETCH:
2959         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2960         case MONO_PATCH_INFO_MONITOR_ENTER:
2961         case MONO_PATCH_INFO_MONITOR_EXIT:
2962         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2963                 return TRUE;
2964         default:
2965                 return FALSE;
2966         }
2967 }
2968
2969 /*
2970  * get_plt_symbol:
2971  *
2972  *   Return the symbol identifying the plt entry PLT_OFFSET.
2973  */
2974 static char*
2975 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2976 {
2977 #ifdef TARGET_MACH
2978         /* 
2979          * The Apple linker reorganizes object files, so it doesn't like branches to local
2980          * labels, since those have no relocations.
2981          */
2982         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2983 #else
2984         return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2985 #endif
2986 }
2987
2988 /*
2989  * get_plt_entry:
2990  *
2991  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2992  */
2993 static MonoPltEntry*
2994 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2995 {
2996         MonoPltEntry *res;
2997
2998         if (!is_plt_patch (patch_info))
2999                 return NULL;
3000
3001         if (!acfg->patch_to_plt_entry [patch_info->type])
3002                 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3003         res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3004
3005         // FIXME: This breaks the calculation of final_got_size         
3006         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3007                 /* 
3008                  * Allocate a separate PLT slot for each such patch, since some plt
3009                  * entries will refer to the method itself, and some will refer to the
3010                  * wrapper.
3011                  */
3012                 res = NULL;
3013         }
3014
3015         if (!res) {
3016                 MonoJumpInfo *new_ji;
3017
3018                 g_assert (!acfg->final_got_size);
3019
3020                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3021
3022                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3023                 res->plt_offset = acfg->plt_offset;
3024                 res->ji = new_ji;
3025                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3026                 if (acfg->aot_opts.write_symbols)
3027                         res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3028                 if (res->debug_sym)
3029                         res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3030                 else
3031                         res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3032
3033                 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3034
3035                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3036
3037                 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3038                 //mono_print_ji (patch_info); printf ("\n");
3039                 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3040
3041                 acfg->plt_offset ++;
3042         }
3043
3044         return res;
3045 }
3046
3047 /**
3048  * get_got_offset:
3049  *
3050  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
3051  * JI could be found if it exists, otherwise allocates a new one.
3052  */
3053 static guint32
3054 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
3055 {
3056         guint32 got_offset;
3057
3058         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
3059         if (got_offset)
3060                 return got_offset - 1;
3061
3062         got_offset = acfg->got_offset;
3063         acfg->got_offset ++;
3064
3065         if (acfg->final_got_size)
3066                 g_assert (got_offset < acfg->final_got_size);
3067
3068         acfg->stats.got_slots ++;
3069         acfg->stats.got_slot_types [ji->type] ++;
3070
3071         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3072         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3073         g_ptr_array_add (acfg->got_patches, ji);
3074
3075         return got_offset;
3076 }
3077
3078 /* Add a method to the list of methods which need to be emitted */
3079 static void
3080 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3081 {
3082         g_assert (method);
3083         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3084                 g_ptr_array_add (acfg->methods, method);
3085                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3086                 acfg->nmethods = acfg->methods->len + 1;
3087         }
3088
3089         if (method->wrapper_type || extra)
3090                 g_ptr_array_add (acfg->extra_methods, method);
3091 }
3092
3093 static guint32
3094 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3095 {
3096         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3097         
3098         g_assert (index);
3099
3100         return index - 1;
3101 }
3102
3103 static int
3104 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3105 {
3106         int index;
3107
3108         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3109         if (index)
3110                 return index - 1;
3111
3112         index = acfg->method_index;
3113         add_method_with_index (acfg, method, index, extra);
3114
3115         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3116
3117         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3118
3119         acfg->method_index ++;
3120
3121         return index;
3122 }
3123
3124 static int
3125 add_method (MonoAotCompile *acfg, MonoMethod *method)
3126 {
3127         return add_method_full (acfg, method, FALSE, 0);
3128 }
3129
3130 static void
3131 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3132 {
3133         if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3134                 method = mini_get_shared_method (method);
3135
3136         if (acfg->aot_opts.log_generics)
3137                 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3138
3139         add_method_full (acfg, method, TRUE, depth);
3140 }
3141
3142 static void
3143 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3144 {
3145         add_extra_method_with_depth (acfg, method, 0);
3146 }
3147
3148 static void
3149 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3150 {
3151         MonoAotCompile *acfg = user_data;
3152         MonoJitICallInfo *callinfo = value;
3153         MonoMethod *wrapper;
3154         char *name;
3155
3156         if (!callinfo->sig)
3157                 return;
3158
3159         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3160         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3161         g_free (name);
3162
3163         add_method (acfg, wrapper);
3164 }
3165
3166 static MonoMethod*
3167 get_runtime_invoke_sig (MonoMethodSignature *sig)
3168 {
3169         MonoMethodBuilder *mb;
3170         MonoMethod *m;
3171
3172         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3173         m = mono_mb_create_method (mb, sig, 16);
3174         return mono_marshal_get_runtime_invoke (m, FALSE);
3175 }
3176
3177 static gboolean
3178 can_marshal_struct (MonoClass *klass)
3179 {
3180         MonoClassField *field;
3181         gboolean can_marshal = TRUE;
3182         gpointer iter = NULL;
3183         MonoMarshalType *info;
3184         int i;
3185
3186         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3187                 return FALSE;
3188
3189         info = mono_marshal_load_type_info (klass);
3190
3191         /* Only allow a few field types to avoid asserts in the marshalling code */
3192         while ((field = mono_class_get_fields (klass, &iter))) {
3193                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3194                         continue;
3195
3196                 switch (field->type->type) {
3197                 case MONO_TYPE_I4:
3198                 case MONO_TYPE_U4:
3199                 case MONO_TYPE_I1:
3200                 case MONO_TYPE_U1:
3201                 case MONO_TYPE_BOOLEAN:
3202                 case MONO_TYPE_I2:
3203                 case MONO_TYPE_U2:
3204                 case MONO_TYPE_CHAR:
3205                 case MONO_TYPE_I8:
3206                 case MONO_TYPE_U8:
3207                 case MONO_TYPE_I:
3208                 case MONO_TYPE_U:
3209                 case MONO_TYPE_PTR:
3210                 case MONO_TYPE_R4:
3211                 case MONO_TYPE_R8:
3212                 case MONO_TYPE_STRING:
3213                         break;
3214                 case MONO_TYPE_VALUETYPE:
3215                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3216                                 can_marshal = FALSE;
3217                         break;
3218                 case MONO_TYPE_SZARRAY: {
3219                         gboolean has_mspec = FALSE;
3220
3221                         if (info) {
3222                                 for (i = 0; i < info->num_fields; ++i) {
3223                                         if (info->fields [i].field == field && info->fields [i].mspec)
3224                                                 has_mspec = TRUE;
3225                                 }
3226                         }
3227                         if (!has_mspec)
3228                                 can_marshal = FALSE;
3229                         break;
3230                 }
3231                 default:
3232                         can_marshal = FALSE;
3233                         break;
3234                 }
3235         }
3236
3237         /* Special cases */
3238         /* Its hard to compute whenever these can be marshalled or not */
3239         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3240                 return TRUE;
3241
3242         return can_marshal;
3243 }
3244
3245 static void
3246 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3247 {
3248         /* Create a vtype instantiation */
3249         MonoGenericContext shared_context;
3250         MonoType **args;
3251         MonoGenericInst *inst;
3252         MonoGenericContainer *container;
3253         MonoClass **constraints;
3254         int i;
3255
3256         memset (ctx, 0, sizeof (MonoGenericContext));
3257
3258         if (method->klass->generic_container) {
3259                 shared_context = method->klass->generic_container->context;
3260                 inst = shared_context.class_inst;
3261
3262                 args = g_new0 (MonoType*, inst->type_argc);
3263                 for (i = 0; i < inst->type_argc; ++i) {
3264                         args [i] = &mono_defaults.int_class->byval_arg;
3265                 }
3266                 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3267         }
3268         if (method->is_generic) {
3269                 container = mono_method_get_generic_container (method);
3270                 shared_context = container->context;
3271                 inst = shared_context.method_inst;
3272
3273                 args = g_new0 (MonoType*, inst->type_argc);
3274                 for (i = 0; i < container->type_argc; ++i) {
3275                         MonoGenericParamInfo *info = &container->type_params [i].info;
3276                         gboolean ref_only = FALSE;
3277
3278                         if (info && info->constraints) {
3279                                 constraints = info->constraints;
3280
3281                                 while (*constraints) {
3282                                         MonoClass *cklass = *constraints;
3283                                         if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3284                                                 /* Inflaring the method with our vtype would not be valid */
3285                                                 ref_only = TRUE;
3286                                         constraints ++;
3287                                 }
3288                         }
3289
3290                         if (ref_only)
3291                                 args [i] = &mono_defaults.object_class->byval_arg;
3292                         else
3293                                 args [i] = &mono_defaults.int_class->byval_arg;
3294                 }
3295                 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3296         }
3297 }
3298
3299 static void
3300 add_wrappers (MonoAotCompile *acfg)
3301 {
3302         MonoMethod *method, *m;
3303         int i, j;
3304         MonoMethodSignature *sig, *csig;
3305         guint32 token;
3306
3307         /* 
3308          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3309          * so there is only one wrapper of a given type, or inlining their contents into their
3310          * callers.
3311          */
3312         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3313                 MonoMethod *method;
3314                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3315                 gboolean skip = FALSE;
3316
3317                 method = mono_get_method (acfg->image, token, NULL);
3318
3319                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3320                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3321                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3322                         skip = TRUE;
3323
3324                 /* Skip methods which can not be handled by get_runtime_invoke () */
3325                 sig = mono_method_signature (method);
3326                 if (!sig)
3327                         continue;
3328                 if ((sig->ret->type == MONO_TYPE_PTR) ||
3329                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3330                         skip = TRUE;
3331                 if (mono_class_is_open_constructed_type (sig->ret))
3332                         skip = TRUE;
3333
3334                 for (j = 0; j < sig->param_count; j++) {
3335                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3336                                 skip = TRUE;
3337                         if (mono_class_is_open_constructed_type (sig->params [j]))
3338                                 skip = TRUE;
3339                 }
3340
3341 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3342                 if (!mono_class_is_contextbound (method->klass)) {
3343                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3344                         gboolean has_nullable = FALSE;
3345
3346                         for (j = 0; j < sig->param_count; j++) {
3347                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3348                                         has_nullable = TRUE;
3349                         }
3350
3351                         if (info && !has_nullable) {
3352                                 /* Supported by the dynamic runtime-invoke wrapper */
3353                                 skip = TRUE;
3354                                 g_free (info);
3355                         }
3356                 }
3357 #endif
3358
3359                 if (!skip) {
3360                         //printf ("%s\n", mono_method_full_name (method, TRUE));
3361                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3362                 }
3363         }
3364
3365         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3366                 MonoMethodDesc *desc;
3367                 MonoMethod *orig_method;
3368                 int nallocators;
3369
3370                 /* Runtime invoke wrappers */
3371
3372                 /* void runtime-invoke () [.cctor] */
3373                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3374                 csig->ret = &mono_defaults.void_class->byval_arg;
3375                 add_method (acfg, get_runtime_invoke_sig (csig));
3376
3377                 /* void runtime-invoke () [Finalize] */
3378                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3379                 csig->hasthis = 1;
3380                 csig->ret = &mono_defaults.void_class->byval_arg;
3381                 add_method (acfg, get_runtime_invoke_sig (csig));
3382
3383                 /* void runtime-invoke (string) [exception ctor] */
3384                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3385                 csig->hasthis = 1;
3386                 csig->ret = &mono_defaults.void_class->byval_arg;
3387                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3388                 add_method (acfg, get_runtime_invoke_sig (csig));
3389
3390                 /* void runtime-invoke (string, string) [exception ctor] */
3391                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3392                 csig->hasthis = 1;
3393                 csig->ret = &mono_defaults.void_class->byval_arg;
3394                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3395                 csig->params [1] = &mono_defaults.string_class->byval_arg;
3396                 add_method (acfg, get_runtime_invoke_sig (csig));
3397
3398                 /* string runtime-invoke () [Exception.ToString ()] */
3399                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3400                 csig->hasthis = 1;
3401                 csig->ret = &mono_defaults.string_class->byval_arg;
3402                 add_method (acfg, get_runtime_invoke_sig (csig));
3403
3404                 /* void runtime-invoke (string, Exception) [exception ctor] */
3405                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3406                 csig->hasthis = 1;
3407                 csig->ret = &mono_defaults.void_class->byval_arg;
3408                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3409                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3410                 add_method (acfg, get_runtime_invoke_sig (csig));
3411
3412                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3413                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3414                 csig->hasthis = 1;
3415                 csig->ret = &(mono_class_from_name (
3416                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3417                 csig->params [0] = &mono_defaults.string_class->byval_arg;
3418                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3419                 add_method (acfg, get_runtime_invoke_sig (csig));
3420
3421                 /* runtime-invoke used by finalizers */
3422                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3423
3424                 /* This is used by mono_runtime_capture_context () */
3425                 method = mono_get_context_capture_method ();
3426                 if (method)
3427                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3428
3429 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3430                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3431 #endif
3432
3433                 /* stelemref */
3434                 add_method (acfg, mono_marshal_get_stelemref ());
3435
3436                 if (MONO_ARCH_HAVE_TLS_GET) {
3437                         /* Managed Allocators */
3438                         nallocators = mono_gc_get_managed_allocator_types ();
3439                         for (i = 0; i < nallocators; ++i) {
3440                                 m = mono_gc_get_managed_allocator_by_type (i);
3441                                 if (m)
3442                                         add_method (acfg, m);
3443                         }
3444
3445                         /* Monitor Enter/Exit */
3446                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3447                         orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3448                         /* This is a v4 method */
3449                         if (orig_method) {
3450                                 method = mono_monitor_get_fast_path (orig_method);
3451                                 if (method)
3452                                         add_method (acfg, method);
3453                         }
3454                         mono_method_desc_free (desc);
3455
3456                         desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3457                         orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3458                         g_assert (orig_method);
3459                         mono_method_desc_free (desc);
3460                         method = mono_monitor_get_fast_path (orig_method);
3461                         if (method)
3462                                 add_method (acfg, method);
3463                 }
3464
3465                 /* Stelemref wrappers */
3466                 {
3467                         MonoMethod **wrappers;
3468                         int nwrappers;
3469
3470                         wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3471                         for (i = 0; i < nwrappers; ++i)
3472                                 add_method (acfg, wrappers [i]);
3473                         g_free (wrappers);
3474                 }
3475
3476                 /* castclass_with_check wrapper */
3477                 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3478                 /* isinst_with_check wrapper */
3479                 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3480
3481 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3482                 {
3483                         MonoMethodDesc *desc;
3484                         MonoMethod *m;
3485
3486                         desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3487                         m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3488                         mono_method_desc_free (desc);
3489                         if (m) {
3490                                 m = mono_monitor_get_fast_path (m);
3491                                 if (m)
3492                                         add_method (acfg, m);
3493                         }
3494                 }
3495 #endif
3496
3497                 /* JIT icall wrappers */
3498                 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3499                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3500         }
3501
3502         /* 
3503          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3504          * we use the original method instead at runtime.
3505          * Since full-aot doesn't support remoting, this is not a problem.
3506          */
3507 #if 0
3508         /* remoting-invoke wrappers */
3509         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3510                 MonoMethodSignature *sig;
3511                 
3512                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3513                 method = mono_get_method (acfg->image, token, NULL);
3514
3515                 sig = mono_method_signature (method);
3516
3517                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3518                         m = mono_marshal_get_remoting_invoke_with_check (method);
3519
3520                         add_method (acfg, m);
3521                 }
3522         }
3523 #endif
3524
3525         /* delegate-invoke wrappers */
3526         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3527                 MonoClass *klass;
3528                 MonoCustomAttrInfo *cattr;
3529                 
3530                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3531                 klass = mono_class_get (acfg->image, token);
3532
3533                 if (!klass) {
3534                         mono_loader_clear_error ();
3535                         continue;
3536                 }
3537
3538                 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3539                         continue;
3540
3541                 if (!klass->generic_container) {
3542                         method = mono_get_delegate_invoke (klass);
3543
3544                         m = mono_marshal_get_delegate_invoke (method, NULL);
3545
3546                         add_method (acfg, m);
3547
3548                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3549                         if (method)
3550                                 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3551
3552                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3553                         if (method)
3554                                 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3555
3556                         cattr = mono_custom_attrs_from_class (klass);
3557
3558                         if (cattr) {
3559                                 int j;
3560
3561                                 for (j = 0; j < cattr->num_attrs; ++j)
3562                                         if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3563                                                 break;
3564                                 if (j < cattr->num_attrs)
3565                                         add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3566                         }
3567                 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3568                         MonoGenericContext ctx;
3569                         MonoMethod *inst, *gshared;
3570
3571                         /*
3572                          * Emit gsharedvt versions of the generic delegate-invoke wrappers
3573                          */
3574                         /* Invoke */
3575                         method = mono_get_delegate_invoke (klass);
3576                         create_gsharedvt_inst (acfg, method, &ctx);
3577
3578                         inst = mono_class_inflate_generic_method (method, &ctx);
3579
3580                         m = mono_marshal_get_delegate_invoke (inst, NULL);
3581                         g_assert (m->is_inflated);
3582
3583                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3584                         add_extra_method (acfg, gshared);
3585
3586                         /* begin-invoke */
3587                         method = mono_get_delegate_begin_invoke (klass);
3588                         create_gsharedvt_inst (acfg, method, &ctx);
3589
3590                         inst = mono_class_inflate_generic_method (method, &ctx);
3591
3592                         m = mono_marshal_get_delegate_begin_invoke (inst);
3593                         g_assert (m->is_inflated);
3594
3595                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3596                         add_extra_method (acfg, gshared);
3597
3598                         /* end-invoke */
3599                         method = mono_get_delegate_end_invoke (klass);
3600                         create_gsharedvt_inst (acfg, method, &ctx);
3601
3602                         inst = mono_class_inflate_generic_method (method, &ctx);
3603
3604                         m = mono_marshal_get_delegate_end_invoke (inst);
3605                         g_assert (m->is_inflated);
3606
3607                         gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3608                         add_extra_method (acfg, gshared);
3609
3610                 }
3611         }
3612
3613         /* array access wrappers */
3614         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3615                 MonoClass *klass;
3616                 
3617                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3618                 klass = mono_class_get (acfg->image, token);
3619
3620                 if (!klass) {
3621                         mono_loader_clear_error ();
3622                         continue;
3623                 }
3624
3625                 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3626                         MonoMethod *m, *wrapper;
3627
3628                         /* Add runtime-invoke wrappers too */
3629
3630                         m = mono_class_get_method_from_name (klass, "Get", -1);
3631                         g_assert (m);
3632                         wrapper = mono_marshal_get_array_accessor_wrapper (m);
3633                         add_extra_method (acfg, wrapper);
3634                         add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3635
3636                         m = mono_class_get_method_from_name (klass, "Set", -1);
3637                         g_assert (m);
3638                         wrapper = mono_marshal_get_array_accessor_wrapper (m);
3639                         add_extra_method (acfg, wrapper);
3640                         add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3641                 }
3642         }
3643
3644         /* Synchronized wrappers */
3645         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3646                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3647                 method = mono_get_method (acfg->image, token, NULL);
3648
3649                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3650                         if (method->is_generic) {
3651                                 // FIXME:
3652                         } else if (method->klass->generic_container) {
3653                                 MonoGenericContext ctx;
3654                                 MonoMethod *inst, *gshared, *m;
3655
3656                                 /*
3657                                  * Create a generic wrapper for a generic instance, and AOT that.
3658                                  */
3659                                 create_gsharedvt_inst (acfg, method, &ctx);
3660                                 inst = mono_class_inflate_generic_method (method, &ctx);        
3661                                 m = mono_marshal_get_synchronized_wrapper (inst);
3662                                 g_assert (m->is_inflated);
3663                                 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3664                                 add_method (acfg, gshared);
3665                         } else {
3666                                 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3667                         }
3668                 }
3669         }
3670
3671         /* pinvoke wrappers */
3672         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3673                 MonoMethod *method;
3674                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3675
3676                 method = mono_get_method (acfg->image, token, NULL);
3677
3678                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3679                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3680                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3681                 }
3682         }
3683  
3684         /* native-to-managed wrappers */
3685         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3686                 MonoMethod *method;
3687                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3688                 MonoCustomAttrInfo *cattr;
3689                 int j;
3690
3691                 method = mono_get_method (acfg->image, token, NULL);
3692
3693                 /* 
3694                  * Only generate native-to-managed wrappers for methods which have an
3695                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3696                  * name to avoid defining a new assembly to contain it.
3697                  */
3698                 cattr = mono_custom_attrs_from_method (method);
3699
3700                 if (cattr) {
3701                         for (j = 0; j < cattr->num_attrs; ++j)
3702                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3703                                         break;
3704                         if (j < cattr->num_attrs) {
3705                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
3706                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3707                                 const char *p = (const char*)e->data;
3708                                 const char *named;
3709                                 int slen, num_named, named_type, data_type;
3710                                 char *n;
3711                                 MonoType *t;
3712                                 MonoClass *klass;
3713                                 char *export_name = NULL;
3714                                 MonoMethod *wrapper;
3715
3716                                 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3717                                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3718                                         g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks", 
3719                                                 mono_method_full_name (method, TRUE));
3720                                         exit (1);
3721                                 }
3722
3723                                 g_assert (sig->param_count == 1);
3724                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3725
3726                                 /* 
3727                                  * Decode the cattr manually since we can't create objects
3728                                  * during aot compilation.
3729                                  */
3730                                         
3731                                 /* Skip prolog */
3732                                 p += 2;
3733
3734                                 /* From load_cattr_value () in reflection.c */
3735                                 slen = mono_metadata_decode_value (p, &p);
3736                                 n = g_memdup (p, slen + 1);
3737                                 n [slen] = 0;
3738                                 t = mono_reflection_type_from_name (n, acfg->image);
3739                                 g_assert (t);
3740                                 g_free (n);
3741
3742                                 klass = mono_class_from_mono_type (t);
3743                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3744
3745                                 p += slen;
3746
3747                                 num_named = read16 (p);
3748                                 p += 2;
3749
3750                                 g_assert (num_named < 2);
3751                                 if (num_named == 1) {
3752                                         int name_len;
3753                                         char *name;
3754                                         MonoType *prop_type;
3755
3756                                         /* parse ExportSymbol attribute */
3757                                         named = p;
3758                                         named_type = *named;
3759                                         named += 1;
3760                                         data_type = *named;
3761                                         named += 1;
3762
3763                                         name_len = mono_metadata_decode_blob_size (named, &named);
3764                                         name = g_malloc (name_len + 1);
3765                                         memcpy (name, named, name_len);
3766                                         name [name_len] = 0;
3767                                         named += name_len;
3768
3769                                         g_assert (named_type == 0x54);
3770                                         g_assert (!strcmp (name, "ExportSymbol"));
3771
3772                                         prop_type = &mono_defaults.string_class->byval_arg;
3773
3774                                         /* load_cattr_value (), string case */
3775                                         g_assert (*named != (char)0xff);
3776                                         slen = mono_metadata_decode_value (named, &named);
3777                                         export_name = g_malloc (slen + 1);
3778                                         memcpy (export_name, named, slen);
3779                                         export_name [slen] = 0;
3780                                         named += slen;
3781                                 }
3782
3783                                 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3784                                 add_method (acfg, wrapper);
3785                                 if (export_name)
3786                                         g_hash_table_insert (acfg->export_names, wrapper, export_name);
3787                         }
3788                 }
3789
3790                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3791                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3792                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3793                 }
3794         }
3795
3796         /* StructureToPtr/PtrToStructure wrappers */
3797         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3798                 MonoClass *klass;
3799                 
3800                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3801                 klass = mono_class_get (acfg->image, token);
3802
3803                 if (!klass) {
3804                         mono_loader_clear_error ();
3805                         continue;
3806                 }
3807
3808                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3809                         !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3810                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3811                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3812                 }
3813         }
3814 }
3815
3816 static gboolean
3817 has_type_vars (MonoClass *klass)
3818 {
3819         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3820                 return TRUE;
3821         if (klass->rank)
3822                 return has_type_vars (klass->element_class);
3823         if (klass->generic_class) {
3824                 MonoGenericContext *context = &klass->generic_class->context;
3825                 if (context->class_inst) {
3826                         int i;
3827
3828                         for (i = 0; i < context->class_inst->type_argc; ++i)
3829                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3830                                         return TRUE;
3831                 }
3832         }
3833         if (klass->generic_container)
3834                 return TRUE;
3835         return FALSE;
3836 }
3837
3838 static gboolean
3839 is_vt_inst (MonoGenericInst *inst)
3840 {
3841         int i;
3842
3843         for (i = 0; i < inst->type_argc; ++i) {
3844                 MonoType *t = inst->type_argv [i];
3845                 if (t->type == MONO_TYPE_VALUETYPE)
3846                         return TRUE;
3847         }
3848         return FALSE;
3849 }
3850
3851 static gboolean
3852 method_has_type_vars (MonoMethod *method)
3853 {
3854         if (has_type_vars (method->klass))
3855                 return TRUE;
3856
3857         if (method->is_inflated) {
3858                 MonoGenericContext *context = mono_method_get_context (method);
3859                 if (context->method_inst) {
3860                         int i;
3861
3862                         for (i = 0; i < context->method_inst->type_argc; ++i)
3863                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3864                                         return TRUE;
3865                 }
3866         }
3867         return FALSE;
3868 }
3869
3870 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3871
3872 static void
3873 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3874 {
3875         /* This might lead to a huge code blowup so only do it if neccesary */
3876         if (!acfg->aot_opts.full_aot && !force)
3877                 return;
3878
3879         add_generic_class_with_depth (acfg, klass, 0, ref);
3880 }
3881
3882 static gboolean
3883 check_type_depth (MonoType *t, int depth)
3884 {
3885         int i;
3886
3887         if (depth > 8)
3888                 return TRUE;
3889
3890         switch (t->type) {
3891         case MONO_TYPE_GENERICINST: {
3892                 MonoGenericClass *gklass = t->data.generic_class;
3893                 MonoGenericInst *ginst = gklass->context.class_inst;
3894
3895                 if (ginst) {
3896                         for (i = 0; i < ginst->type_argc; ++i) {
3897                                 if (check_type_depth (ginst->type_argv [i], depth + 1))
3898                                         return TRUE;
3899                         }
3900                 }
3901                 break;
3902         }
3903         default:
3904                 break;
3905         }
3906
3907         return FALSE;
3908 }
3909
3910 static void
3911 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3912
3913 /*
3914  * add_generic_class:
3915  *
3916  *   Add all methods of a generic class.
3917  */
3918 static void
3919 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3920 {
3921         MonoMethod *method;
3922         MonoClassField *field;
3923         gpointer iter;
3924         gboolean use_gsharedvt = FALSE;
3925
3926         if (!acfg->ginst_hash)
3927                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3928
3929         mono_class_init (klass);
3930
3931         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3932                 return;
3933
3934         if (has_type_vars (klass))
3935                 return;
3936
3937         if (!klass->generic_class && !klass->rank)
3938                 return;
3939
3940         if (klass->exception_type)
3941                 return;
3942
3943         if (!acfg->ginst_hash)
3944                 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3945
3946         if (g_hash_table_lookup (acfg->ginst_hash, klass))
3947                 return;
3948
3949         if (check_type_depth (&klass->byval_arg, 0))
3950                 return;
3951
3952         if (acfg->aot_opts.log_generics)
3953                 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3954
3955         g_hash_table_insert (acfg->ginst_hash, klass, klass);
3956
3957         /*
3958          * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3959          * Enable this only for some classes since gsharedvt might not support all methods.
3960          */
3961         if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) &&
3962                 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
3963                 use_gsharedvt = TRUE;
3964
3965         iter = NULL;
3966         while ((method = mono_class_get_methods (klass, &iter))) {
3967                 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3968                         /*
3969                          * This is partial sharing, and we can't handle it yet
3970                          */
3971                         continue;
3972                 }
3973                 
3974                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3975                         /* Already added */
3976                         add_types_from_method_header (acfg, method);
3977                         continue;
3978                 }
3979
3980                 if (method->is_generic)
3981                         /* FIXME: */
3982                         continue;
3983
3984                 /*
3985                  * FIXME: Instances which are referenced by these methods are not added,
3986                  * for example Array.Resize<int> for List<int>.Add ().
3987                  */
3988                 add_extra_method_with_depth (acfg, method, depth + 1);
3989         }
3990
3991         iter = NULL;
3992         while ((field = mono_class_get_fields (klass, &iter))) {
3993                 if (field->type->type == MONO_TYPE_GENERICINST)
3994                         add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3995         }
3996
3997         if (klass->delegate) {
3998                 method = mono_get_delegate_invoke (klass);
3999
4000                 method = mono_marshal_get_delegate_invoke (method, NULL);
4001
4002                 if (acfg->aot_opts.log_generics)
4003                         aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4004
4005                 add_method (acfg, method);
4006         }
4007
4008         /* Add superclasses */
4009         if (klass->parent)
4010                 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4011
4012         /* 
4013          * For ICollection<T>, add instances of the helper methods
4014          * in Array, since a T[] could be cast to ICollection<T>.
4015          */
4016         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4017                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1") || !strcmp (klass->name, "IReadOnlyList`1"))) {
4018                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4019                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4020                 gpointer iter;
4021                 char *name_prefix;
4022
4023                 if (!strcmp (klass->name, "IEnumerator`1"))
4024                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4025                 else
4026                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4027
4028                 /* Add the T[]/InternalEnumerator class */
4029                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4030                         MonoClass *nclass;
4031
4032                         iter = NULL;
4033                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4034                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4035                                         break;
4036                         }
4037                         g_assert (nclass);
4038                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4039                         add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4040                 }
4041
4042                 iter = NULL;
4043                 while ((method = mono_class_get_methods (array_class, &iter))) {
4044                         if (strstr (method->name, name_prefix)) {
4045                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4046
4047                                 add_extra_method_with_depth (acfg, m, depth);
4048                         }
4049                 }
4050
4051                 g_free (name_prefix);
4052         }
4053
4054         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4055         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4056                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4057                 MonoClass *icomparable, *gcomparer;
4058                 MonoGenericContext ctx;
4059                 MonoType *args [16];
4060
4061                 memset (&ctx, 0, sizeof (ctx));
4062
4063                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4064                 g_assert (icomparable);
4065                 args [0] = &tclass->byval_arg;
4066                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4067
4068                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4069                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4070                         g_assert (gcomparer);
4071                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4072                 }
4073         }
4074
4075         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4076         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4077                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4078                 MonoClass *iface, *gcomparer;
4079                 MonoGenericContext ctx;
4080                 MonoType *args [16];
4081
4082                 memset (&ctx, 0, sizeof (ctx));
4083
4084                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4085                 g_assert (iface);
4086                 args [0] = &tclass->byval_arg;
4087                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4088
4089                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4090                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4091                         g_assert (gcomparer);
4092                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4093                 }
4094         }
4095 }
4096
4097 static void
4098 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4099 {
4100         int i;
4101         MonoGenericContext ctx;
4102         MonoType *args [16];
4103
4104         if (acfg->aot_opts.no_instances)
4105                 return;
4106
4107         memset (&ctx, 0, sizeof (ctx));
4108
4109         for (i = 0; i < ninsts; ++i) {
4110                 args [0] = insts [i];
4111                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4112                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4113         }
4114 }
4115
4116 static void
4117 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4118 {
4119         MonoMethodHeader *header;
4120         MonoMethodSignature *sig;
4121         int j, depth;
4122
4123         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4124
4125         sig = mono_method_signature (method);
4126
4127         if (sig) {
4128                 for (j = 0; j < sig->param_count; ++j)
4129                         if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4130                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4131         }
4132
4133         header = mono_method_get_header (method);
4134
4135         if (header) {
4136                 for (j = 0; j < header->num_locals; ++j)
4137                         if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4138                                 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4139         } else {
4140                 mono_loader_clear_error ();
4141         }
4142 }
4143
4144 /*
4145  * add_generic_instances:
4146  *
4147  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
4148  */
4149 static void
4150 add_generic_instances (MonoAotCompile *acfg)
4151 {
4152         int i;
4153         guint32 token;
4154         MonoMethod *method;
4155         MonoGenericContext *context;
4156
4157         if (acfg->aot_opts.no_instances)
4158                 return;
4159
4160         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4161                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4162                 method = mono_get_method (acfg->image, token, NULL);
4163
4164                 if (!method)
4165                         continue;
4166
4167                 if (method->klass->image != acfg->image)
4168                         continue;
4169
4170                 context = mono_method_get_context (method);
4171
4172                 if (context && ((context->class_inst && context->class_inst->is_open)))
4173                         continue;
4174
4175                 /*
4176                  * For open methods, create an instantiation which can be passed to the JIT.
4177                  * FIXME: Handle class_inst as well.
4178                  */
4179                 if (context && context->method_inst && context->method_inst->is_open) {
4180                         MonoGenericContext shared_context;
4181                         MonoGenericInst *inst;
4182                         MonoType **type_argv;
4183                         int i;
4184                         MonoMethod *declaring_method;
4185                         gboolean supported = TRUE;
4186
4187                         /* Check that the context doesn't contain open constructed types */
4188                         if (context->class_inst) {
4189                                 inst = context->class_inst;
4190                                 for (i = 0; i < inst->type_argc; ++i) {
4191                                         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)
4192                                                 continue;
4193                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4194                                                 supported = FALSE;
4195                                 }
4196                         }
4197                         if (context->method_inst) {
4198                                 inst = context->method_inst;
4199                                 for (i = 0; i < inst->type_argc; ++i) {
4200                                         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)
4201                                                 continue;
4202                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4203                                                 supported = FALSE;
4204                                 }
4205                         }
4206
4207                         if (!supported)
4208                                 continue;
4209
4210                         memset (&shared_context, 0, sizeof (MonoGenericContext));
4211
4212                         inst = context->class_inst;
4213                         if (inst) {
4214                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4215                                 for (i = 0; i < inst->type_argc; ++i) {
4216                                         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)
4217                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4218                                         else
4219                                                 type_argv [i] = inst->type_argv [i];
4220                                 }
4221                                 
4222                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4223                                 g_free (type_argv);
4224                         }
4225
4226                         inst = context->method_inst;
4227                         if (inst) {
4228                                 type_argv = g_new0 (MonoType*, inst->type_argc);
4229                                 for (i = 0; i < inst->type_argc; ++i) {
4230                                         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)
4231                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
4232                                         else
4233                                                 type_argv [i] = inst->type_argv [i];
4234                                 }
4235
4236                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4237                                 g_free (type_argv);
4238                         }
4239
4240                         if (method->is_generic || method->klass->generic_container)
4241                                 declaring_method = method;
4242                         else
4243                                 declaring_method = mono_method_get_declaring_generic_method (method);
4244
4245                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4246                 }
4247
4248                 /* 
4249                  * If the method is fully sharable, it was already added in place of its
4250                  * generic definition.
4251                  */
4252                 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4253                         continue;
4254
4255                 /*
4256                  * FIXME: Partially shared methods are not shared here, so we end up with
4257                  * many identical methods.
4258                  */
4259                 add_extra_method (acfg, method);
4260         }
4261
4262         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4263                 MonoClass *klass;
4264
4265                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4266
4267                 klass = mono_class_get (acfg->image, token);
4268                 if (!klass || klass->rank) {
4269                         mono_loader_clear_error ();
4270                         continue;
4271                 }
4272
4273                 add_generic_class (acfg, klass, FALSE, "typespec");
4274         }
4275
4276         /* Add types of args/locals */
4277         for (i = 0; i < acfg->methods->len; ++i) {
4278                 method = g_ptr_array_index (acfg->methods, i);
4279                 add_types_from_method_header (acfg, method);
4280         }
4281
4282         if (acfg->image == mono_defaults.corlib) {
4283                 MonoClass *klass;
4284                 MonoType *insts [256];
4285                 int ninsts = 0;
4286
4287                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4288                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4289                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4290                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4291                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4292                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4293                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4294                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4295                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4296                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4297                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4298                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4299
4300                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4301                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4302                 if (klass)
4303                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4304                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4305                 if (klass)
4306                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4307
4308                 /* Add instances of the array generic interfaces for primitive types */
4309                 /* This will add instances of the InternalArray_ helper methods in Array too */
4310                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4311                 if (klass)
4312                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4313                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4314                 if (klass)
4315                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4316                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4317                 if (klass)
4318                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
4319
4320                 /* 
4321                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4322                  * used for all instances of GetGenericValueImpl by the AOT runtime.
4323                  */
4324                 {
4325                         MonoGenericContext ctx;
4326                         MonoType *args [16];
4327                         MonoMethod *get_method;
4328                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4329
4330                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4331
4332                         if (get_method) {
4333                                 memset (&ctx, 0, sizeof (ctx));
4334                                 args [0] = &mono_defaults.object_class->byval_arg;
4335                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4336                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4337                         }
4338                 }
4339
4340                 /* Same for CompareExchange<T>/Exchange<T> */
4341                 {
4342                         MonoGenericContext ctx;
4343                         MonoType *args [16];
4344                         MonoMethod *m;
4345                         MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4346                         gpointer iter = NULL;
4347
4348                         while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4349                                 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4350                                         memset (&ctx, 0, sizeof (ctx));
4351                                         args [0] = &mono_defaults.object_class->byval_arg;
4352                                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4353                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4354                                 }
4355                         }
4356                 }
4357
4358                 /* Same for Volatile.Read/Write<T> */
4359                 {
4360                         MonoGenericContext ctx;
4361                         MonoType *args [16];
4362                         MonoMethod *m;
4363                         MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4364                         gpointer iter = NULL;
4365
4366                         if (volatile_klass) {
4367                                 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4368                                         if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4369                                                 memset (&ctx, 0, sizeof (ctx));
4370                                                 args [0] = &mono_defaults.object_class->byval_arg;
4371                                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4372                                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4373                                         }
4374                                 }
4375                         }
4376                 }
4377         }
4378 }
4379
4380 /*
4381  * is_direct_callable:
4382  *
4383  *   Return whenever the method identified by JI is directly callable without 
4384  * going through the PLT.
4385  */
4386 static gboolean
4387 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4388 {
4389         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4390                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4391                 if (callee_cfg) {
4392                         gboolean direct_callable = TRUE;
4393
4394                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4395                                 direct_callable = FALSE;
4396                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4397                                 // FIXME: Maybe call the wrapper directly ?
4398                                 direct_callable = FALSE;
4399
4400                         if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4401                                 /* Disable this so all calls go through load_method (), see the
4402                                  * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4403                                  * mono_debugger_agent_init ().
4404                                  */
4405                                 direct_callable = FALSE;
4406                         }
4407
4408                         if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4409                                 /* sgen does some initialization when the allocator method is created */
4410                                 direct_callable = FALSE;
4411
4412                         if (direct_callable)
4413                                 return TRUE;
4414                 }
4415         } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4416                 if (acfg->aot_opts.direct_pinvoke)
4417                         return TRUE;
4418         } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4419                 if (acfg->aot_opts.direct_icalls)
4420                         return TRUE;
4421                 return FALSE;
4422         }
4423
4424         return FALSE;
4425 }
4426
4427 #ifdef MONO_ARCH_AOT_SUPPORTED
4428 static const char *
4429 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4430 {
4431         MonoImage *image = method->klass->image;
4432         MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4433         MonoTableInfo *tables = image->tables;
4434         MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4435         MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4436         guint32 im_cols [MONO_IMPLMAP_SIZE];
4437         char *import;
4438
4439         import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4440         if (import != NULL)
4441                 return import;
4442
4443         if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4444                 return NULL;
4445
4446         mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4447
4448         if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4449                 return NULL;
4450
4451         import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4452
4453         g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4454         
4455         return import;
4456 }
4457 #endif
4458
4459 static gint
4460 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4461 {
4462         if (a->native_offset == b->native_offset)
4463                 return a->il_offset - b->il_offset;
4464         else
4465                 return a->native_offset - b->native_offset;
4466 }
4467
4468 /*
4469  * compute_line_numbers:
4470  *
4471  * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4472  * entry.
4473  */
4474 static MonoDebugSourceLocation**
4475 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4476 {
4477         MonoDebugMethodInfo *minfo;
4478         MonoDebugLineNumberEntry *ln_array;
4479         MonoDebugSourceLocation *loc;
4480         int i, prev_line, prev_il_offset;
4481         int *native_to_il_offset = NULL;
4482         MonoDebugSourceLocation **res;
4483         gboolean first;
4484
4485         minfo = mono_debug_lookup_method (method);
4486         if (!minfo)
4487                 return NULL;
4488         // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4489         if (debug_info->code_size != code_size)
4490                 return NULL;
4491
4492         g_assert (code_size);
4493
4494         /* Compute the native->IL offset mapping */
4495
4496         ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4497         memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4498
4499         qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4500
4501         native_to_il_offset = g_new0 (int, code_size + 1);
4502
4503         for (i = 0; i < debug_info->num_line_numbers; ++i) {
4504                 int j;
4505                 MonoDebugLineNumberEntry *lne = &ln_array [i];
4506
4507                 if (i == 0) {
4508                         for (j = 0; j < lne->native_offset; ++j)
4509                                 native_to_il_offset [j] = -1;
4510                 }
4511
4512                 if (i < debug_info->num_line_numbers - 1) {
4513                         MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4514
4515                         for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4516                                 native_to_il_offset [j] = lne->il_offset;
4517                 } else {
4518                         for (j = lne->native_offset; j < code_size; ++j)
4519                                 native_to_il_offset [j] = lne->il_offset;
4520                 }
4521         }
4522         g_free (ln_array);
4523
4524         /* Compute the native->line number mapping */
4525         res = g_new0 (MonoDebugSourceLocation*, code_size);
4526         prev_il_offset = -1;
4527         prev_line = -1;
4528         first = TRUE;
4529         for (i = 0; i < code_size; ++i) {
4530                 int il_offset = native_to_il_offset [i];
4531
4532                 if (il_offset == -1 || il_offset == prev_il_offset)
4533                         continue;
4534                 prev_il_offset = il_offset;
4535                 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4536                 if (!(loc && loc->source_file))
4537                         continue;
4538                 if (loc->row == prev_line) {
4539                         mono_debug_symfile_free_location (loc);
4540                         continue;
4541                 }
4542                 prev_line = loc->row;
4543                 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4544                 if (first)
4545                         /* This will cover the prolog too */
4546                         res [0] = loc;
4547                 else
4548                         res [i] = loc;
4549                 first = FALSE;
4550         }
4551         return res;
4552 }
4553
4554 static int
4555 get_file_index (MonoAotCompile *acfg, const char *source_file)
4556 {
4557         int findex;
4558
4559         // FIXME: Free these
4560         if (!acfg->dwarf_ln_filenames)
4561                 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4562         findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4563         if (!findex) {
4564                 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4565                 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4566                 emit_unset_mode (acfg);
4567                 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4568         }
4569         return findex;
4570 }
4571
4572 #ifdef TARGET_ARM64
4573 #define INST_LEN 4
4574 #else
4575 #define INST_LEN 1
4576 #endif
4577
4578 /*
4579  * emit_and_reloc_code:
4580  *
4581  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4582  * is true, calls are made through the GOT too. This is used for emitting trampolines
4583  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4584  * since trampolines are needed to make PTL work.
4585  */
4586 static void
4587 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4588 {
4589         int i, pindex, start_index, method_index;
4590         GPtrArray *patches;
4591         MonoJumpInfo *patch_info;
4592         MonoMethodHeader *header;
4593         MonoDebugSourceLocation **locs = NULL;
4594         gboolean skip;
4595 #ifdef MONO_ARCH_AOT_SUPPORTED
4596         gboolean direct_call, external_call;
4597         guint32 got_slot;
4598         const char *direct_call_target = 0;
4599         const char *direct_pinvoke;
4600 #endif
4601
4602         if (method) {
4603                 header = mono_method_get_header (method);
4604
4605                 method_index = get_method_index (acfg, method);
4606         }
4607
4608         if (acfg->gas_line_numbers && method && debug_info) {
4609                 locs = compute_line_numbers (method, code_len, debug_info);
4610                 if (!locs) {
4611                         int findex = get_file_index (acfg, "<unknown>");
4612                         emit_unset_mode (acfg);
4613                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4614                 }
4615         }
4616
4617         /* Collect and sort relocations */
4618         patches = g_ptr_array_new ();
4619         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4620                 g_ptr_array_add (patches, patch_info);
4621         g_ptr_array_sort (patches, compare_patches);
4622
4623         start_index = 0;
4624         for (i = 0; i < code_len; i += INST_LEN) {
4625                 patch_info = NULL;
4626                 for (pindex = start_index; pindex < patches->len; ++pindex) {
4627                         patch_info = g_ptr_array_index (patches, pindex);
4628                         if (patch_info->ip.i >= i)
4629                                 break;
4630                 }
4631
4632                 if (locs && locs [i]) {
4633                         MonoDebugSourceLocation *loc = locs [i];
4634                         int findex;
4635
4636                         findex = get_file_index (acfg, loc->source_file);
4637                         emit_unset_mode (acfg);
4638                         fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4639                         mono_debug_symfile_free_location (loc);
4640                 }
4641
4642                 skip = FALSE;
4643 #ifdef MONO_ARCH_AOT_SUPPORTED
4644                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4645                         start_index = pindex;
4646
4647                         switch (patch_info->type) {
4648                         case MONO_PATCH_INFO_NONE:
4649                                 break;
4650                         case MONO_PATCH_INFO_GOT_OFFSET: {
4651                                 int code_size;
4652  
4653                                 arch_emit_got_offset (acfg, code + i, &code_size);
4654                                 i += code_size - INST_LEN;
4655                                 skip = TRUE;
4656                                 patch_info->type = MONO_PATCH_INFO_NONE;
4657                                 break;
4658                         }
4659                         case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4660                                 int code_size, index;
4661                                 char *selector = (void*)patch_info->data.target;
4662
4663                                 if (!acfg->objc_selector_to_index)
4664                                         acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4665                                 if (!acfg->objc_selectors)
4666                                         acfg->objc_selectors = g_ptr_array_new ();
4667                                 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4668                                 if (index)
4669                                         index --;
4670                                 else {
4671                                         index = acfg->objc_selector_index;
4672                                         g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4673                                         g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4674                                         acfg->objc_selector_index ++;
4675                                 }
4676
4677                                 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4678                                 i += code_size - INST_LEN;
4679                                 skip = TRUE;
4680                                 patch_info->type = MONO_PATCH_INFO_NONE;
4681                                 break;
4682                         }
4683                         default: {
4684                                 /*
4685                                  * If this patch is a call, try emitting a direct call instead of
4686                                  * through a PLT entry. This is possible if the called method is in
4687                                  * the same assembly and requires no initialization.
4688                                  */
4689                                 direct_call = FALSE;
4690                                 external_call = FALSE;
4691                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4692                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4693                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4694                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4695                                                 direct_call = TRUE;
4696                                                 direct_call_target = callee_cfg->asm_symbol;
4697                                                 patch_info->type = MONO_PATCH_INFO_NONE;
4698                                                 acfg->stats.direct_calls ++;
4699                                         }
4700
4701                                         acfg->stats.all_calls ++;
4702                                 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4703                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4704                                                 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4705                                                         direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4706                                                 else
4707                                                         direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4708                                                 if (direct_pinvoke) {
4709                                                         direct_call = TRUE;
4710                                                         g_assert (strlen (direct_pinvoke) < 1000);
4711                                                         direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4712                                                 }
4713                                         }
4714                                 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4715                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4716                                         if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4717                                                 /* Call to a C function implementing a jit icall */
4718                                                 direct_call = TRUE;
4719                                                 external_call = TRUE;
4720                                                 g_assert (strlen (sym) < 1000);
4721                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4722                                         }
4723                                 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4724                                         MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4725                                         const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4726                                         if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4727                                                 /* Call to a jit icall without a wrapper */
4728                                                 direct_call = TRUE;
4729                                                 external_call = TRUE;
4730                                                 g_assert (strlen (sym) < 1000);
4731                                                 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4732                                         }
4733                                 }
4734
4735                                 if (direct_call) {
4736                                         patch_info->type = MONO_PATCH_INFO_NONE;
4737                                         acfg->stats.direct_calls ++;
4738                                 }
4739
4740                                 if (!got_only && !direct_call) {
4741                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4742                                         if (plt_entry) {
4743                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4744                                                 direct_call = TRUE;
4745                                                 direct_call_target = plt_entry->symbol;
4746                 
4747                                                 /* Nullify the patch */
4748                                                 patch_info->type = MONO_PATCH_INFO_NONE;
4749                                                 plt_entry->jit_used = TRUE;
4750                                         }
4751                                 }
4752
4753                                 if (direct_call) {
4754                                         int call_size;
4755
4756                                         arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4757                                         i += call_size - INST_LEN;
4758                                 } else {
4759                                         int code_size;
4760
4761                                         got_slot = get_got_offset (acfg, patch_info);
4762
4763                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4764                                         i += code_size - INST_LEN;
4765                                 }
4766                                 skip = TRUE;
4767                         }
4768                         }
4769                 }
4770 #endif /* MONO_ARCH_AOT_SUPPORTED */
4771
4772                 if (!skip) {
4773                         /* Find next patch */
4774                         patch_info = NULL;
4775                         for (pindex = start_index; pindex < patches->len; ++pindex) {
4776                                 patch_info = g_ptr_array_index (patches, pindex);
4777                                 if (patch_info->ip.i >= i)
4778                                         break;
4779                         }
4780
4781                         /* Try to emit multiple bytes at once */
4782                         if (pindex < patches->len && patch_info->ip.i > i) {
4783                                 int limit;
4784
4785                                 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4786                                         if (locs && locs [limit])
4787                                                 break;
4788                                 }
4789
4790                                 emit_code_bytes (acfg, code + i, limit - i);
4791                                 i = limit - INST_LEN;
4792                         } else {
4793                                 emit_code_bytes (acfg, code + i, INST_LEN);
4794                         }
4795                 }
4796         }
4797
4798         g_free (locs);
4799 }
4800
4801 /*
4802  * sanitize_symbol:
4803  *
4804  *   Return a modified version of S which only includes characters permissible in symbols.
4805  */
4806 static char*
4807 sanitize_symbol (MonoAotCompile *acfg, char *s)
4808 {
4809         gboolean process = FALSE;
4810         int i, len;
4811         GString *gs;
4812         char *res;
4813
4814         if (!s)
4815                 return s;
4816
4817         len = strlen (s);
4818         for (i = 0; i < len; ++i)
4819                 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4820                         process = TRUE;
4821         if (!process)
4822                 return s;
4823
4824         gs = g_string_sized_new (len);
4825         for (i = 0; i < len; ++i) {
4826                 guint8 c = s [i];
4827                 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4828                         g_string_append_c (gs, c);
4829                 } else if (c > 0x7f) {
4830                         /* multi-byte utf8 */
4831                         g_string_append_printf (gs, "_0x%x", c);
4832                         i ++;
4833                         c = s [i];
4834                         while (c >> 6 == 0x2) {
4835                                 g_string_append_printf (gs, "%x", c);
4836                                 i ++;
4837                                 c = s [i];
4838                         }
4839                         g_string_append_printf (gs, "_");
4840                         i --;
4841                 } else {
4842                         g_string_append_c (gs, '_');
4843                 }
4844         }
4845
4846         res = mono_mempool_strdup (acfg->mempool, gs->str);
4847         g_string_free (gs, TRUE);
4848         return res;
4849 }
4850
4851 static char*
4852 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4853 {
4854         char *name1, *name2, *cached;
4855         int i, j, len, count;
4856
4857 #ifdef TARGET_MACH
4858         // This is so that we don't accidentally create a local symbol (which starts with 'L')
4859         if (!prefix || !*prefix)
4860                 prefix = "_";
4861 #endif
4862
4863         name1 = mono_method_full_name (method, TRUE);
4864         len = strlen (name1);
4865         name2 = malloc (strlen (prefix) + len + 16);
4866         memcpy (name2, prefix, strlen (prefix));
4867         j = strlen (prefix);
4868         for (i = 0; i < len; ++i) {
4869                 if (isalnum (name1 [i])) {
4870                         name2 [j ++] = name1 [i];
4871                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4872                         i += 2;
4873                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4874                         name2 [j ++] = '_';
4875                         i++;
4876                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4877                 } else
4878                         name2 [j ++] = '_';
4879         }
4880         name2 [j] = '\0';
4881
4882         g_free (name1);
4883
4884         count = 0;
4885         while (g_hash_table_lookup (cache, name2)) {
4886                 sprintf (name2 + j, "_%d", count);
4887                 count ++;
4888         }
4889
4890         cached = g_strdup (name2);
4891         g_hash_table_insert (cache, cached, cached);
4892
4893         return name2;
4894 }
4895
4896 static void
4897 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4898 {
4899         MonoMethod *method;
4900         int method_index;
4901         guint8 *code;
4902         char *debug_sym = NULL;
4903         char *symbol = NULL;
4904         int func_alignment = AOT_FUNC_ALIGNMENT;
4905         MonoMethodHeader *header;
4906         char *export_name;
4907
4908         method = cfg->orig_method;
4909         code = cfg->native_code;
4910         header = cfg->header;
4911
4912         method_index = get_method_index (acfg, method);
4913         symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4914
4915
4916         /* Make the labels local */
4917         emit_section_change (acfg, ".text", 0);
4918         emit_alignment (acfg, func_alignment);
4919         
4920         if (acfg->global_symbols && acfg->need_no_dead_strip)
4921                 fprintf (acfg->fp, "    .no_dead_strip %s\n", cfg->asm_symbol);
4922         
4923         emit_label (acfg, cfg->asm_symbol);
4924
4925         if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4926                 /* 
4927                  * Write a C style symbol for every method, this has two uses:
4928                  * - it works on platforms where the dwarf debugging info is not
4929                  *   yet supported.
4930                  * - it allows the setting of breakpoints of aot-ed methods.
4931                  */
4932                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4933
4934                 if (acfg->need_no_dead_strip)
4935                         fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4936                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4937                 emit_label (acfg, debug_sym);
4938         }
4939
4940         export_name = g_hash_table_lookup (acfg->export_names, method);
4941         if (export_name) {
4942                 /* Emit a global symbol for the method */
4943                 emit_global_inner (acfg, export_name, TRUE);
4944                 emit_label (acfg, export_name);
4945         }
4946
4947         if (cfg->verbose_level > 0)
4948                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4949
4950         acfg->stats.code_size += cfg->code_len;
4951
4952         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4953
4954         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
4955
4956         emit_line (acfg);
4957
4958         if (acfg->aot_opts.write_symbols) {
4959                 emit_symbol_size (acfg, debug_sym, ".");
4960                 g_free (debug_sym);
4961         }
4962
4963         emit_label (acfg, symbol);
4964         g_free (symbol);
4965 }
4966
4967 /**
4968  * encode_patch:
4969  *
4970  *  Encode PATCH_INFO into its disk representation.
4971  */
4972 static void
4973 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4974 {
4975         guint8 *p = buf;
4976
4977         switch (patch_info->type) {
4978         case MONO_PATCH_INFO_NONE:
4979                 break;
4980         case MONO_PATCH_INFO_IMAGE:
4981                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4982                 break;
4983         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4984         case MONO_PATCH_INFO_JIT_TLS_ID:
4985         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4986         case MONO_PATCH_INFO_CASTCLASS_CACHE:
4987                 break;
4988         case MONO_PATCH_INFO_METHOD_REL:
4989                 encode_value ((gint)patch_info->data.offset, p, &p);
4990                 break;
4991         case MONO_PATCH_INFO_SWITCH: {
4992                 gpointer *table = (gpointer *)patch_info->data.table->table;
4993                 int k;
4994
4995                 encode_value (patch_info->data.table->table_size, p, &p);
4996                 for (k = 0; k < patch_info->data.table->table_size; k++)
4997                         encode_value ((int)(gssize)table [k], p, &p);
4998                 break;
4999         }
5000         case MONO_PATCH_INFO_METHODCONST:
5001         case MONO_PATCH_INFO_METHOD:
5002         case MONO_PATCH_INFO_METHOD_JUMP:
5003         case MONO_PATCH_INFO_ICALL_ADDR:
5004         case MONO_PATCH_INFO_METHOD_RGCTX:
5005         case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5006                 encode_method_ref (acfg, patch_info->data.method, p, &p);
5007                 break;
5008         case MONO_PATCH_INFO_INTERNAL_METHOD:
5009         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5010                 guint32 len = strlen (patch_info->data.name);
5011
5012                 encode_value (len, p, &p);
5013
5014                 memcpy (p, patch_info->data.name, len);
5015                 p += len;
5016                 *p++ = '\0';
5017                 break;
5018         }
5019         case MONO_PATCH_INFO_LDSTR: {
5020                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5021                 guint32 token = patch_info->data.token->token;
5022                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5023                 encode_value (image_index, p, &p);
5024                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5025                 break;
5026         }
5027         case MONO_PATCH_INFO_RVA:
5028         case MONO_PATCH_INFO_DECLSEC:
5029         case MONO_PATCH_INFO_LDTOKEN:
5030         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5031                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5032                 encode_value (patch_info->data.token->token, p, &p);
5033                 encode_value (patch_info->data.token->has_context, p, &p);
5034                 if (patch_info->data.token->has_context)
5035                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5036                 break;
5037         case MONO_PATCH_INFO_EXC_NAME: {
5038                 MonoClass *ex_class;
5039
5040                 ex_class =
5041                         mono_class_from_name (mono_defaults.exception_class->image,
5042                                                                   "System", patch_info->data.target);
5043                 g_assert (ex_class);
5044                 encode_klass_ref (acfg, ex_class, p, &p);
5045                 break;
5046         }
5047         case MONO_PATCH_INFO_R4:
5048                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5049                 break;
5050         case MONO_PATCH_INFO_R8:
5051                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5052                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5053                 break;
5054         case MONO_PATCH_INFO_VTABLE:
5055         case MONO_PATCH_INFO_CLASS:
5056         case MONO_PATCH_INFO_IID:
5057         case MONO_PATCH_INFO_ADJUSTED_IID:
5058         case MONO_PATCH_INFO_CLASS_INIT:
5059                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5060                 break;
5061         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5062                 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5063                 if (patch_info->data.del_tramp->method) {
5064                         encode_value (1, p, &p);
5065                         encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5066                 } else {
5067                         encode_value (0, p, &p);
5068                 }
5069                 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5070                 break;
5071         case MONO_PATCH_INFO_FIELD:
5072         case MONO_PATCH_INFO_SFLDA:
5073                 encode_field_info (acfg, patch_info->data.field, p, &p);
5074                 break;
5075         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5076                 break;
5077         case MONO_PATCH_INFO_RGCTX_FETCH: {
5078                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5079                 guint32 offset;
5080                 guint8 *buf2, *p2;
5081
5082                 /* 
5083                  * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5084                  * reference the same method, so encode the method only once.
5085                  */
5086                 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5087                 if (!offset) {
5088                         buf2 = g_malloc (1024);
5089                         p2 = buf2;
5090
5091                         encode_method_ref (acfg, entry->method, p2, &p2);
5092                         g_assert (p2 - buf2 < 1024);
5093
5094                         offset = add_to_blob (acfg, buf2, p2 - buf2);
5095                         g_free (buf2);
5096
5097                         g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5098                 } else {
5099                         offset --;
5100                 }
5101
5102                 encode_value (offset, p, &p);
5103                 g_assert ((int)entry->info_type < 256);
5104                 g_assert (entry->data->type < 256);
5105                 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5106                 encode_patch (acfg, entry->data, p, &p);
5107                 break;
5108         }
5109         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5110         case MONO_PATCH_INFO_MONITOR_ENTER:
5111         case MONO_PATCH_INFO_MONITOR_EXIT:
5112         case MONO_PATCH_INFO_SEQ_POINT_INFO:
5113                 break;
5114         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5115                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5116                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5117                 break;
5118         case MONO_PATCH_INFO_SIGNATURE:
5119                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5120                 break;
5121         case MONO_PATCH_INFO_TLS_OFFSET:
5122                 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5123                 break;
5124         case MONO_PATCH_INFO_GSHAREDVT_CALL:
5125                 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5126                 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5127                 break;
5128         case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5129                 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5130                 int i;
5131
5132                 encode_method_ref (acfg, info->method, p, &p);
5133                 encode_value (info->num_entries, p, &p);
5134                 for (i = 0; i < info->num_entries; ++i) {
5135                         MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5136
5137                         encode_value (template->info_type, p, &p);
5138                         switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5139                         case MONO_PATCH_INFO_CLASS:
5140                                 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5141                                 break;
5142                         case MONO_PATCH_INFO_FIELD:
5143                                 encode_field_info (acfg, template->data, p, &p);
5144                                 break;
5145                         default:
5146                                 g_assert_not_reached ();
5147                                 break;
5148                         }
5149                 }
5150                 break;
5151         }
5152         default:
5153                 g_warning ("unable to handle jump info %d", patch_info->type);
5154                 g_assert_not_reached ();
5155         }
5156
5157         *endbuf = p;
5158 }
5159
5160 static void
5161 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5162 {
5163         guint8 *p = buf;
5164         guint32 pindex, offset;
5165         MonoJumpInfo *patch_info;
5166
5167         encode_value (n_patches, p, &p);
5168
5169         for (pindex = 0; pindex < patches->len; ++pindex) {
5170                 patch_info = g_ptr_array_index (patches, pindex);
5171
5172                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5173                         /* Nothing to do */
5174                         continue;
5175
5176                 offset = get_got_offset (acfg, patch_info);
5177                 encode_value (offset, p, &p);
5178         }
5179
5180         *endbuf = p;
5181 }
5182
5183 static void
5184 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5185 {
5186         MonoMethod *method;
5187         GList *l;
5188         int pindex, buf_size, n_patches;
5189         GPtrArray *patches;
5190         MonoJumpInfo *patch_info;
5191         MonoMethodHeader *header;
5192         guint32 method_index;
5193         guint8 *p, *buf;
5194         guint32 first_got_offset;
5195
5196         method = cfg->orig_method;
5197         header = mono_method_get_header (method);
5198
5199         method_index = get_method_index (acfg, method);
5200
5201         /* Sort relocations */
5202         patches = g_ptr_array_new ();
5203         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5204                 g_ptr_array_add (patches, patch_info);
5205         g_ptr_array_sort (patches, compare_patches);
5206
5207         first_got_offset = acfg->cfgs [method_index]->got_offset;
5208
5209         /**********************/
5210         /* Encode method info */
5211         /**********************/
5212
5213         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5214         p = buf = g_malloc (buf_size);
5215
5216         if (mono_class_get_cctor (method->klass))
5217                 encode_klass_ref (acfg, method->klass, p, &p);
5218         else
5219                 /* Not needed when loading the method */
5220                 encode_value (0, p, &p);
5221
5222         /* String table */
5223         if (cfg->opt & MONO_OPT_SHARED) {
5224                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5225                 for (l = cfg->ldstr_list; l; l = l->next) {
5226                         encode_value ((long)l->data, p, &p);
5227                 }
5228         }
5229         else
5230                 /* Used only in shared mode */
5231                 g_assert (!cfg->ldstr_list);
5232
5233         n_patches = 0;
5234         for (pindex = 0; pindex < patches->len; ++pindex) {
5235                 patch_info = g_ptr_array_index (patches, pindex);
5236                 
5237                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5238                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
5239                         patch_info->type = MONO_PATCH_INFO_NONE;
5240                         /* Nothing to do */
5241                         continue;
5242                 }
5243
5244                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5245                         /* Stored in a GOT slot initialized at module load time */
5246                         patch_info->type = MONO_PATCH_INFO_NONE;
5247                         continue;
5248                 }
5249
5250                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5251                         /* Stored in a GOT slot initialized at module load time */
5252                         patch_info->type = MONO_PATCH_INFO_NONE;
5253                         continue;
5254                 }
5255
5256                 if (is_plt_patch (patch_info)) {
5257                         /* Calls are made through the PLT */
5258                         patch_info->type = MONO_PATCH_INFO_NONE;
5259                         continue;
5260                 }
5261
5262                 n_patches ++;
5263         }
5264
5265         if (n_patches)
5266                 g_assert (cfg->has_got_slots);
5267
5268         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5269
5270         acfg->stats.info_size += p - buf;
5271
5272         g_assert (p - buf < buf_size);
5273
5274         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5275         g_free (buf);
5276 }
5277
5278 static guint32
5279 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5280 {
5281         guint32 cache_index;
5282         guint32 offset;
5283
5284         /* Reuse the unwind module to canonize and store unwind info entries */
5285         cache_index = mono_cache_unwind_info (encoded, encoded_len);
5286
5287         /* Use +/- 1 to distinguish 0s from missing entries */
5288         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5289         if (offset)
5290                 return offset - 1;
5291         else {
5292                 guint8 buf [16];
5293                 guint8 *p;
5294
5295                 /* 
5296                  * It would be easier to use assembler symbols, but the caller needs an
5297                  * offset now.
5298                  */
5299                 offset = acfg->unwind_info_offset;
5300                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5301                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5302
5303                 p = buf;
5304                 encode_value (encoded_len, p, &p);
5305
5306                 acfg->unwind_info_offset += encoded_len + (p - buf);
5307                 return offset;
5308         }
5309 }
5310
5311 static void
5312 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5313 {
5314         MonoMethod *method;
5315         int i, k, buf_size, method_index;
5316         guint32 debug_info_size;
5317         guint8 *code;
5318         MonoMethodHeader *header;
5319         guint8 *p, *buf, *debug_info;
5320         MonoJitInfo *jinfo = cfg->jit_info;
5321         guint32 flags;
5322         gboolean use_unwind_ops = FALSE;
5323         MonoSeqPointInfo *seq_points;
5324
5325         method = cfg->orig_method;
5326         code = cfg->native_code;
5327         header = cfg->header;
5328
5329         method_index = get_method_index (acfg, method);
5330
5331         if (!acfg->aot_opts.nodebug) {
5332                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5333         } else {
5334                 debug_info = NULL;
5335                 debug_info_size = 0;
5336         }
5337
5338         seq_points = cfg->seq_point_info;
5339
5340         buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5341         p = buf = g_malloc (buf_size);
5342
5343         use_unwind_ops = cfg->unwind_ops != NULL;
5344
5345         flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
5346
5347         encode_value (flags, p, &p);
5348
5349         if (use_unwind_ops) {
5350                 guint32 encoded_len;
5351                 guint8 *encoded;
5352                 guint32 unwind_desc;
5353
5354                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5355
5356                 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5357                 g_assert (unwind_desc < 0xffff);
5358                 if (cfg->has_unwind_info_for_epilog) {
5359                         /*
5360                          * The lower 16 bits identify the unwind descriptor, the upper 16 bits contain the offset of
5361                          * the start of the epilog from the end of the method.
5362                          */
5363                         g_assert (cfg->code_size - cfg->epilog_begin < 0xffff);
5364                         encode_value (((cfg->code_size - cfg->epilog_begin) << 16) | unwind_desc, p, &p);
5365                         g_free (encoded);
5366                 } else {
5367                         encode_value (unwind_desc, p, &p);
5368                 }
5369         } else {
5370                 encode_value (jinfo->unwind_info, p, &p);
5371         }
5372
5373         /*Encode the number of holes before the number of clauses to make decoding easier*/
5374         if (jinfo->has_try_block_holes) {
5375                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5376                 encode_value (table->num_holes, p, &p);
5377         }
5378
5379         /* Exception table */
5380         if (cfg->compile_llvm) {
5381                 /*
5382                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5383                  * since the information is only available to llc. Instead, we let llc save the data
5384                  * into the LSDA, and read it from there at runtime.
5385                  */
5386                 /* The assembly might be CIL stripped so emit the data ourselves */
5387                 if (header->num_clauses)
5388                         encode_value (header->num_clauses, p, &p);
5389
5390                 for (k = 0; k < header->num_clauses; ++k) {
5391                         MonoExceptionClause *clause;
5392
5393                         clause = &header->clauses [k];
5394
5395                         encode_value (clause->flags, p, &p);
5396                         if (clause->data.catch_class) {
5397                                 encode_value (1, p, &p);
5398                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5399                         } else {
5400                                 encode_value (0, p, &p);
5401                         }
5402
5403                         /* Emit a list of nesting clauses */
5404                         for (i = 0; i < header->num_clauses; ++i) {
5405                                 gint32 cindex1 = k;
5406                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5407                                 gint32 cindex2 = i;
5408                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5409
5410                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5411                                         encode_value (i, p, &p);
5412                         }
5413                         encode_value (-1, p, &p);
5414                 }
5415         } else {
5416                 if (jinfo->num_clauses)
5417                         encode_value (jinfo->num_clauses, p, &p);
5418
5419                 for (k = 0; k < jinfo->num_clauses; ++k) {
5420                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5421
5422                         encode_value (ei->flags, p, &p);
5423                         encode_value (ei->exvar_offset, p, &p);
5424
5425                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5426                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5427                         else {
5428                                 if (ei->data.catch_class) {
5429                                         guint8 *buf2, *p2;
5430                                         int len;
5431
5432                                         buf2 = g_malloc (4096);
5433                                         p2 = buf2;
5434                                         encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5435                                         len = p2 - buf2;
5436                                         g_assert (len < 4096);
5437                                         encode_value (len, p, &p);
5438                                         memcpy (p, buf2, len);
5439                                         p += p2 - buf2;
5440                                         g_free (buf2);
5441                                 } else {
5442                                         encode_value (0, p, &p);
5443                                 }
5444                         }
5445
5446                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5447                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5448                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5449                 }
5450         }
5451
5452         if (jinfo->has_try_block_holes) {
5453                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5454                 for (i = 0; i < table->num_holes; ++i) {
5455                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5456                         encode_value (hole->clause, p, &p);
5457                         encode_value (hole->length, p, &p);
5458                         encode_value (hole->offset, p, &p);
5459                 }
5460         }
5461
5462         if (jinfo->has_arch_eh_info) {
5463                 MonoArchEHJitInfo *eh_info;
5464
5465                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5466                 encode_value (eh_info->stack_size, p, &p);
5467         }
5468
5469         if (jinfo->has_generic_jit_info) {
5470                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5471                 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5472                 guint8 *p1;
5473                 guint8 *buf2, *p2;
5474                 int len;
5475
5476                 p1 = p;
5477                 encode_value (gi->nlocs, p, &p);
5478                 if (gi->nlocs) {
5479                         for (i = 0; i < gi->nlocs; ++i) {
5480                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
5481
5482                                 encode_value (entry->is_reg ? 1 : 0, p, &p);
5483                                 encode_value (entry->reg, p, &p);
5484                                 if (!entry->is_reg)
5485                                         encode_value (entry->offset, p, &p);
5486                                 if (i == 0)
5487                                         g_assert (entry->from == 0);
5488                                 else
5489                                         encode_value (entry->from, p, &p);
5490                                 encode_value (entry->to, p, &p);
5491                         }
5492                 } else {
5493                         if (!cfg->compile_llvm) {
5494                                 encode_value (gi->has_this ? 1 : 0, p, &p);
5495                                 encode_value (gi->this_reg, p, &p);
5496                                 encode_value (gi->this_offset, p, &p);
5497                         }
5498                 }
5499
5500                 /* 
5501                  * Need to encode jinfo->method too, since it is not equal to 'method'
5502                  * when using generic sharing.
5503                  */
5504                 buf2 = g_malloc (4096);
5505                 p2 = buf2;
5506                 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5507                 len = p2 - buf2;
5508                 g_assert (len < 4096);
5509                 encode_value (len, p, &p);
5510                 memcpy (p, buf2, len);
5511                 p += p2 - buf2;
5512                 g_free (buf2);
5513
5514                 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5515                         MonoMethodInflated *inflated;
5516                         MonoGenericContext *context;
5517                         MonoGenericInst *inst;
5518
5519                         g_assert (jinfo->d.method->is_inflated);
5520                         inflated = (MonoMethodInflated*)jinfo->d.method;
5521                         context = &inflated->context;
5522
5523                         encode_value (1, p, &p);
5524                         if (context->class_inst) {
5525                                 inst = context->class_inst;
5526
5527                                 encode_value (inst->type_argc, p, &p);
5528                                 for (i = 0; i < inst->type_argc; ++i)
5529                                         encode_value (gsctx->var_is_vt [i], p, &p);
5530                         } else {
5531                                 encode_value (0, p, &p);
5532                         }
5533                         if (context->method_inst) {
5534                                 inst = context->method_inst;
5535
5536                                 encode_value (inst->type_argc, p, &p);
5537                                 for (i = 0; i < inst->type_argc; ++i)
5538                                         encode_value (gsctx->mvar_is_vt [i], p, &p);
5539                         } else {
5540                                 encode_value (0, p, &p);
5541                         }
5542                 } else {
5543                         encode_value (0, p, &p);
5544                 }
5545         }
5546
5547         if (seq_points) {
5548                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5549
5550                 encode_value (seq_points->len, p, &p);
5551                 last_il_offset = last_native_offset = 0;
5552                 for (i = 0; i < seq_points->len; ++i) {
5553                         SeqPoint *sp = &seq_points->seq_points [i];
5554                         il_offset = sp->il_offset;
5555                         native_offset = sp->native_offset;
5556                         encode_value (il_offset - last_il_offset, p, &p);
5557                         encode_value (native_offset - last_native_offset, p, &p);
5558                         last_il_offset = il_offset;
5559                         last_native_offset = native_offset;
5560
5561                         encode_value (sp->flags, p, &p);
5562                         encode_value (sp->next_len, p, &p);
5563                         for (j = 0; j < sp->next_len; ++j)
5564                                 encode_value (sp->next [j], p, &p);
5565                 }
5566         }
5567                 
5568         g_assert (debug_info_size < buf_size);
5569
5570         encode_value (debug_info_size, p, &p);
5571         if (debug_info_size) {
5572                 memcpy (p, debug_info, debug_info_size);
5573                 p += debug_info_size;
5574                 g_free (debug_info);
5575         }
5576
5577         /* GC Map */
5578         if (cfg->gc_map) {
5579                 encode_value (cfg->gc_map_size, p, &p);
5580                 /* The GC map requires 4 bytes of alignment */
5581                 while ((gsize)p % 4)
5582                         p ++;
5583                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5584                 p += cfg->gc_map_size;
5585         }
5586
5587         acfg->stats.ex_info_size += p - buf;
5588
5589         g_assert (p - buf < buf_size);
5590
5591         /* Emit info */
5592         /* The GC Map requires 4 byte alignment */
5593         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5594         g_free (buf);
5595 }
5596
5597 static guint32
5598 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5599 {
5600         MonoClass *klass = mono_class_get (acfg->image, token);
5601         guint8 *p, *buf;
5602         int i, buf_size, res;
5603         gboolean no_special_static, cant_encode;
5604         gpointer iter = NULL;
5605
5606         if (!klass) {
5607                 mono_loader_clear_error ();
5608
5609                 buf_size = 16;
5610
5611                 p = buf = g_malloc (buf_size);
5612
5613                 /* Mark as unusable */
5614                 encode_value (-1, p, &p);
5615
5616                 res = add_to_blob (acfg, buf, p - buf);
5617                 g_free (buf);
5618
5619                 return res;
5620         }
5621                 
5622         buf_size = 10240 + (klass->vtable_size * 16);
5623         p = buf = g_malloc (buf_size);
5624
5625         g_assert (klass);
5626
5627         mono_class_init (klass);
5628
5629         mono_class_get_nested_types (klass, &iter);
5630         g_assert (klass->nested_classes_inited);
5631
5632         mono_class_setup_vtable (klass);
5633
5634         /* 
5635          * Emit all the information which is required for creating vtables so
5636          * the runtime does not need to create the MonoMethod structures which
5637          * take up a lot of space.
5638          */
5639
5640         no_special_static = !mono_class_has_special_static_fields (klass);
5641
5642         /* Check whenever we have enough info to encode the vtable */
5643         cant_encode = FALSE;
5644         for (i = 0; i < klass->vtable_size; ++i) {
5645                 MonoMethod *cm = klass->vtable [i];
5646
5647                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5648                         cant_encode = TRUE;
5649         }
5650
5651         mono_class_has_finalizer (klass);
5652
5653         if (klass->generic_container || cant_encode) {
5654                 encode_value (-1, p, &p);
5655         } else {
5656                 encode_value (klass->vtable_size, p, &p);
5657                 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
5658                 if (klass->has_cctor)
5659                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5660                 if (klass->has_finalize)
5661                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5662  
5663                 encode_value (klass->instance_size, p, &p);
5664                 encode_value (mono_class_data_size (klass), p, &p);
5665                 encode_value (klass->packing_size, p, &p);
5666                 encode_value (klass->min_align, p, &p);
5667
5668                 for (i = 0; i < klass->vtable_size; ++i) {
5669                         MonoMethod *cm = klass->vtable [i];
5670
5671                         if (cm)
5672                                 encode_method_ref (acfg, cm, p, &p);
5673                         else
5674                                 encode_value (0, p, &p);
5675                 }
5676         }
5677
5678         acfg->stats.class_info_size += p - buf;
5679
5680         g_assert (p - buf < buf_size);
5681         res = add_to_blob (acfg, buf, p - buf);
5682         g_free (buf);
5683
5684         return res;
5685 }
5686
5687 static char*
5688 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5689 {
5690         char *debug_sym = NULL;
5691         char *s;
5692
5693         switch (ji->type) {
5694         case MONO_PATCH_INFO_METHOD:
5695                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5696                 break;
5697         case MONO_PATCH_INFO_INTERNAL_METHOD:
5698                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5699                 break;
5700         case MONO_PATCH_INFO_CLASS_INIT:
5701                 s = mono_type_get_name (&ji->data.klass->byval_arg);
5702                 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5703                 g_free (s);
5704                 break;
5705         case MONO_PATCH_INFO_RGCTX_FETCH:
5706                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5707                 break;
5708         case MONO_PATCH_INFO_ICALL_ADDR: {
5709                 char *s = get_debug_sym (ji->data.method, "", cache);
5710                 
5711                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5712                 g_free (s);
5713                 break;
5714         }
5715         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5716                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5717                 break;
5718         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5719                 debug_sym = g_strdup_printf ("plt__generic_class_init");
5720                 break;
5721         default:
5722                 break;
5723         }
5724
5725         return sanitize_symbol (acfg, debug_sym);
5726 }
5727
5728 /*
5729  * Calls made from AOTed code are routed through a table of jumps similar to the
5730  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5731  * control to the AOT runtime through a trampoline.
5732  */
5733 static void
5734 emit_plt (MonoAotCompile *acfg)
5735 {
5736         char symbol [128];
5737         int i;
5738
5739         emit_line (acfg);
5740         sprintf (symbol, "plt");
5741
5742         emit_section_change (acfg, ".text", 0);
5743         emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5744         emit_label (acfg, symbol);
5745         emit_label (acfg, acfg->plt_symbol);
5746
5747         for (i = 0; i < acfg->plt_offset; ++i) {
5748                 char *debug_sym = NULL;
5749                 MonoPltEntry *plt_entry = NULL;
5750                 MonoJumpInfo *ji;
5751
5752                 if (i == 0)
5753                         /* 
5754                          * The first plt entry is unused.
5755                          */
5756                         continue;
5757
5758                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5759                 ji = plt_entry->ji;
5760
5761                 if (acfg->llvm) {
5762                         /*
5763                          * If the target is directly callable, alias the plt symbol to point to
5764                          * the method code.
5765                          * FIXME: Use this to simplify emit_and_reloc_code ().
5766                          * FIXME: Avoid the got slot.
5767                          * FIXME: Add support to the binary writer.
5768                          */
5769                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5770                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5771
5772                                 if (callee_cfg) {
5773                                         if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5774                                                 /* LLVM calls the PLT entries using bl, so emit a stub */
5775                                                 emit_set_thumb_mode (acfg);
5776                                                 fprintf (acfg->fp, "\n.thumb_func\n");
5777                                                 emit_label (acfg, plt_entry->llvm_symbol);
5778                                                 fprintf (acfg->fp, "bx pc\n");
5779                                                 fprintf (acfg->fp, "nop\n");
5780                                                 emit_set_arm_mode (acfg);
5781                                                 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5782                                         } else {
5783                                                 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5784                                         }
5785                                         continue;
5786                                 }
5787                         }
5788                 }
5789
5790                 debug_sym = plt_entry->debug_sym;
5791
5792                 if (acfg->thumb_mixed && !plt_entry->jit_used)
5793                         /* Emit only a thumb version */
5794                         continue;
5795
5796                 if (acfg->llvm && !acfg->thumb_mixed)
5797                         emit_label (acfg, plt_entry->llvm_symbol);
5798
5799                 if (debug_sym) {
5800                         if (acfg->need_no_dead_strip) {
5801                                 emit_unset_mode (acfg);
5802                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
5803                         }
5804                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5805                         emit_label (acfg, debug_sym);
5806                 }
5807
5808                 emit_label (acfg, plt_entry->symbol);
5809
5810                 arch_emit_plt_entry (acfg, i);
5811
5812                 if (debug_sym)
5813                         emit_symbol_size (acfg, debug_sym, ".");
5814         }
5815
5816         if (acfg->thumb_mixed) {
5817                 /* Make sure the ARM symbols don't alias the thumb ones */
5818                 emit_zero_bytes (acfg, 16);
5819
5820                 /* 
5821                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5822                  * code.
5823                  */
5824                 for (i = 0; i < acfg->plt_offset; ++i) {
5825                         char *debug_sym = NULL;
5826                         MonoPltEntry *plt_entry = NULL;
5827                         MonoJumpInfo *ji;
5828
5829                         if (i == 0)
5830                                 continue;
5831
5832                         plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5833                         ji = plt_entry->ji;
5834
5835                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5836                                 continue;
5837
5838                         /* Skip plt entries not actually called by LLVM code */
5839                         if (!plt_entry->llvm_used)
5840                                 continue;
5841
5842                         if (acfg->aot_opts.write_symbols) {
5843                                 if (plt_entry->debug_sym)
5844                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5845                         }
5846
5847                         if (debug_sym) {
5848 #if defined(TARGET_MACH)
5849                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
5850                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
5851 #endif
5852                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5853                                 emit_label (acfg, debug_sym);
5854                         }
5855                         fprintf (acfg->fp, "\n.thumb_func\n");
5856
5857                         emit_label (acfg, plt_entry->llvm_symbol);
5858
5859                         arch_emit_llvm_plt_entry (acfg, i);
5860
5861                         if (debug_sym) {
5862                                 emit_symbol_size (acfg, debug_sym, ".");
5863                                 g_free (debug_sym);
5864                         }
5865                 }
5866         }
5867
5868         emit_symbol_size (acfg, acfg->plt_symbol, ".");
5869
5870         sprintf (symbol, "plt_end");
5871         emit_label (acfg, symbol);
5872 }
5873
5874 /*
5875  * emit_trampoline_full:
5876  *
5877  *   If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5878  * create_jit_info_for_trampoline ().
5879  */
5880 static G_GNUC_UNUSED void
5881 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5882 {
5883         char start_symbol [256];
5884         char end_symbol [256];
5885         char symbol [256];
5886         guint32 buf_size, info_offset;
5887         MonoJumpInfo *patch_info;
5888         guint8 *buf, *p;
5889         GPtrArray *patches;
5890         char *name;
5891         guint8 *code;
5892         guint32 code_size;
5893         MonoJumpInfo *ji;
5894         GSList *unwind_ops;
5895
5896         g_assert (info);
5897
5898         name = info->name;
5899         code = info->code;
5900         code_size = info->code_size;
5901         ji = info->ji;
5902         unwind_ops = info->unwind_ops;
5903
5904 #ifdef __native_client_codegen__
5905         mono_nacl_fix_patches (code, ji);
5906 #endif
5907
5908         /* Emit code */
5909
5910         sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5911
5912         emit_section_change (acfg, ".text", 0);
5913         emit_global (acfg, start_symbol, TRUE);
5914         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5915         emit_label (acfg, start_symbol);
5916
5917         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5918         emit_label (acfg, symbol);
5919
5920         /* 
5921          * The code should access everything through the GOT, so we pass
5922          * TRUE here.
5923          */
5924         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5925
5926         emit_symbol_size (acfg, start_symbol, ".");
5927
5928         if (emit_tinfo) {
5929                 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5930                 emit_label (acfg, end_symbol);
5931         }
5932
5933         /* Emit info */
5934
5935         /* Sort relocations */
5936         patches = g_ptr_array_new ();
5937         for (patch_info = ji; patch_info; patch_info = patch_info->next)
5938                 if (patch_info->type != MONO_PATCH_INFO_NONE)
5939                         g_ptr_array_add (patches, patch_info);
5940         g_ptr_array_sort (patches, compare_patches);
5941
5942         buf_size = patches->len * 128 + 128;
5943         buf = g_malloc (buf_size);
5944         p = buf;
5945
5946         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5947         g_assert (p - buf < buf_size);
5948
5949         sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5950
5951         info_offset = add_to_blob (acfg, buf, p - buf);
5952
5953         emit_section_change (acfg, RODATA_SECT, 0);
5954         emit_global (acfg, symbol, FALSE);
5955         emit_label (acfg, symbol);
5956
5957         emit_int32 (acfg, info_offset);
5958
5959         if (emit_tinfo) {
5960                 guint8 *encoded;
5961                 guint32 encoded_len;
5962                 guint32 uw_offset;
5963
5964                 /*
5965                  * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5966                  */
5967                 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5968                 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5969                 g_free (encoded);
5970
5971                 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5972                 emit_int32 (acfg, uw_offset);
5973         }
5974
5975         /* Emit debug info */
5976         if (unwind_ops) {
5977                 char symbol2 [256];
5978
5979                 sprintf (symbol, "%s", name);
5980                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5981
5982                 if (acfg->dwarf)
5983                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5984         }
5985 }
5986
5987 static G_GNUC_UNUSED void
5988 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5989 {
5990         emit_trampoline_full (acfg, got_offset, info, FALSE);
5991 }
5992
5993 static void
5994 emit_trampolines (MonoAotCompile *acfg)
5995 {
5996         char symbol [256];
5997         char end_symbol [256];
5998         int i, tramp_got_offset;
5999         MonoAotTrampoline ntype;
6000 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6001         int tramp_type;
6002 #endif
6003
6004         if (!acfg->aot_opts.full_aot)
6005                 return;
6006         
6007         g_assert (acfg->image->assembly);
6008
6009         /* Currently, we emit most trampolines into the mscorlib AOT image. */
6010         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6011 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6012                 MonoTrampInfo *info;
6013
6014                 /*
6015                  * Emit the generic trampolines.
6016                  *
6017                  * We could save some code by treating the generic trampolines as a wrapper
6018                  * method, but that approach has its own complexities, so we choose the simpler
6019                  * method.
6020                  */
6021                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6022                         /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6023 #ifdef DISABLE_REMOTING
6024                         if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6025                                 continue;
6026 #endif
6027 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6028                         if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6029                                 continue;
6030 #endif
6031                         mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6032                         emit_trampoline (acfg, acfg->got_offset, info);
6033                 }
6034
6035                 mono_arch_get_nullified_class_init_trampoline (&info);
6036                 emit_trampoline (acfg, acfg->got_offset, info);
6037 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6038                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
6039                 emit_trampoline (acfg, acfg->got_offset, info);
6040                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6041                 emit_trampoline (acfg, acfg->got_offset, info);
6042 #endif
6043
6044                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6045                 emit_trampoline (acfg, acfg->got_offset, info);
6046
6047                 /* Emit the exception related code pieces */
6048                 mono_arch_get_restore_context (&info, TRUE);
6049                 emit_trampoline (acfg, acfg->got_offset, info);
6050                 mono_arch_get_call_filter (&info, TRUE);
6051                 emit_trampoline (acfg, acfg->got_offset, info);
6052                 mono_arch_get_throw_exception (&info, TRUE);
6053                 emit_trampoline (acfg, acfg->got_offset, info);
6054                 mono_arch_get_rethrow_exception (&info, TRUE);
6055                 emit_trampoline (acfg, acfg->got_offset, info);
6056                 mono_arch_get_throw_corlib_exception (&info, TRUE);
6057                 emit_trampoline (acfg, acfg->got_offset, info);
6058
6059 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6060                 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6061                 if (info) {
6062                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6063
6064                         /* Create a separate out trampoline for more information in stack traces */
6065                         info->name = g_strdup ("gsharedvt_out_trampoline");
6066                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6067                 }
6068 #endif
6069
6070 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6071                 {
6072                         GSList *l = mono_arch_get_trampolines (TRUE);
6073
6074                         while (l) {
6075                                 MonoTrampInfo *info = l->data;
6076
6077                                 emit_trampoline (acfg, acfg->got_offset, info);
6078                                 l = l->next;
6079                         }
6080                 }
6081 #endif
6082
6083                 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6084                         int offset;
6085
6086                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6087                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6088                         emit_trampoline (acfg, acfg->got_offset, info);
6089
6090                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6091                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6092                         emit_trampoline (acfg, acfg->got_offset, info);
6093                 }
6094
6095 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6096                 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6097                 emit_trampoline (acfg, acfg->got_offset, info);
6098 #endif
6099
6100                 {
6101                         GSList *l;
6102
6103                         /* delegate_invoke_impl trampolines */
6104                         l = mono_arch_get_delegate_invoke_impls ();
6105                         while (l) {
6106                                 MonoTrampInfo *info = l->data;
6107
6108                                 emit_trampoline (acfg, acfg->got_offset, info);
6109                                 l = l->next;
6110                         }
6111                 }
6112
6113 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6114
6115                 /* Emit trampolines which are numerous */
6116
6117                 /*
6118                  * These include the following:
6119                  * - specific trampolines
6120                  * - static rgctx invoke trampolines
6121                  * - imt thunks
6122                  * These trampolines have the same code, they are parameterized by GOT 
6123                  * slots. 
6124                  * They are defined in this file, in the arch_... routines instead of
6125                  * in tramp-<ARCH>.c, since it is easier to do it this way.
6126                  */
6127
6128                 /*
6129                  * When running in aot-only mode, we can't create specific trampolines at 
6130                  * runtime, so we create a few, and save them in the AOT file. 
6131                  * Normal trampolines embed their argument as a literal inside the 
6132                  * trampoline code, we can't do that here, so instead we embed an offset
6133                  * which needs to be added to the trampoline address to get the address of
6134                  * the GOT slot which contains the argument value.
6135                  * The generated trampolines jump to the generic trampolines using another
6136                  * GOT slot, which will be setup by the AOT loader to point to the 
6137                  * generic trampoline code of the given type.
6138                  */
6139
6140                 /*
6141                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6142                  * each class).
6143                  */
6144
6145                 emit_section_change (acfg, ".text", 0);
6146
6147                 tramp_got_offset = acfg->got_offset;
6148
6149                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6150                         switch (ntype) {
6151                         case MONO_AOT_TRAMP_SPECIFIC:
6152                                 sprintf (symbol, "specific_trampolines");
6153                                 break;
6154                         case MONO_AOT_TRAMP_STATIC_RGCTX:
6155                                 sprintf (symbol, "static_rgctx_trampolines");
6156                                 break;
6157                         case MONO_AOT_TRAMP_IMT_THUNK:
6158                                 sprintf (symbol, "imt_thunks");
6159                                 break;
6160                         case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6161                                 sprintf (symbol, "gsharedvt_arg_trampolines");
6162                                 break;
6163                         default:
6164                                 g_assert_not_reached ();
6165                         }
6166
6167                         sprintf (end_symbol, "%s_e", symbol);
6168
6169                         if (acfg->aot_opts.write_symbols)
6170                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6171
6172                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6173                         emit_label (acfg, symbol);
6174
6175                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6176
6177                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6178                                 int tramp_size = 0;
6179
6180                                 switch (ntype) {
6181                                 case MONO_AOT_TRAMP_SPECIFIC:
6182                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6183                                         tramp_got_offset += 2;
6184                                 break;
6185                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
6186                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
6187                                         tramp_got_offset += 2;
6188                                         break;
6189                                 case MONO_AOT_TRAMP_IMT_THUNK:
6190                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6191                                         tramp_got_offset += 1;
6192                                         break;
6193                                 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6194                                         arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);                               
6195                                         tramp_got_offset += 2;
6196                                         break;
6197                                 default:
6198                                         g_assert_not_reached ();
6199                                 }
6200 #ifdef __native_client_codegen__
6201                                 /* align to avoid 32-byte boundary crossings */
6202                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6203 #endif
6204
6205                                 if (!acfg->trampoline_size [ntype]) {
6206                                         g_assert (tramp_size);
6207                                         acfg->trampoline_size [ntype] = tramp_size;
6208                                 }
6209                         }
6210
6211                         emit_label (acfg, end_symbol);
6212                         emit_int32 (acfg, 0);
6213                 }
6214
6215                 arch_emit_specific_trampoline_pages (acfg);
6216
6217                 /* Reserve some entries at the end of the GOT for our use */
6218                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6219         }
6220
6221         acfg->got_offset += acfg->num_trampoline_got_entries;
6222 }
6223
6224 static gboolean
6225 str_begins_with (const char *str1, const char *str2)
6226 {
6227         int len = strlen (str2);
6228         return strncmp (str1, str2, len) == 0;
6229 }
6230
6231 void*
6232 mono_aot_readonly_field_override (MonoClassField *field)
6233 {
6234         ReadOnlyValue *rdv;
6235         for (rdv = readonly_values; rdv; rdv = rdv->next) {
6236                 char *p = rdv->name;
6237                 int len;
6238                 len = strlen (field->parent->name_space);
6239                 if (strncmp (p, field->parent->name_space, len))
6240                         continue;
6241                 p += len;
6242                 if (*p++ != '.')
6243                         continue;
6244                 len = strlen (field->parent->name);
6245                 if (strncmp (p, field->parent->name, len))
6246                         continue;
6247                 p += len;
6248                 if (*p++ != '.')
6249                         continue;
6250                 if (strcmp (p, field->name))
6251                         continue;
6252                 switch (rdv->type) {
6253                 case MONO_TYPE_I1:
6254                         return &rdv->value.i1;
6255                 case MONO_TYPE_I2:
6256                         return &rdv->value.i2;
6257                 case MONO_TYPE_I4:
6258                         return &rdv->value.i4;
6259                 default:
6260                         break;
6261                 }
6262         }
6263         return NULL;
6264 }
6265
6266 static void
6267 add_readonly_value (MonoAotOptions *opts, const char *val)
6268 {
6269         ReadOnlyValue *rdv;
6270         const char *fval;
6271         const char *tval;
6272         /* the format of val is:
6273          * namespace.typename.fieldname=type/value
6274          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6275          */
6276         fval = strrchr (val, '/');
6277         if (!fval) {
6278                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6279                 exit (1);
6280         }
6281         tval = strrchr (val, '=');
6282         if (!tval) {
6283                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6284                 exit (1);
6285         }
6286         rdv = g_new0 (ReadOnlyValue, 1);
6287         rdv->name = g_malloc0 (tval - val + 1);
6288         memcpy (rdv->name, val, tval - val);
6289         tval++;
6290         fval++;
6291         if (strncmp (tval, "i1", 2) == 0) {
6292                 rdv->value.i1 = atoi (fval);
6293                 rdv->type = MONO_TYPE_I1;
6294         } else if (strncmp (tval, "i2", 2) == 0) {
6295                 rdv->value.i2 = atoi (fval);
6296                 rdv->type = MONO_TYPE_I2;
6297         } else if (strncmp (tval, "i4", 2) == 0) {
6298                 rdv->value.i4 = atoi (fval);
6299                 rdv->type = MONO_TYPE_I4;
6300         } else {
6301                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6302                 exit (1);
6303         }
6304         rdv->next = readonly_values;
6305         readonly_values = rdv;
6306 }
6307
6308 static void
6309 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6310 {
6311         gchar **args, **ptr;
6312
6313         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6314         for (ptr = args; ptr && *ptr; ptr ++) {
6315                 const char *arg = *ptr;
6316
6317                 if (str_begins_with (arg, "outfile=")) {
6318                         opts->outfile = g_strdup (arg + strlen ("outfile="));
6319                 } else if (str_begins_with (arg, "save-temps")) {
6320                         opts->save_temps = TRUE;
6321                 } else if (str_begins_with (arg, "keep-temps")) {
6322                         opts->save_temps = TRUE;
6323                 } else if (str_begins_with (arg, "write-symbols")) {
6324                         opts->write_symbols = TRUE;
6325                 } else if (str_begins_with (arg, "no-write-symbols")) {
6326                         opts->write_symbols = FALSE;
6327                 } else if (str_begins_with (arg, "metadata-only")) {
6328                         opts->metadata_only = TRUE;
6329                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6330                         opts->bind_to_runtime_version = TRUE;
6331                 } else if (str_begins_with (arg, "full")) {
6332                         opts->full_aot = TRUE;
6333                 } else if (str_begins_with (arg, "threads=")) {
6334                         opts->nthreads = atoi (arg + strlen ("threads="));
6335                 } else if (str_begins_with (arg, "static")) {
6336                         opts->static_link = TRUE;
6337                         opts->no_dlsym = TRUE;
6338                 } else if (str_begins_with (arg, "asmonly")) {
6339                         opts->asm_only = TRUE;
6340                 } else if (str_begins_with (arg, "asmwriter")) {
6341                         opts->asm_writer = TRUE;
6342                 } else if (str_begins_with (arg, "nodebug")) {
6343                         opts->nodebug = TRUE;
6344                 } else if (str_begins_with (arg, "dwarfdebug")) {
6345                         opts->dwarf_debug = TRUE;
6346                 } else if (str_begins_with (arg, "nopagetrampolines")) {
6347                         opts->use_trampolines_page = FALSE;
6348                 } else if (str_begins_with (arg, "ntrampolines=")) {
6349                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6350                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6351                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6352                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6353                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6354                 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6355                         opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6356                 } else if (str_begins_with (arg, "autoreg")) {
6357                         opts->autoreg = TRUE;
6358                 } else if (str_begins_with (arg, "tool-prefix=")) {
6359                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6360                 } else if (str_begins_with (arg, "soft-debug")) {
6361                         opts->soft_debug = TRUE;
6362                 } else if (str_begins_with (arg, "direct-pinvoke")) {
6363                         opts->direct_pinvoke = TRUE;
6364                 } else if (str_begins_with (arg, "direct-icalls")) {
6365                         opts->direct_icalls = TRUE;
6366 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6367                 } else if (str_begins_with (arg, "iphone-abi")) {
6368                         // older full-aot users did depend on this.
6369 #endif
6370                 } else if (str_begins_with (arg, "no-direct-calls")) {
6371                         opts->no_direct_calls = TRUE;
6372                 } else if (str_begins_with (arg, "print-skipped")) {
6373                         opts->print_skipped_methods = TRUE;
6374                 } else if (str_begins_with (arg, "stats")) {
6375                         opts->stats = TRUE;
6376                 } else if (str_begins_with (arg, "no-instances")) {
6377                         opts->no_instances = TRUE;
6378                 } else if (str_begins_with (arg, "log-generics")) {
6379                         opts->log_generics = TRUE;
6380                 } else if (str_begins_with (arg, "log-instances=")) {
6381                         opts->log_instances = TRUE;
6382                         opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6383                 } else if (str_begins_with (arg, "log-instances")) {
6384                         opts->log_instances = TRUE;
6385                 } else if (str_begins_with (arg, "internal-logfile=")) {
6386                         opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6387                 } else if (str_begins_with (arg, "mtriple=")) {
6388                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6389                 } else if (str_begins_with (arg, "llvm-path=")) {
6390                         opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6391                 } else if (str_begins_with (arg, "readonly-value=")) {
6392                         add_readonly_value (opts, arg + strlen ("readonly-value="));
6393                 } else if (str_begins_with (arg, "info")) {
6394                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6395                         exit (0);
6396                 } else if (str_begins_with (arg, "gc-maps")) {
6397                         mini_gc_enable_gc_maps_for_aot ();
6398                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6399                         printf ("Supported options for --aot:\n");
6400                         printf ("    outfile=\n");
6401                         printf ("    save-temps\n");
6402                         printf ("    keep-temps\n");
6403                         printf ("    write-symbols\n");
6404                         printf ("    metadata-only\n");
6405                         printf ("    bind-to-runtime-version\n");
6406                         printf ("    full\n");
6407                         printf ("    threads=\n");
6408                         printf ("    static\n");
6409                         printf ("    asmonly\n");
6410                         printf ("    asmwriter\n");
6411                         printf ("    nodebug\n");
6412                         printf ("    dwarfdebug\n");
6413                         printf ("    ntrampolines=\n");
6414                         printf ("    nrgctx-trampolines=\n");
6415                         printf ("    nimt-trampolines=\n");
6416                         printf ("    ngsharedvt-trampolines=\n");
6417                         printf ("    autoreg\n");
6418                         printf ("    tool-prefix=\n");
6419                         printf ("    readonly-value=\n");
6420                         printf ("    soft-debug\n");
6421                         printf ("    gc-maps\n");
6422                         printf ("    print-skipped\n");
6423                         printf ("    no-instances\n");
6424                         printf ("    stats\n");
6425                         printf ("    info\n");
6426                         printf ("    help/?\n");
6427                         exit (0);
6428                 } else {
6429                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6430                         exit (1);
6431                 }
6432         }
6433
6434         if (opts->use_trampolines_page) {
6435                 opts->ntrampolines = 0;
6436                 opts->nrgctx_trampolines = 0;
6437                 opts->nimt_trampolines = 0;
6438                 opts->ngsharedvt_arg_trampolines = 0;
6439         }
6440         g_strfreev (args);
6441 }
6442
6443 static void
6444 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6445 {
6446         MonoMethod *method = (MonoMethod*)key;
6447         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6448         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6449         MonoAotCompile *acfg = user_data;
6450
6451         new_ji->image = ji->image;
6452         new_ji->token = ji->token;
6453         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6454 }
6455
6456 static gboolean
6457 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6458 {
6459         if (klass->type_token)
6460                 return TRUE;
6461         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6462                 return TRUE;
6463         if (klass->rank)
6464                 return can_encode_class (acfg, klass->element_class);
6465         return FALSE;
6466 }
6467
6468 static gboolean
6469 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6470 {
6471                 if (method->wrapper_type) {
6472                         switch (method->wrapper_type) {
6473                         case MONO_WRAPPER_NONE:
6474                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6475                         case MONO_WRAPPER_XDOMAIN_INVOKE:
6476                         case MONO_WRAPPER_STFLD:
6477                         case MONO_WRAPPER_LDFLD:
6478                         case MONO_WRAPPER_LDFLDA:
6479                         case MONO_WRAPPER_LDFLD_REMOTE:
6480                         case MONO_WRAPPER_STFLD_REMOTE:
6481                         case MONO_WRAPPER_STELEMREF:
6482                         case MONO_WRAPPER_ISINST:
6483                         case MONO_WRAPPER_PROXY_ISINST:
6484                         case MONO_WRAPPER_ALLOC:
6485                         case MONO_WRAPPER_REMOTING_INVOKE:
6486                         case MONO_WRAPPER_UNKNOWN:
6487                         case MONO_WRAPPER_WRITE_BARRIER:
6488                         case MONO_WRAPPER_DELEGATE_INVOKE:
6489                         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6490                         case MONO_WRAPPER_DELEGATE_END_INVOKE:
6491                         case MONO_WRAPPER_SYNCHRONIZED:
6492                                 break;
6493                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
6494                         case MONO_WRAPPER_CASTCLASS: {
6495                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6496
6497                                 if (info)
6498                                         return TRUE;
6499                                 else
6500                                         return FALSE;
6501                                 break;
6502                         }
6503                         default:
6504                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6505                                 return FALSE;
6506                         }
6507                 } else {
6508                         if (!method->token) {
6509                                 /* The method is part of a constructed type like Int[,].Set (). */
6510                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6511                                         if (method->klass->rank)
6512                                                 return TRUE;
6513                                         return FALSE;
6514                                 }
6515                         }
6516                 }
6517                 return TRUE;
6518 }
6519
6520 static gboolean
6521 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6522 {
6523         switch (patch_info->type) {
6524         case MONO_PATCH_INFO_METHOD:
6525         case MONO_PATCH_INFO_METHODCONST:
6526         case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6527                 MonoMethod *method = patch_info->data.method;
6528
6529                 return can_encode_method (acfg, method);
6530         }
6531         case MONO_PATCH_INFO_VTABLE:
6532         case MONO_PATCH_INFO_CLASS_INIT:
6533         case MONO_PATCH_INFO_CLASS:
6534         case MONO_PATCH_INFO_IID:
6535         case MONO_PATCH_INFO_ADJUSTED_IID:
6536                 if (!can_encode_class (acfg, patch_info->data.klass)) {
6537                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6538                         return FALSE;
6539                 }
6540                 break;
6541         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6542                 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6543                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6544                         return FALSE;
6545                 }
6546                 break;
6547         }
6548         case MONO_PATCH_INFO_RGCTX_FETCH: {
6549                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6550
6551                 if (!can_encode_method (acfg, entry->method))
6552                         return FALSE;
6553                 if (!can_encode_patch (acfg, entry->data))
6554                         return FALSE;
6555                 break;
6556         }
6557         default:
6558                 break;
6559         }
6560
6561         return TRUE;
6562 }
6563
6564 /*
6565  * compile_method:
6566  *
6567  *   AOT compile a given method.
6568  * This function might be called by multiple threads, so it must be thread-safe.
6569  */
6570 static void
6571 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6572 {
6573         MonoCompile *cfg;
6574         MonoJumpInfo *patch_info;
6575         gboolean skip;
6576         int index, depth;
6577         MonoMethod *wrapped;
6578
6579         if (acfg->aot_opts.metadata_only)
6580                 return;
6581
6582         mono_acfg_lock (acfg);
6583         index = get_method_index (acfg, method);
6584         mono_acfg_unlock (acfg);
6585
6586         /* fixme: maybe we can also precompile wrapper methods */
6587         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6588                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6589                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6590                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6591                 return;
6592         }
6593
6594         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6595                 return;
6596
6597         wrapped = mono_marshal_method_from_wrapper (method);
6598         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6599                 // FIXME: The wrapper should be generic too, but it is not
6600                 return;
6601
6602         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6603                 return;
6604
6605         InterlockedIncrement (&acfg->stats.mcount);
6606
6607 #if 0
6608         if (method->is_generic || method->klass->generic_container) {
6609                 InterlockedIncrement (&acfg->stats.genericcount);
6610                 return;
6611         }
6612 #endif
6613
6614         //acfg->aot_opts.print_skipped_methods = TRUE;
6615
6616         /*
6617          * Since these methods are the only ones which are compiled with
6618          * AOT support, and they are not used by runtime startup/shutdown code,
6619          * the runtime will not see AOT methods during AOT compilation,so it
6620          * does not need to support them by creating a fake GOT etc.
6621          */
6622         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
6623         mono_loader_clear_error ();
6624
6625         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6626                 if (acfg->aot_opts.print_skipped_methods)
6627                         printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6628                 InterlockedIncrement (&acfg->stats.genericcount);
6629                 return;
6630         }
6631         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6632                 if (acfg->aot_opts.print_skipped_methods)
6633                         printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6634                 /* Let the exception happen at runtime */
6635                 return;
6636         }
6637
6638         if (cfg->disable_aot) {
6639                 if (acfg->aot_opts.print_skipped_methods)
6640                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6641                 InterlockedIncrement (&acfg->stats.ocount);
6642                 mono_destroy_compile (cfg);
6643                 return;
6644         }
6645         cfg->method_index = index;
6646
6647         /* Nullify patches which need no aot processing */
6648         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6649                 switch (patch_info->type) {
6650                 case MONO_PATCH_INFO_LABEL:
6651                 case MONO_PATCH_INFO_BB:
6652                         patch_info->type = MONO_PATCH_INFO_NONE;
6653                         break;
6654                 default:
6655                         break;
6656                 }
6657         }
6658
6659         /* Collect method->token associations from the cfg */
6660         mono_acfg_lock (acfg);
6661         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6662         mono_acfg_unlock (acfg);
6663
6664         /*
6665          * Check for absolute addresses.
6666          */
6667         skip = FALSE;
6668         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6669                 switch (patch_info->type) {
6670                 case MONO_PATCH_INFO_ABS:
6671                         /* unable to handle this */
6672                         skip = TRUE;    
6673                         break;
6674                 default:
6675                         break;
6676                 }
6677         }
6678
6679         if (skip) {
6680                 if (acfg->aot_opts.print_skipped_methods)
6681                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6682                 InterlockedIncrement (&acfg->stats.abscount);
6683                 mono_destroy_compile (cfg);
6684                 return;
6685         }
6686
6687         /* Lock for the rest of the code */
6688         mono_acfg_lock (acfg);
6689
6690         /*
6691          * Check for methods/klasses we can't encode.
6692          */
6693         skip = FALSE;
6694         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6695                 if (!can_encode_patch (acfg, patch_info))
6696                         skip = TRUE;
6697         }
6698
6699         if (skip) {
6700                 if (acfg->aot_opts.print_skipped_methods)
6701                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6702                 acfg->stats.ocount++;
6703                 mono_destroy_compile (cfg);
6704                 mono_acfg_unlock (acfg);
6705                 return;
6706         }
6707
6708         if (method->is_inflated && acfg->aot_opts.log_instances) {
6709                 if (acfg->instances_logfile)
6710                         fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6711                 else
6712                         printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6713         }
6714
6715         /* Adds generic instances referenced by this method */
6716         /* 
6717          * The depth is used to avoid infinite loops when generic virtual recursion is 
6718          * encountered.
6719          */
6720         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6721         if (!acfg->aot_opts.no_instances && depth < 32) {
6722                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6723                         switch (patch_info->type) {
6724                         case MONO_PATCH_INFO_METHOD: {
6725                                 MonoMethod *m = patch_info->data.method;
6726                                 if (m->is_inflated) {
6727                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
6728                                                   mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6729                                                 !method_has_type_vars (m)) {
6730                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6731                                                         if (acfg->aot_opts.full_aot)
6732                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6733                                                 } else {
6734                                                         add_extra_method_with_depth (acfg, m, depth + 1);
6735                                                         add_types_from_method_header (acfg, m);
6736                                                 }
6737                                         }
6738                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6739                                 }
6740                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6741                                         add_extra_method_with_depth (acfg, m, depth + 1);
6742                                 break;
6743                         }
6744                         case MONO_PATCH_INFO_VTABLE: {
6745                                 MonoClass *klass = patch_info->data.klass;
6746
6747                                 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6748                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6749                                 break;
6750                         }
6751                         case MONO_PATCH_INFO_SFLDA: {
6752                                 MonoClass *klass = patch_info->data.field->parent;
6753
6754                                 /* The .cctor needs to run at runtime. */
6755                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6756                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6757                                 break;
6758                         }
6759                         default:
6760                                 break;
6761                         }
6762                 }
6763         }
6764
6765         /* Determine whenever the method has GOT slots */
6766         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6767                 switch (patch_info->type) {
6768                 case MONO_PATCH_INFO_GOT_OFFSET:
6769                 case MONO_PATCH_INFO_NONE:
6770                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6771                         break;
6772                 case MONO_PATCH_INFO_IMAGE:
6773                         /* The assembly is stored in GOT slot 0 */
6774                         if (patch_info->data.image != acfg->image)
6775                                 cfg->has_got_slots = TRUE;
6776                         break;
6777                 default:
6778                         if (!is_plt_patch (patch_info))
6779                                 cfg->has_got_slots = TRUE;
6780                         break;
6781                 }
6782         }
6783
6784         if (!cfg->has_got_slots)
6785                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6786
6787         /* 
6788          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6789          */
6790         /* Make a copy of the patch info which is in the mempool */
6791         {
6792                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6793
6794                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6795                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6796
6797                         if (!patches)
6798                                 patches = new_patch_info;
6799                         else
6800                                 patches_end->next = new_patch_info;
6801                         patches_end = new_patch_info;
6802                 }
6803                 cfg->patch_info = patches;
6804         }
6805         /* Make a copy of the unwind info */
6806         {
6807                 GSList *l, *unwind_ops;
6808                 MonoUnwindOp *op;
6809
6810                 unwind_ops = NULL;
6811                 for (l = cfg->unwind_ops; l; l = l->next) {
6812                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6813                         memcpy (op, l->data, sizeof (MonoUnwindOp));
6814                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6815                 }
6816                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6817         }
6818         /* Make a copy of the argument/local info */
6819         {
6820                 MonoInst **args, **locals;
6821                 MonoMethodSignature *sig;
6822                 MonoMethodHeader *header;
6823                 int i;
6824                 
6825                 sig = mono_method_signature (method);
6826                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6827                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6828                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6829                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6830                 }
6831                 cfg->args = args;
6832
6833                 header = mono_method_get_header (method);
6834                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6835                 for (i = 0; i < header->num_locals; ++i) {
6836                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6837                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6838                 }
6839                 cfg->locals = locals;
6840         }
6841
6842         /* Free some fields used by cfg to conserve memory */
6843         mono_mempool_destroy (cfg->mempool);
6844         cfg->mempool = NULL;
6845         g_free (cfg->varinfo);
6846         cfg->varinfo = NULL;
6847         g_free (cfg->vars);
6848         cfg->vars = NULL;
6849         if (cfg->rs) {
6850                 mono_regstate_free (cfg->rs);
6851                 cfg->rs = NULL;
6852         }
6853
6854         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
6855
6856         while (index >= acfg->cfgs_size) {
6857                 MonoCompile **new_cfgs;
6858                 int new_size;
6859
6860                 new_size = acfg->cfgs_size * 2;
6861                 new_cfgs = g_new0 (MonoCompile*, new_size);
6862                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6863                 g_free (acfg->cfgs);
6864                 acfg->cfgs = new_cfgs;
6865                 acfg->cfgs_size = new_size;
6866         }
6867         acfg->cfgs [index] = cfg;
6868
6869         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6870
6871         /*
6872         if (cfg->orig_method->wrapper_type)
6873                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6874         */
6875
6876         mono_acfg_unlock (acfg);
6877
6878         InterlockedIncrement (&acfg->stats.ccount);
6879 }
6880  
6881 static void
6882 compile_thread_main (gpointer *user_data)
6883 {
6884         MonoDomain *domain = user_data [0];
6885         MonoAotCompile *acfg = user_data [1];
6886         GPtrArray *methods = user_data [2];
6887         int i;
6888
6889         mono_thread_attach (domain);
6890
6891         for (i = 0; i < methods->len; ++i)
6892                 compile_method (acfg, g_ptr_array_index (methods, i));
6893 }
6894
6895 static void
6896 load_profile_files (MonoAotCompile *acfg)
6897 {
6898         FILE *infile;
6899         char *tmp;
6900         int file_index, res, method_index, i;
6901         char ver [256];
6902         guint32 token;
6903         GList *unordered, *l;
6904         gboolean found;
6905
6906         file_index = 0;
6907         while (TRUE) {
6908                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6909
6910                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6911                         g_free (tmp);
6912                         break;
6913                 }
6914
6915                 infile = fopen (tmp, "r");
6916                 g_assert (infile);
6917
6918                 printf ("Using profile data file '%s'\n", tmp);
6919                 g_free (tmp);
6920
6921                 file_index ++;
6922
6923                 res = fscanf (infile, "%32s\n", ver);
6924                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6925                         printf ("Profile file has wrong version or invalid.\n");
6926                         fclose (infile);
6927                         continue;
6928                 }
6929
6930                 while (TRUE) {
6931                         char name [1024];
6932                         MonoMethodDesc *desc;
6933                         MonoMethod *method;
6934
6935                         if (fgets (name, 1023, infile) == NULL)
6936                                 break;
6937
6938                         /* Kill the newline */
6939                         if (strlen (name) > 0)
6940                                 name [strlen (name) - 1] = '\0';
6941
6942                         desc = mono_method_desc_new (name, TRUE);
6943
6944                         method = mono_method_desc_search_in_image (desc, acfg->image);
6945
6946                         if (method && mono_method_get_token (method)) {
6947                                 token = mono_method_get_token (method);
6948                                 method_index = mono_metadata_token_index (token) - 1;
6949
6950                                 found = FALSE;
6951                                 for (i = 0; i < acfg->method_order->len; ++i) {
6952                                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6953                                                 found = TRUE;
6954                                                 break;
6955                                         }
6956                                 }
6957                                 if (!found)
6958                                         g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6959                         } else {
6960                                 //printf ("No method found matching '%s'.\n", name);
6961                         }
6962                 }
6963                 fclose (infile);
6964         }
6965
6966         /* Add missing methods */
6967         unordered = NULL;
6968         for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6969                 found = FALSE;
6970                 for (i = 0; i < acfg->method_order->len; ++i) {
6971                         if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6972                                 found = TRUE;
6973                                 break;
6974                         }
6975                 }
6976                 if (!found)
6977                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6978         }
6979         unordered = g_list_reverse (unordered);
6980         for (l = unordered; l; l = l->next)
6981                 g_ptr_array_add (acfg->method_order, l->data);
6982 }
6983  
6984 /* Used by the LLVM backend */
6985 guint32
6986 mono_aot_get_got_offset (MonoJumpInfo *ji)
6987 {
6988         return get_got_offset (llvm_acfg, ji);
6989 }
6990
6991 char*
6992 mono_aot_get_method_name (MonoCompile *cfg)
6993 {
6994         if (llvm_acfg->aot_opts.static_link)
6995                 /* Include the assembly name too to avoid duplicate symbol errors */
6996                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6997         else
6998                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6999 }
7000
7001 char*
7002 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7003 {
7004         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7005         MonoPltEntry *plt_entry;
7006
7007         ji->type = type;
7008         ji->data.target = data;
7009
7010         if (!can_encode_patch (llvm_acfg, ji))
7011                 return NULL;
7012
7013         plt_entry = get_plt_entry (llvm_acfg, ji);
7014         plt_entry->llvm_used = TRUE;
7015
7016 #if defined(TARGET_MACH)
7017         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7018 #else
7019         return g_strdup_printf (plt_entry->llvm_symbol);
7020 #endif
7021 }
7022
7023 int
7024 mono_aot_get_method_index (MonoMethod *method)
7025 {
7026         g_assert (llvm_acfg);
7027         return get_method_index (llvm_acfg, method);
7028 }
7029
7030 MonoJumpInfo*
7031 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7032 {
7033         MonoJumpInfo *res;
7034
7035         mono_acfg_lock (llvm_acfg);
7036         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7037         mono_acfg_unlock (llvm_acfg);
7038
7039         return res;
7040 }
7041
7042 #ifdef ENABLE_LLVM
7043
7044 /*
7045  * emit_llvm_file:
7046  *
7047  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7048  * tools.
7049  */
7050 static void
7051 emit_llvm_file (MonoAotCompile *acfg)
7052 {
7053         char *command, *opts, *tempbc;
7054         int i;
7055         MonoJumpInfo *patch_info;
7056
7057         /*
7058          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
7059          * to it.
7060          */
7061
7062         /* Compute the final size of the got */
7063         for (i = 0; i < acfg->nmethods; ++i) {
7064                 if (acfg->cfgs [i]) {
7065                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
7066                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
7067                                         if (!is_plt_patch (patch_info))
7068                                                 get_got_offset (acfg, patch_info);
7069                                         else
7070                                                 get_plt_entry (acfg, patch_info);
7071                                 }
7072                         }
7073                 }
7074         }
7075
7076         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
7077
7078         if (acfg->aot_opts.full_aot) {
7079                 int ntype;
7080
7081                 /* 
7082                  * Need to add the got entries used by the trampolines.
7083                  * This is only a conservative approximation.
7084                  */
7085                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
7086                         /* For the generic + rgctx trampolines */
7087                         acfg->final_got_size += 400;
7088                         /* For the specific trampolines */
7089                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
7090                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
7091                 }
7092         }
7093
7094
7095         tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7096         mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
7097         g_free (tempbc);
7098
7099         /*
7100          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7101          * a lot of time, and doesn't seem to save much space.
7102          * The following optimizations cannot be enabled:
7103          * - 'tailcallelim'
7104          * - 'jump-threading' changes our blockaddress references to int constants.
7105          * - 'basiccg' fails because it contains:
7106          * if (CS && !isa<IntrinsicInst>(II)) {
7107          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7108          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7109          * The opt list below was produced by taking the output of:
7110          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7111          * then removing tailcallelim + the global opts.
7112          * strip-dead-prototypes deletes unused intrinsics definitions.
7113          */
7114         opts = g_strdup ("-instcombine -simplifycfg");
7115         //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7116         /* The dse pass is disabled because of #13734 and #17616 */
7117         /*
7118          * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7119          * // If we have no DataLayout information around, then the size of the store
7120          *  // is inferrable from the pointee type.  If they are the same type, then
7121          * // we know that the store is safe.
7122          * if (AA.getDataLayout() == 0 &&
7123          * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7124          * return OverwriteComplete;
7125          * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7126          */
7127         opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7128 #if 1
7129         command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7130         aot_printf (acfg, "Executing opt: %s\n", command);
7131         if (system (command) != 0) {
7132                 exit (1);
7133         }
7134 #endif
7135         g_free (opts);
7136
7137         if (!acfg->llc_args)
7138                 acfg->llc_args = g_string_new ("");
7139
7140         /* Verbose asm slows down llc greatly */
7141         g_string_append (acfg->llc_args, " -asm-verbose=false");
7142
7143         if (acfg->aot_opts.mtriple)
7144                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7145
7146 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7147         /* ios requires PIC code now */
7148         g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7149 #else
7150         if (llvm_acfg->aot_opts.static_link)
7151                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7152         else
7153                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7154 #endif
7155         unlink (acfg->tmpfname);
7156
7157         command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpbasename);
7158
7159         aot_printf (acfg, "Executing llc: %s\n", command);
7160
7161         if (system (command) != 0) {
7162                 exit (1);
7163         }
7164 }
7165 #endif
7166
7167 static void
7168 emit_code (MonoAotCompile *acfg)
7169 {
7170         int oindex, i, prev_index;
7171         char symbol [256];
7172
7173 #if defined(TARGET_POWERPC64)
7174         sprintf (symbol, ".Lgot_addr");
7175         emit_section_change (acfg, ".text", 0);
7176         emit_alignment (acfg, 8);
7177         emit_label (acfg, symbol);
7178         emit_pointer (acfg, acfg->got_symbol);
7179 #endif
7180
7181         /* 
7182          * This global symbol is used to compute the address of each method using the
7183          * code_offsets array. It is also used to compute the memory ranges occupied by
7184          * AOT code, so it must be equal to the address of the first emitted method.
7185          */
7186         emit_section_change (acfg, ".text", 0);
7187         emit_alignment (acfg, 8);
7188         if (acfg->llvm) {
7189                 for (i = 0; i < acfg->nmethods; ++i) {
7190                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7191                                 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7192                                 break;
7193                         }
7194                 }
7195         }
7196         if (!acfg->methods_symbol) {
7197                 sprintf (symbol, "methods");
7198                 emit_label (acfg, symbol);
7199                 acfg->methods_symbol = g_strdup (symbol);
7200         }
7201
7202         /* 
7203          * Emit some padding so the local symbol for the first method doesn't have the
7204          * same address as 'methods'.
7205          */
7206 #if defined(__default_codegen__)
7207         emit_zero_bytes (acfg, 16);
7208 #elif defined(__native_client_codegen__)
7209         {
7210                 const int kPaddingSize = 16;
7211                 guint8 pad_buffer[kPaddingSize];
7212                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7213                 emit_bytes (acfg, pad_buffer, kPaddingSize);
7214         }
7215 #endif
7216
7217         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7218                 MonoCompile *cfg;
7219                 MonoMethod *method;
7220
7221                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7222
7223                 cfg = acfg->cfgs [i];
7224
7225                 if (!cfg)
7226                         continue;
7227
7228                 method = cfg->orig_method;
7229
7230                 /* Emit unbox trampoline */
7231                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7232                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7233
7234                         emit_section_change (acfg, ".text", 0);
7235 #ifdef __native_client_codegen__
7236                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7237 #endif
7238
7239                         if (acfg->thumb_mixed && cfg->compile_llvm) {
7240                                 emit_set_thumb_mode (acfg);
7241                                 fprintf (acfg->fp, "\n.thumb_func\n");
7242                         }
7243
7244                         emit_label (acfg, symbol);
7245
7246                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7247
7248                         if (acfg->thumb_mixed && cfg->compile_llvm) {
7249                                 emit_set_arm_mode (acfg);
7250                         }
7251                 }
7252
7253                 if (cfg->compile_llvm)
7254                         acfg->stats.llvm_count ++;
7255                 else
7256                         emit_method_code (acfg, cfg);
7257         }
7258
7259         sprintf (symbol, "methods_end");
7260         emit_section_change (acfg, ".text", 0);
7261         emit_alignment (acfg, 8);
7262         emit_label (acfg, symbol);
7263         /* To distinguish it from the next symbol */
7264         emit_int32 (acfg, 0);
7265
7266         /* 
7267          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7268          * from optimizing them away, since it doesn't see that code_offsets references them.
7269          * JITted methods don't need this since they are referenced using assembler local
7270          * symbols.
7271          * FIXME: This is why write-symbols doesn't work on OSX ?
7272          */
7273         if (acfg->llvm && acfg->need_no_dead_strip) {
7274                 fprintf (acfg->fp, "\n");
7275                 for (i = 0; i < acfg->nmethods; ++i) {
7276                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7277                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7278                 }
7279         }
7280
7281         if (acfg->direct_method_addresses) {
7282                 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7283
7284                 /*
7285                  * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7286                  * This is PIE code, and the linker can update it if needed.
7287                  */
7288                 sprintf (symbol, "method_addresses");
7289                 emit_section_change (acfg, ".text", 1);
7290                 emit_alignment (acfg, 8);
7291                 emit_label (acfg, symbol);
7292                 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7293                 emit_unset_mode (acfg);
7294                 if (acfg->need_no_dead_strip)
7295                         fprintf (acfg->fp, "    .no_dead_strip %s\n", symbol);
7296
7297                 for (i = 0; i < acfg->nmethods; ++i) {
7298 #ifdef MONO_ARCH_AOT_SUPPORTED
7299                         int call_size;
7300
7301                         if (acfg->cfgs [i])
7302                                 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7303                         else
7304                                 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7305 #endif
7306                 }
7307
7308                 sprintf (symbol, "method_addresses_end");
7309                 emit_label (acfg, symbol);
7310
7311                 /* Empty */
7312                 sprintf (symbol, "code_offsets");
7313                 emit_section_change (acfg, RODATA_SECT, 1);
7314                 emit_alignment (acfg, 8);
7315                 emit_label (acfg, symbol);
7316                 emit_int32 (acfg, 0);
7317         } else {
7318                 sprintf (symbol, "code_offsets");
7319                 emit_section_change (acfg, RODATA_SECT, 1);
7320                 emit_alignment (acfg, 8);
7321                 emit_label (acfg, symbol);
7322
7323                 acfg->stats.offsets_size += acfg->nmethods * 4;
7324
7325                 for (i = 0; i < acfg->nmethods; ++i) {
7326                         if (acfg->cfgs [i]) {
7327                                 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7328                         } else {
7329                                 emit_int32 (acfg, 0xffffffff);
7330                         }
7331                 }
7332         }
7333         emit_line (acfg);
7334
7335         /* Emit a sorted table mapping methods to their unbox trampolines */
7336         sprintf (symbol, "unbox_trampolines");
7337         if (acfg->direct_method_addresses)
7338                 emit_section_change (acfg, ".text", 0);
7339         else
7340                 emit_section_change (acfg, RODATA_SECT, 0);
7341         emit_alignment (acfg, 8);
7342         emit_label (acfg, symbol);
7343
7344         prev_index = -1;
7345         for (i = 0; i < acfg->nmethods; ++i) {
7346                 MonoCompile *cfg;
7347                 MonoMethod *method;
7348                 int index;
7349
7350                 cfg = acfg->cfgs [i];
7351                 if (!cfg)
7352                         continue;
7353
7354                 method = cfg->orig_method;
7355
7356                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7357 #ifdef MONO_ARCH_AOT_SUPPORTED
7358                         int call_size;
7359 #endif
7360
7361                         index = get_method_index (acfg, method);
7362                         sprintf (symbol, "ut_%d", index);
7363
7364                         emit_int32 (acfg, index);
7365                         if (acfg->direct_method_addresses) {
7366 #ifdef MONO_ARCH_AOT_SUPPORTED
7367                                 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7368 #endif
7369                         } else {
7370                                 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7371                         }
7372                         /* Make sure the table is sorted by index */
7373                         g_assert (index > prev_index);
7374                         prev_index = index;
7375                 }
7376         }
7377         sprintf (symbol, "unbox_trampolines_end");
7378         emit_label (acfg, symbol);
7379         emit_int32 (acfg, 0);
7380 }
7381
7382 static void
7383 emit_info (MonoAotCompile *acfg)
7384 {
7385         int oindex, i;
7386         char symbol [256];
7387         gint32 *offsets;
7388
7389         offsets = g_new0 (gint32, acfg->nmethods);
7390
7391         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7392                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7393
7394                 if (acfg->cfgs [i]) {
7395                         emit_method_info (acfg, acfg->cfgs [i]);
7396                         offsets [i] = acfg->cfgs [i]->method_info_offset;
7397                 } else {
7398                         offsets [i] = 0;
7399                 }
7400         }
7401
7402         sprintf (symbol, "method_info_offsets");
7403         emit_section_change (acfg, RODATA_SECT, 1);
7404         emit_alignment (acfg, 8);
7405         emit_label (acfg, symbol);
7406
7407         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7408
7409         g_free (offsets);
7410 }
7411
7412 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7413
7414 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7415 #define mix(a,b,c) { \
7416         a -= c;  a ^= rot(c, 4);  c += b; \
7417         b -= a;  b ^= rot(a, 6);  a += c; \
7418         c -= b;  c ^= rot(b, 8);  b += a; \
7419         a -= c;  a ^= rot(c,16);  c += b; \
7420         b -= a;  b ^= rot(a,19);  a += c; \
7421         c -= b;  c ^= rot(b, 4);  b += a; \
7422 }
7423 #define final(a,b,c) { \
7424         c ^= b; c -= rot(b,14); \
7425         a ^= c; a -= rot(c,11); \
7426         b ^= a; b -= rot(a,25); \
7427         c ^= b; c -= rot(b,16); \
7428         a ^= c; a -= rot(c,4);  \
7429         b ^= a; b -= rot(a,14); \
7430         c ^= b; c -= rot(b,24); \
7431 }
7432
7433 static guint
7434 mono_aot_type_hash (MonoType *t1)
7435 {
7436         guint hash = t1->type;
7437
7438         hash |= t1->byref << 6; /* do not collide with t1->type values */
7439         switch (t1->type) {
7440         case MONO_TYPE_VALUETYPE:
7441         case MONO_TYPE_CLASS:
7442         case MONO_TYPE_SZARRAY:
7443                 /* check if the distribution is good enough */
7444                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7445         case MONO_TYPE_PTR:
7446                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7447         case MONO_TYPE_ARRAY:
7448                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7449         case MONO_TYPE_GENERICINST:
7450                 return ((hash << 5) - hash) ^ 0;
7451         default:
7452                 return hash;
7453         }
7454 }
7455
7456 /*
7457  * mono_aot_method_hash:
7458  *
7459  *   Return a hash code for methods which only depends on metadata.
7460  */
7461 guint32
7462 mono_aot_method_hash (MonoMethod *method)
7463 {
7464         MonoMethodSignature *sig;
7465         MonoClass *klass;
7466         int i, hindex;
7467         int hashes_count;
7468         guint32 *hashes_start, *hashes;
7469         guint32 a, b, c;
7470         MonoGenericInst *ginst = NULL;
7471
7472         /* Similar to the hash in mono_method_get_imt_slot () */
7473
7474         sig = mono_method_signature (method);
7475
7476         if (method->is_inflated)
7477                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7478
7479         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7480         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7481         hashes = hashes_start;
7482
7483         /* Some wrappers are assigned to random classes */
7484         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7485                 klass = method->klass;
7486         else
7487                 klass = mono_defaults.object_class;
7488
7489         if (!method->wrapper_type) {
7490                 char *full_name = mono_type_full_name (&klass->byval_arg);
7491
7492                 hashes [0] = mono_metadata_str_hash (full_name);
7493                 hashes [1] = 0;
7494                 g_free (full_name);
7495         } else {
7496                 hashes [0] = mono_metadata_str_hash (klass->name);
7497                 hashes [1] = mono_metadata_str_hash (klass->name_space);
7498         }
7499         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7500                 /* The method name includes a stringified pointer */
7501                 hashes [2] = 0;
7502         else
7503                 hashes [2] = mono_metadata_str_hash (method->name);
7504         hashes [3] = method->wrapper_type;
7505         hashes [4] = mono_aot_type_hash (sig->ret);
7506         hindex = 5;
7507         for (i = 0; i < sig->param_count; i++) {
7508                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7509         }
7510         if (ginst) {
7511                 for (i = 0; i < ginst->type_argc; ++i)
7512                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7513         }               
7514         g_assert (hindex == hashes_count);
7515
7516         /* Setup internal state */
7517         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7518
7519         /* Handle most of the hashes */
7520         while (hashes_count > 3) {
7521                 a += hashes [0];
7522                 b += hashes [1];
7523                 c += hashes [2];
7524                 mix (a,b,c);
7525                 hashes_count -= 3;
7526                 hashes += 3;
7527         }
7528
7529         /* Handle the last 3 hashes (all the case statements fall through) */
7530         switch (hashes_count) { 
7531         case 3 : c += hashes [2];
7532         case 2 : b += hashes [1];
7533         case 1 : a += hashes [0];
7534                 final (a,b,c);
7535         case 0: /* nothing left to add */
7536                 break;
7537         }
7538         
7539         free (hashes_start);
7540         
7541         return c;
7542 }
7543 #undef rot
7544 #undef mix
7545 #undef final
7546
7547 /*
7548  * mono_aot_get_array_helper_from_wrapper;
7549  *
7550  * Get the helper method in Array called by an array wrapper method.
7551  */
7552 MonoMethod*
7553 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7554 {
7555         MonoMethod *m;
7556         const char *prefix;
7557         MonoGenericContext ctx;
7558         MonoType *args [16];
7559         char *mname, *iname, *s, *s2, *helper_name = NULL;
7560
7561         prefix = "System.Collections.Generic";
7562         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7563         s2 = strstr (s, "`1.");
7564         g_assert (s2);
7565         s2 [0] = '\0';
7566         iname = s;
7567         mname = s2 + 3;
7568
7569         //printf ("X: %s %s\n", iname, mname);
7570
7571         if (!strcmp (iname, "IList"))
7572                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7573         else
7574                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7575         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7576         g_assert (m);
7577         g_free (helper_name);
7578         g_free (s);
7579
7580         if (m->is_generic) {
7581                 memset (&ctx, 0, sizeof (ctx));
7582                 args [0] = &method->klass->element_class->byval_arg;
7583                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7584                 m = mono_class_inflate_generic_method (m, &ctx);
7585         }
7586
7587         return m;
7588 }
7589
7590 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7591
7592 typedef struct HashEntry {
7593     guint32 key, value, index;
7594         struct HashEntry *next;
7595 } HashEntry;
7596
7597 /*
7598  * emit_extra_methods:
7599  *
7600  * Emit methods which are not in the METHOD table, like wrappers.
7601  */
7602 static void
7603 emit_extra_methods (MonoAotCompile *acfg)
7604 {
7605         int i, table_size, buf_size;
7606         char symbol [256];
7607         guint8 *p, *buf;
7608         guint32 *info_offsets;
7609         guint32 hash;
7610         GPtrArray *table;
7611         HashEntry *entry, *new_entry;
7612         int nmethods, max_chain_length;
7613         int *chain_lengths;
7614
7615         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7616
7617         /* Emit method info */
7618         nmethods = 0;
7619         for (i = 0; i < acfg->extra_methods->len; ++i) {
7620                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7621                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7622
7623                 if (!cfg)
7624                         continue;
7625
7626                 buf_size = 10240;
7627                 p = buf = g_malloc (buf_size);
7628
7629                 nmethods ++;
7630
7631                 method = cfg->method_to_register;
7632
7633                 encode_method_ref (acfg, method, p, &p);
7634
7635                 g_assert ((p - buf) < buf_size);
7636
7637                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7638                 g_free (buf);
7639         }
7640
7641         /*
7642          * Construct a chained hash table for mapping indexes in extra_method_info to
7643          * method indexes.
7644          */
7645         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7646         table = g_ptr_array_sized_new (table_size);
7647         for (i = 0; i < table_size; ++i)
7648                 g_ptr_array_add (table, NULL);
7649         chain_lengths = g_new0 (int, table_size);
7650         max_chain_length = 0;
7651         for (i = 0; i < acfg->extra_methods->len; ++i) {
7652                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7653                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7654                 guint32 key, value;
7655
7656                 if (!cfg)
7657                         continue;
7658
7659                 key = info_offsets [i];
7660                 value = get_method_index (acfg, method);
7661
7662                 hash = mono_aot_method_hash (method) % table_size;
7663                 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7664
7665                 chain_lengths [hash] ++;
7666                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7667
7668                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7669                 new_entry->key = key;
7670                 new_entry->value = value;
7671
7672                 entry = g_ptr_array_index (table, hash);
7673                 if (entry == NULL) {
7674                         new_entry->index = hash;
7675                         g_ptr_array_index (table, hash) = new_entry;
7676                 } else {
7677                         while (entry->next)
7678                                 entry = entry->next;
7679                         
7680                         entry->next = new_entry;
7681                         new_entry->index = table->len;
7682                         g_ptr_array_add (table, new_entry);
7683                 }
7684         }
7685
7686         //printf ("MAX: %d\n", max_chain_length);
7687
7688         /* Emit the table */
7689         sprintf (symbol, "extra_method_table");
7690         emit_section_change (acfg, RODATA_SECT, 0);
7691         emit_alignment (acfg, 8);
7692         emit_label (acfg, symbol);
7693
7694         emit_int32 (acfg, table_size);
7695         for (i = 0; i < table->len; ++i) {
7696                 HashEntry *entry = g_ptr_array_index (table, i);
7697
7698                 if (entry == NULL) {
7699                         emit_int32 (acfg, 0);
7700                         emit_int32 (acfg, 0);
7701                         emit_int32 (acfg, 0);
7702                 } else {
7703                         //g_assert (entry->key > 0);
7704                         emit_int32 (acfg, entry->key);
7705                         emit_int32 (acfg, entry->value);
7706                         if (entry->next)
7707                                 emit_int32 (acfg, entry->next->index);
7708                         else
7709                                 emit_int32 (acfg, 0);
7710                 }
7711         }
7712
7713         /* 
7714          * Emit a table reverse mapping method indexes to their index in extra_method_info.
7715          * This is used by mono_aot_find_jit_info ().
7716          */
7717         sprintf (symbol, "extra_method_info_offsets");
7718         emit_section_change (acfg, RODATA_SECT, 0);
7719         emit_alignment (acfg, 8);
7720         emit_label (acfg, symbol);
7721
7722         emit_int32 (acfg, acfg->extra_methods->len);
7723         for (i = 0; i < acfg->extra_methods->len; ++i) {
7724                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7725
7726                 emit_int32 (acfg, get_method_index (acfg, method));
7727                 emit_int32 (acfg, info_offsets [i]);
7728         }
7729 }       
7730
7731 static void
7732 emit_exception_info (MonoAotCompile *acfg)
7733 {
7734         int i;
7735         char symbol [256];
7736         gint32 *offsets;
7737
7738         offsets = g_new0 (gint32, acfg->nmethods);
7739         for (i = 0; i < acfg->nmethods; ++i) {
7740                 if (acfg->cfgs [i]) {
7741                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
7742                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
7743                 } else {
7744                         offsets [i] = 0;
7745                 }
7746         }
7747
7748         sprintf (symbol, "ex_info_offsets");
7749         emit_section_change (acfg, RODATA_SECT, 1);
7750         emit_alignment (acfg, 8);
7751         emit_label (acfg, symbol);
7752
7753         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7754         g_free (offsets);
7755 }
7756
7757 static void
7758 emit_unwind_info (MonoAotCompile *acfg)
7759 {
7760         int i;
7761         char symbol [128];
7762
7763         /* 
7764          * The unwind info contains a lot of duplicates so we emit each unique
7765          * entry once, and only store the offset from the start of the table in the
7766          * exception info.
7767          */
7768
7769         sprintf (symbol, "unwind_info");
7770         emit_section_change (acfg, RODATA_SECT, 1);
7771         emit_alignment (acfg, 8);
7772         emit_label (acfg, symbol);
7773
7774         for (i = 0; i < acfg->unwind_ops->len; ++i) {
7775                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7776                 guint8 *unwind_info;
7777                 guint32 unwind_info_len;
7778                 guint8 buf [16];
7779                 guint8 *p;
7780
7781                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7782
7783                 p = buf;
7784                 encode_value (unwind_info_len, p, &p);
7785                 emit_bytes (acfg, buf, p - buf);
7786                 emit_bytes (acfg, unwind_info, unwind_info_len);
7787
7788                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7789         }
7790 }
7791
7792 static void
7793 emit_class_info (MonoAotCompile *acfg)
7794 {
7795         int i;
7796         char symbol [256];
7797         gint32 *offsets;
7798
7799         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7800         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7801                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7802
7803         sprintf (symbol, "class_info_offsets");
7804         emit_section_change (acfg, RODATA_SECT, 1);
7805         emit_alignment (acfg, 8);
7806         emit_label (acfg, symbol);
7807
7808         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7809         g_free (offsets);
7810 }
7811
7812 typedef struct ClassNameTableEntry {
7813         guint32 token, index;
7814         struct ClassNameTableEntry *next;
7815 } ClassNameTableEntry;
7816
7817 static void
7818 emit_class_name_table (MonoAotCompile *acfg)
7819 {
7820         int i, table_size;
7821         guint32 token, hash;
7822         MonoClass *klass;
7823         GPtrArray *table;
7824         char *full_name;
7825         char symbol [256];
7826         ClassNameTableEntry *entry, *new_entry;
7827
7828         /*
7829          * Construct a chained hash table for mapping class names to typedef tokens.
7830          */
7831         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7832         table = g_ptr_array_sized_new (table_size);
7833         for (i = 0; i < table_size; ++i)
7834                 g_ptr_array_add (table, NULL);
7835         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7836                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7837                 klass = mono_class_get (acfg->image, token);
7838                 if (!klass) {
7839                         mono_loader_clear_error ();
7840                         continue;
7841                 }
7842                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7843                 hash = mono_metadata_str_hash (full_name) % table_size;
7844                 g_free (full_name);
7845
7846                 /* FIXME: Allocate from the mempool */
7847                 new_entry = g_new0 (ClassNameTableEntry, 1);
7848                 new_entry->token = token;
7849
7850                 entry = g_ptr_array_index (table, hash);
7851                 if (entry == NULL) {
7852                         new_entry->index = hash;
7853                         g_ptr_array_index (table, hash) = new_entry;
7854                 } else {
7855                         while (entry->next)
7856                                 entry = entry->next;
7857                         
7858                         entry->next = new_entry;
7859                         new_entry->index = table->len;
7860                         g_ptr_array_add (table, new_entry);
7861                 }
7862         }
7863
7864         /* Emit the table */
7865         sprintf (symbol, "class_name_table");
7866         emit_section_change (acfg, RODATA_SECT, 0);
7867         emit_alignment (acfg, 8);
7868         emit_label (acfg, symbol);
7869
7870         /* FIXME: Optimize memory usage */
7871         g_assert (table_size < 65000);
7872         emit_int16 (acfg, table_size);
7873         g_assert (table->len < 65000);
7874         for (i = 0; i < table->len; ++i) {
7875                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7876
7877                 if (entry == NULL) {
7878                         emit_int16 (acfg, 0);
7879                         emit_int16 (acfg, 0);
7880                 } else {
7881                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
7882                         if (entry->next)
7883                                 emit_int16 (acfg, entry->next->index);
7884                         else
7885                                 emit_int16 (acfg, 0);
7886                 }
7887         }
7888 }
7889
7890 static void
7891 emit_image_table (MonoAotCompile *acfg)
7892 {
7893         int i;
7894         char symbol [256];
7895
7896         /*
7897          * The image table is small but referenced in a lot of places.
7898          * So we emit it at once, and reference its elements by an index.
7899          */
7900
7901         sprintf (symbol, "image_table");
7902         emit_section_change (acfg, RODATA_SECT, 1);
7903         emit_alignment (acfg, 8);
7904         emit_label (acfg, symbol);
7905
7906         emit_int32 (acfg, acfg->image_table->len);
7907         for (i = 0; i < acfg->image_table->len; i++) {
7908                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7909                 MonoAssemblyName *aname = &image->assembly->aname;
7910
7911                 /* FIXME: Support multi-module assemblies */
7912                 g_assert (image->assembly->image == image);
7913
7914                 emit_string (acfg, image->assembly_name);
7915                 emit_string (acfg, image->guid);
7916                 emit_string (acfg, aname->culture ? aname->culture : "");
7917                 emit_string (acfg, (const char*)aname->public_key_token);
7918
7919                 emit_alignment (acfg, 8);
7920                 emit_int32 (acfg, aname->flags);
7921                 emit_int32 (acfg, aname->major);
7922                 emit_int32 (acfg, aname->minor);
7923                 emit_int32 (acfg, aname->build);
7924                 emit_int32 (acfg, aname->revision);
7925         }
7926 }
7927
7928 static void
7929 emit_got_info (MonoAotCompile *acfg)
7930 {
7931         char symbol [256];
7932         int i, first_plt_got_patch, buf_size;
7933         guint8 *p, *buf;
7934         guint32 *got_info_offsets;
7935
7936         /* Add the patches needed by the PLT to the GOT */
7937         acfg->plt_got_offset_base = acfg->got_offset;
7938         first_plt_got_patch = acfg->got_patches->len;
7939         for (i = 1; i < acfg->plt_offset; ++i) {
7940                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7941
7942                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7943
7944                 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7945         }
7946
7947         acfg->got_offset += acfg->plt_offset;
7948
7949         /**
7950          * FIXME: 
7951          * - optimize offsets table.
7952          * - reduce number of exported symbols.
7953          * - emit info for a klass only once.
7954          * - determine when a method uses a GOT slot which is guaranteed to be already 
7955          *   initialized.
7956          * - clean up and document the code.
7957          * - use String.Empty in class libs.
7958          */
7959
7960         /* Encode info required to decode shared GOT entries */
7961         buf_size = acfg->got_patches->len * 128;
7962         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7963         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7964         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7965         /* Unused */
7966         if (acfg->plt_offset)
7967                 acfg->plt_got_info_offsets [0] = 0;
7968         for (i = 0; i < acfg->got_patches->len; ++i) {
7969                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7970                 guint8 *p2;
7971
7972                 p = buf;
7973
7974                 encode_value (ji->type, p, &p);
7975                 p2 = p;
7976                 encode_patch (acfg, ji, p, &p);
7977                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7978                 g_assert (p - buf <= buf_size);
7979                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7980
7981                 if (i >= first_plt_got_patch)
7982                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7983                 acfg->stats.got_info_size += p - buf;
7984         }
7985
7986         /* Emit got_info_offsets table */
7987         sprintf (symbol, "got_info_offsets");
7988         emit_section_change (acfg, RODATA_SECT, 1);
7989         emit_alignment (acfg, 8);
7990         emit_label (acfg, symbol);
7991
7992         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7993         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7994 }
7995
7996 static void
7997 emit_got (MonoAotCompile *acfg)
7998 {
7999         char symbol [256];
8000
8001         if (!acfg->llvm) {
8002                 /* Don't make GOT global so accesses to it don't need relocations */
8003                 sprintf (symbol, "%s", acfg->got_symbol);
8004                 emit_section_change (acfg, ".bss", 0);
8005                 emit_alignment (acfg, 8);
8006                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8007                 emit_label (acfg, symbol);
8008                 if (acfg->got_offset > 0)
8009                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8010
8011                 sprintf (symbol, "got_end");
8012                 emit_label (acfg, symbol);
8013         }
8014 }
8015
8016 typedef struct GlobalsTableEntry {
8017         guint32 value, index;
8018         struct GlobalsTableEntry *next;
8019 } GlobalsTableEntry;
8020
8021 static void
8022 emit_globals (MonoAotCompile *acfg)
8023 {
8024         int i, table_size;
8025         guint32 hash;
8026         GPtrArray *table;
8027         char symbol [256];
8028         GlobalsTableEntry *entry, *new_entry;
8029
8030         if (!acfg->aot_opts.static_link)
8031                 return;
8032
8033         /* 
8034          * When static linking, we emit a table containing our globals.
8035          */
8036
8037         /*
8038          * Construct a chained hash table for mapping global names to their index in
8039          * the globals table.
8040          */
8041         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8042         table = g_ptr_array_sized_new (table_size);
8043         for (i = 0; i < table_size; ++i)
8044                 g_ptr_array_add (table, NULL);
8045         for (i = 0; i < acfg->globals->len; ++i) {
8046                 char *name = g_ptr_array_index (acfg->globals, i);
8047
8048                 hash = mono_metadata_str_hash (name) % table_size;
8049
8050                 /* FIXME: Allocate from the mempool */
8051                 new_entry = g_new0 (GlobalsTableEntry, 1);
8052                 new_entry->value = i;
8053
8054                 entry = g_ptr_array_index (table, hash);
8055                 if (entry == NULL) {
8056                         new_entry->index = hash;
8057                         g_ptr_array_index (table, hash) = new_entry;
8058                 } else {
8059                         while (entry->next)
8060                                 entry = entry->next;
8061                         
8062                         entry->next = new_entry;
8063                         new_entry->index = table->len;
8064                         g_ptr_array_add (table, new_entry);
8065                 }
8066         }
8067
8068         /* Emit the table */
8069         sprintf (symbol, ".Lglobals_hash");
8070         emit_section_change (acfg, RODATA_SECT, 0);
8071         emit_alignment (acfg, 8);
8072         emit_label (acfg, symbol);
8073
8074         /* FIXME: Optimize memory usage */
8075         g_assert (table_size < 65000);
8076         emit_int16 (acfg, table_size);
8077         for (i = 0; i < table->len; ++i) {
8078                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8079
8080                 if (entry == NULL) {
8081                         emit_int16 (acfg, 0);
8082                         emit_int16 (acfg, 0);
8083                 } else {
8084                         emit_int16 (acfg, entry->value + 1);
8085                         if (entry->next)
8086                                 emit_int16 (acfg, entry->next->index);
8087                         else
8088                                 emit_int16 (acfg, 0);
8089                 }
8090         }
8091
8092         /* Emit the names */
8093         for (i = 0; i < acfg->globals->len; ++i) {
8094                 char *name = g_ptr_array_index (acfg->globals, i);
8095
8096                 sprintf (symbol, "name_%d", i);
8097                 emit_section_change (acfg, RODATA_SECT, 1);
8098 #ifdef TARGET_MACH
8099                 emit_alignment (acfg, 4);
8100 #endif
8101                 emit_label (acfg, symbol);
8102                 emit_string (acfg, name);
8103         }
8104
8105         /* Emit the globals table */
8106         sprintf (symbol, "globals");
8107         emit_section_change (acfg, ".data", 0);
8108         /* This is not a global, since it is accessed by the init function */
8109         emit_alignment (acfg, 8);
8110         emit_label (acfg, symbol);
8111
8112         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8113         emit_pointer (acfg, symbol);
8114
8115         for (i = 0; i < acfg->globals->len; ++i) {
8116                 char *name = g_ptr_array_index (acfg->globals, i);
8117
8118                 sprintf (symbol, "name_%d", i);
8119                 emit_pointer (acfg, symbol);
8120
8121                 sprintf (symbol, "%s", name);
8122                 emit_pointer (acfg, symbol);
8123         }
8124         /* Null terminate the table */
8125         emit_int32 (acfg, 0);
8126         emit_int32 (acfg, 0);
8127 }
8128
8129 static void
8130 emit_autoreg (MonoAotCompile *acfg)
8131 {
8132         char *symbol;
8133
8134         /*
8135          * Emit a function into the .ctor section which will be called by the ELF
8136          * loader to register this module with the runtime.
8137          */
8138         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8139                 return;
8140
8141         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8142
8143         arch_emit_autoreg (acfg, symbol);
8144
8145         g_free (symbol);
8146 }       
8147
8148 static void
8149 emit_mem_end (MonoAotCompile *acfg)
8150 {
8151         char symbol [128];
8152
8153         sprintf (symbol, "mem_end");
8154         emit_section_change (acfg, ".text", 1);
8155         emit_alignment (acfg, 8);
8156         emit_label (acfg, symbol);
8157 }
8158
8159 /*
8160  * Emit a structure containing all the information not stored elsewhere.
8161  */
8162 static void
8163 emit_file_info (MonoAotCompile *acfg)
8164 {
8165         char symbol [256];
8166         int i;
8167         int gc_name_offset;
8168         const char *gc_name;
8169         char *build_info;
8170
8171         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8172
8173         if (acfg->aot_opts.bind_to_runtime_version) {
8174                 build_info = mono_get_runtime_build_info ();
8175                 emit_string_symbol (acfg, "runtime_version", build_info);
8176                 g_free (build_info);
8177         } else {
8178                 emit_string_symbol (acfg, "runtime_version", "");
8179         }
8180
8181         /* Emit a string holding the assembly name */
8182         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8183
8184         /*
8185          * The managed allocators are GC specific, so can't use an AOT image created by one GC
8186          * in another.
8187          */
8188         gc_name = mono_gc_get_gc_name ();
8189         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8190
8191         sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8192         emit_section_change (acfg, ".data", 0);
8193         emit_alignment (acfg, 8);
8194         emit_label (acfg, symbol);
8195         if (!acfg->aot_opts.static_link)
8196                 emit_global (acfg, symbol, FALSE);
8197
8198         /* The data emitted here must match MonoAotFileInfo. */
8199
8200         emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8201         emit_int32 (acfg, 0);
8202
8203         /* 
8204          * We emit pointers to our data structures instead of emitting global symbols which
8205          * point to them, to reduce the number of globals, and because using globals leads to
8206          * various problems (i.e. arm/thumb).
8207          */
8208         emit_pointer (acfg, acfg->got_symbol);
8209         emit_pointer (acfg, acfg->methods_symbol);
8210         if (acfg->llvm) {
8211                 /*
8212                  * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8213                  */
8214                 emit_pointer (acfg, "mono_eh_frame");
8215         } else {
8216                 emit_pointer (acfg, NULL);
8217         }
8218         emit_pointer (acfg, "blob");
8219         emit_pointer (acfg, "class_name_table");
8220         emit_pointer (acfg, "class_info_offsets");
8221         emit_pointer (acfg, "method_info_offsets");
8222         emit_pointer (acfg, "ex_info_offsets");
8223         emit_pointer (acfg, "code_offsets");
8224         if (acfg->direct_method_addresses)
8225                 emit_pointer (acfg, "method_addresses");
8226         else
8227                 emit_pointer (acfg, NULL);
8228         emit_pointer (acfg, "extra_method_info_offsets");
8229         emit_pointer (acfg, "extra_method_table");
8230         emit_pointer (acfg, "got_info_offsets");
8231         emit_pointer (acfg, "methods_end");
8232         emit_pointer (acfg, "unwind_info");
8233         emit_pointer (acfg, "mem_end");
8234         emit_pointer (acfg, "image_table");
8235         emit_pointer (acfg, "plt");
8236         emit_pointer (acfg, "plt_end");
8237         emit_pointer (acfg, "assembly_guid");
8238         emit_pointer (acfg, "runtime_version");
8239         if (acfg->num_trampoline_got_entries) {
8240                 emit_pointer (acfg, "specific_trampolines");
8241                 emit_pointer (acfg, "static_rgctx_trampolines");
8242                 emit_pointer (acfg, "imt_thunks");
8243                 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8244         } else {
8245                 emit_pointer (acfg, NULL);
8246                 emit_pointer (acfg, NULL);
8247                 emit_pointer (acfg, NULL);
8248                 emit_pointer (acfg, NULL);
8249         }
8250         if (acfg->thumb_mixed) {
8251                 emit_pointer (acfg, "thumb_end");
8252         } else {
8253                 emit_pointer (acfg, NULL);
8254         }
8255         if (acfg->aot_opts.static_link) {
8256                 emit_pointer (acfg, "globals");
8257         } else {
8258                 emit_pointer (acfg, NULL);
8259         }
8260         emit_pointer (acfg, "assembly_name");
8261         emit_pointer (acfg, "unbox_trampolines");
8262         emit_pointer (acfg, "unbox_trampolines_end");
8263
8264         emit_int32 (acfg, acfg->plt_got_offset_base);
8265         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8266         emit_int32 (acfg, acfg->plt_offset);
8267         emit_int32 (acfg, acfg->nmethods);
8268         emit_int32 (acfg, acfg->flags);
8269         emit_int32 (acfg, acfg->opts);
8270         emit_int32 (acfg, acfg->simd_opts);
8271         emit_int32 (acfg, gc_name_offset);
8272
8273         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8274                 emit_int32 (acfg, acfg->num_trampolines [i]);
8275         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8276                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8277         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8278                 emit_int32 (acfg, acfg->trampoline_size [i]);
8279         emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8280
8281 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8282         {
8283                 MonoType t;
8284                 int align = 0;
8285
8286                 memset (&t, 0, sizeof (MonoType));
8287                 t.type = MONO_TYPE_R8;
8288                 mono_type_size (&t, &align);
8289                 emit_int32 (acfg, align);
8290
8291                 memset (&t, 0, sizeof (MonoType));
8292                 t.type = MONO_TYPE_I8;
8293                 mono_type_size (&t, &align);
8294
8295                 emit_int32 (acfg, align);
8296         }
8297 #else
8298         emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8299         emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8300 #endif
8301         emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8302         emit_int32 (acfg, acfg->tramp_page_size);
8303         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8304                 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8305
8306         if (acfg->aot_opts.static_link) {
8307                 char *p;
8308
8309                 /* 
8310                  * Emit a global symbol which can be passed by an embedding app to
8311                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
8312                  * structure.
8313                  */
8314                 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8315
8316                 /* Get rid of characters which cannot occur in symbols */
8317                 p = symbol;
8318                 for (p = symbol; *p; ++p) {
8319                         if (!(isalnum (*p) || *p == '_'))
8320                                 *p = '_';
8321                 }
8322                 acfg->static_linking_symbol = g_strdup (symbol);
8323                 emit_global_inner (acfg, symbol, FALSE);
8324                 emit_alignment (acfg, sizeof (gpointer));
8325                 emit_label (acfg, symbol);
8326                 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8327         }
8328 }
8329
8330 static void
8331 emit_blob (MonoAotCompile *acfg)
8332 {
8333         char symbol [128];
8334
8335         sprintf (symbol, "blob");
8336         emit_section_change (acfg, RODATA_SECT, 1);
8337         emit_alignment (acfg, 8);
8338         emit_label (acfg, symbol);
8339
8340         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8341 }
8342
8343 static void
8344 emit_objc_selectors (MonoAotCompile *acfg)
8345 {
8346         int i;
8347
8348         if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8349                 return;
8350
8351         /*
8352          * From
8353          * cat > foo.m << EOF
8354          * void *ret ()
8355          * {
8356          * return @selector(print:);
8357          * }
8358          * EOF
8359          */
8360
8361         img_writer_emit_unset_mode (acfg->w);
8362         g_assert (acfg->fp);
8363         fprintf (acfg->fp, ".section    __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8364         fprintf (acfg->fp, ".align      3\n");
8365         for (i = 0; i < acfg->objc_selectors->len; ++i) {
8366                 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8367                 fprintf (acfg->fp, ".long       L_OBJC_METH_VAR_NAME_%d\n", i);
8368         }
8369         fprintf (acfg->fp, ".section    __TEXT,__cstring,cstring_literals\n");
8370         for (i = 0; i < acfg->objc_selectors->len; ++i) {
8371                 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8372                 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8373         }
8374
8375         fprintf (acfg->fp, ".section    __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8376         fprintf (acfg->fp, ".align      3\n");
8377         fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8378         fprintf (acfg->fp, ".long       0\n");
8379         fprintf (acfg->fp, ".long       16\n");
8380 }
8381
8382 static void
8383 emit_dwarf_info (MonoAotCompile *acfg)
8384 {
8385 #ifdef EMIT_DWARF_INFO
8386         int i;
8387         char symbol2 [128];
8388
8389         /* DIEs for methods */
8390         for (i = 0; i < acfg->nmethods; ++i) {
8391                 MonoCompile *cfg = acfg->cfgs [i];
8392
8393                 if (!cfg)
8394                         continue;
8395
8396                 // FIXME: LLVM doesn't define .Lme_...
8397                 if (cfg->compile_llvm)
8398                         continue;
8399
8400                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8401
8402                 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
8403         }
8404 #endif
8405 }
8406
8407 static void
8408 collect_methods (MonoAotCompile *acfg)
8409 {
8410         int mindex, i;
8411         MonoImage *image = acfg->image;
8412
8413         /* Collect methods */
8414         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8415                 MonoMethod *method;
8416                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8417
8418                 method = mono_get_method (acfg->image, token, NULL);
8419
8420                 if (!method) {
8421                         aot_printf (acfg, "Failed to load method 0x%x from '%s'.\n", token, image->name);
8422                         aot_printf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8423                         exit (1);
8424                 }
8425                         
8426                 /* Load all methods eagerly to skip the slower lazy loading code */
8427                 mono_class_setup_methods (method->klass);
8428
8429                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8430                         /* Compile the wrapper instead */
8431                         /* We do this here instead of add_wrappers () because it is easy to do it here */
8432                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8433                         method = wrapper;
8434                 }
8435
8436                 /* FIXME: Some mscorlib methods don't have debug info */
8437                 /*
8438                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8439                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8440                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8441                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8442                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8443                                 if (!mono_debug_lookup_method (method)) {
8444                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8445                                         exit (1);
8446                                 }
8447                         }
8448                 }
8449                 */
8450
8451                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8452                 add_method_with_index (acfg, method, i, FALSE);
8453                 acfg->method_index ++;
8454         }
8455
8456         /* gsharedvt methods */
8457         for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8458                 MonoMethod *method;
8459                 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8460
8461                 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8462                         continue;
8463
8464                 method = mono_get_method (acfg->image, token, NULL);
8465                 if (!method)
8466                         continue;
8467                 /*
8468                 if (strcmp (method->name, "gshared2"))
8469                         continue;
8470                 */
8471                 /*
8472                 if (!strstr (method->klass->image->name, "mini"))
8473                         continue;
8474                 */
8475                 if (method->is_generic || method->klass->generic_container) {
8476                         MonoMethod *gshared;
8477
8478                         gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8479                         add_extra_method (acfg, gshared);
8480                 }
8481         }
8482
8483         add_generic_instances (acfg);
8484
8485         if (acfg->aot_opts.full_aot)
8486                 add_wrappers (acfg);
8487 }
8488
8489 static void
8490 compile_methods (MonoAotCompile *acfg)
8491 {
8492         int i, methods_len;
8493
8494         if (acfg->aot_opts.nthreads > 0) {
8495                 GPtrArray *frag;
8496                 int len, j;
8497                 GPtrArray *threads;
8498                 HANDLE handle;
8499                 gpointer *user_data;
8500                 MonoMethod **methods;
8501
8502                 methods_len = acfg->methods->len;
8503
8504                 len = acfg->methods->len / acfg->aot_opts.nthreads;
8505                 g_assert (len > 0);
8506                 /* 
8507                  * Partition the list of methods into fragments, and hand it to threads to
8508                  * process.
8509                  */
8510                 threads = g_ptr_array_new ();
8511                 /* Make a copy since acfg->methods is modified by compile_method () */
8512                 methods = g_new0 (MonoMethod*, methods_len);
8513                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8514                 for (i = 0; i < methods_len; ++i)
8515                         methods [i] = g_ptr_array_index (acfg->methods, i);
8516                 i = 0;
8517                 while (i < methods_len) {
8518                         frag = g_ptr_array_new ();
8519                         for (j = 0; j < len; ++j) {
8520                                 if (i < methods_len) {
8521                                         g_ptr_array_add (frag, methods [i]);
8522                                         i ++;
8523                                 }
8524                         }
8525
8526                         user_data = g_new0 (gpointer, 3);
8527                         user_data [0] = mono_domain_get ();
8528                         user_data [1] = acfg;
8529                         user_data [2] = frag;
8530                         
8531                         handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8532                         g_ptr_array_add (threads, handle);
8533                 }
8534                 g_free (methods);
8535
8536                 for (i = 0; i < threads->len; ++i) {
8537                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8538                 }
8539         } else {
8540                 methods_len = 0;
8541         }
8542
8543         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8544         for (i = methods_len; i < acfg->methods->len; ++i) {
8545                 /* This can new methods to acfg->methods */
8546                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8547         }
8548 }
8549
8550 static int
8551 compile_asm (MonoAotCompile *acfg)
8552 {
8553         char *command, *objfile;
8554         char *outfile_name, *tmp_outfile_name;
8555         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8556
8557 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8558 #define AS_OPTIONS "--64"
8559 #elif defined(TARGET_POWERPC64)
8560 #define AS_OPTIONS "-a64 -mppc64"
8561 #define LD_OPTIONS "-m elf64ppc"
8562 #elif defined(sparc) && SIZEOF_VOID_P == 8
8563 #define AS_OPTIONS "-xarch=v9"
8564 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8565 #define AS_OPTIONS "-arch i386"
8566 #else
8567 #define AS_OPTIONS ""
8568 #endif
8569
8570 #ifdef __native_client_codegen__
8571 #if defined(TARGET_AMD64)
8572 #define AS_NAME "nacl64-as"
8573 #else
8574 #define AS_NAME "nacl-as"
8575 #endif
8576 #elif defined(TARGET_OSX)
8577 #define AS_NAME "clang -c -x assembler"
8578 #else
8579 #define AS_NAME "as"
8580 #endif
8581
8582 #ifndef LD_OPTIONS
8583 #define LD_OPTIONS ""
8584 #endif
8585
8586 #if defined(sparc)
8587 #define LD_NAME "ld -shared -G"
8588 #elif defined(__ppc__) && defined(TARGET_MACH)
8589 #define LD_NAME "gcc -dynamiclib"
8590 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8591 #define LD_NAME "clang --shared"
8592 #elif defined(HOST_WIN32)
8593 #define LD_NAME "gcc -shared --dll"
8594 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8595 #define LD_NAME "clang -m32 -dynamiclib"
8596 #endif
8597
8598         if (acfg->aot_opts.asm_only) {
8599                 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8600                 if (acfg->aot_opts.static_link)
8601                         aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8602                 return 0;
8603         }
8604
8605         if (acfg->aot_opts.static_link) {
8606                 if (acfg->aot_opts.outfile)
8607                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8608                 else
8609                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
8610         } else {
8611                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8612         }
8613         command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
8614         aot_printf (acfg, "Executing the native assembler: %s\n", command);
8615         if (system (command) != 0) {
8616                 g_free (command);
8617                 g_free (objfile);
8618                 return 1;
8619         }
8620
8621         g_free (command);
8622
8623         if (acfg->aot_opts.static_link) {
8624                 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8625                 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8626                 g_free (objfile);
8627                 return 0;
8628         }
8629
8630         if (acfg->aot_opts.outfile)
8631                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8632         else
8633                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8634
8635         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8636
8637 #ifdef LD_NAME
8638         command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8639 #else
8640         command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8641 #endif
8642         aot_printf (acfg, "Executing the native linker: %s\n", command);
8643         if (system (command) != 0) {
8644                 g_free (tmp_outfile_name);
8645                 g_free (outfile_name);
8646                 g_free (command);
8647                 g_free (objfile);
8648                 return 1;
8649         }
8650
8651         g_free (command);
8652
8653         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8654         printf ("Stripping the binary: %s\n", com);
8655         system (com);
8656         g_free (com);*/
8657
8658 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8659         /* 
8660          * gas generates 'mapping symbols' each time code and data is mixed, which 
8661          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8662          */
8663         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8664         aot_printf (acfg, "Stripping the binary: %s\n", command);
8665         if (system (command) != 0) {
8666                 g_free (tmp_outfile_name);
8667                 g_free (outfile_name);
8668                 g_free (command);
8669                 g_free (objfile);
8670                 return 1;
8671         }
8672 #endif
8673
8674         rename (tmp_outfile_name, outfile_name);
8675
8676 #if defined(TARGET_MACH)
8677         command = g_strdup_printf ("dsymutil %s", outfile_name);
8678         aot_printf (acfg, "Executing dsymutil: %s\n", command);
8679         if (system (command) != 0) {
8680                 return 1;
8681         }
8682 #endif
8683
8684         if (!acfg->aot_opts.save_temps)
8685                 unlink (objfile);
8686
8687         g_free (tmp_outfile_name);
8688         g_free (outfile_name);
8689         g_free (objfile);
8690
8691         if (acfg->aot_opts.save_temps)
8692                 aot_printf (acfg, "Retained input file.\n");
8693         else
8694                 unlink (acfg->tmpfname);
8695
8696         return 0;
8697 }
8698
8699 static MonoAotCompile*
8700 acfg_create (MonoAssembly *ass, guint32 opts)
8701 {
8702         MonoImage *image = ass->image;
8703         MonoAotCompile *acfg;
8704         int i;
8705
8706         acfg = g_new0 (MonoAotCompile, 1);
8707         acfg->methods = g_ptr_array_new ();
8708         acfg->method_indexes = g_hash_table_new (NULL, NULL);
8709         acfg->method_depth = g_hash_table_new (NULL, NULL);
8710         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8711         acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8712         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8713         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8714         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8715                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8716         acfg->got_patches = g_ptr_array_new ();
8717         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8718         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8719         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8720         acfg->image_hash = g_hash_table_new (NULL, NULL);
8721         acfg->image_table = g_ptr_array_new ();
8722         acfg->globals = g_ptr_array_new ();
8723         acfg->image = image;
8724         acfg->opts = opts;
8725         /* TODO: Write out set of SIMD instructions used, rather than just those available */
8726         acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8727         acfg->mempool = mono_mempool_new ();
8728         acfg->extra_methods = g_ptr_array_new ();
8729         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8730         acfg->unwind_ops = g_ptr_array_new ();
8731         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8732         acfg->method_order = g_ptr_array_new ();
8733         acfg->export_names = g_hash_table_new (NULL, NULL);
8734         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8735         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8736         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8737         mono_mutex_init_recursive (&acfg->mutex);
8738
8739         return acfg;
8740 }
8741
8742 static void
8743 acfg_free (MonoAotCompile *acfg)
8744 {
8745         int i;
8746
8747         img_writer_destroy (acfg->w);
8748         for (i = 0; i < acfg->nmethods; ++i)
8749                 if (acfg->cfgs [i])
8750                         g_free (acfg->cfgs [i]);
8751         g_free (acfg->cfgs);
8752         g_free (acfg->static_linking_symbol);
8753         g_free (acfg->got_symbol);
8754         g_free (acfg->plt_symbol);
8755         g_ptr_array_free (acfg->methods, TRUE);
8756         g_ptr_array_free (acfg->got_patches, TRUE);
8757         g_ptr_array_free (acfg->image_table, TRUE);
8758         g_ptr_array_free (acfg->globals, TRUE);
8759         g_ptr_array_free (acfg->unwind_ops, TRUE);
8760         g_hash_table_destroy (acfg->method_indexes);
8761         g_hash_table_destroy (acfg->method_depth);
8762         g_hash_table_destroy (acfg->plt_offset_to_entry);
8763         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8764                 if (acfg->patch_to_plt_entry [i])
8765                         g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8766         }
8767         g_free (acfg->patch_to_plt_entry);
8768         g_hash_table_destroy (acfg->patch_to_got_offset);
8769         g_hash_table_destroy (acfg->method_to_cfg);
8770         g_hash_table_destroy (acfg->token_info_hash);
8771         g_hash_table_destroy (acfg->method_to_pinvoke_import);
8772         g_hash_table_destroy (acfg->image_hash);
8773         g_hash_table_destroy (acfg->unwind_info_offsets);
8774         g_hash_table_destroy (acfg->method_label_hash);
8775         g_hash_table_destroy (acfg->export_names);
8776         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8777         g_hash_table_destroy (acfg->klass_blob_hash);
8778         g_hash_table_destroy (acfg->method_blob_hash);
8779         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8780                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8781         g_free (acfg->patch_to_got_offset_by_type);
8782         mono_mempool_destroy (acfg->mempool);
8783         g_free (acfg);
8784 }
8785
8786 int
8787 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8788 {
8789         MonoImage *image = ass->image;
8790         int i, res, all_sizes;
8791         MonoAotCompile *acfg;
8792         char *outfile_name, *tmp_outfile_name, *p;
8793         char llvm_stats_msg [256];
8794         TV_DECLARE (atv);
8795         TV_DECLARE (btv);
8796
8797 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8798         if (opts & MONO_OPT_GSHAREDVT) {
8799                 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8800                 exit (1);
8801         }
8802 #endif
8803
8804         acfg = acfg_create (ass, opts);
8805
8806         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8807         acfg->aot_opts.write_symbols = TRUE;
8808         acfg->aot_opts.ntrampolines = 1024;
8809         acfg->aot_opts.nrgctx_trampolines = 1024;
8810         acfg->aot_opts.nimt_trampolines = 128;
8811         acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8812         acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8813         acfg->aot_opts.llvm_path = g_strdup ("");
8814 #ifdef MONOTOUCH
8815         acfg->aot_opts.use_trampolines_page = TRUE;
8816 #endif
8817
8818         mono_aot_parse_options (aot_options, &acfg->aot_opts);
8819
8820         if (acfg->aot_opts.logfile) {
8821                 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
8822         }
8823
8824         if (acfg->aot_opts.static_link)
8825                 acfg->aot_opts.autoreg = TRUE;
8826
8827         //acfg->aot_opts.print_skipped_methods = TRUE;
8828
8829         aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8830
8831 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8832         if (acfg->aot_opts.full_aot) {
8833                 aot_printf (acfg, "--aot=full is not supported on this platform.\n");
8834                 return 1;
8835         }
8836 #endif
8837
8838         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8839                 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8840                 exit (1);
8841         }
8842
8843         if (acfg->aot_opts.static_link)
8844                 acfg->aot_opts.asm_writer = TRUE;
8845
8846         if (acfg->aot_opts.soft_debug) {
8847                 MonoDebugOptions *opt = mini_get_debug_options ();
8848
8849                 opt->mdb_optimizations = TRUE;
8850                 opt->gen_seq_points = TRUE;
8851
8852                 if (!mono_debug_enabled ()) {
8853                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8854                         return 1;
8855                 }
8856                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8857         }
8858
8859         if (mono_use_llvm) {
8860                 acfg->llvm = TRUE;
8861                 acfg->aot_opts.asm_writer = TRUE;
8862                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8863
8864                 if (acfg->aot_opts.soft_debug) {
8865                         fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8866                         exit (1);
8867                 }
8868         }
8869
8870         if (acfg->aot_opts.full_aot)
8871                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8872
8873         if (acfg->aot_opts.instances_logfile_path) {
8874                 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
8875                 if (!acfg->instances_logfile) {
8876                         fprintf (stderr, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
8877                         exit (1);
8878                 }
8879         }
8880
8881         load_profile_files (acfg);
8882
8883         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8884 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8885         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8886 #endif
8887         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8888 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8889         if (acfg->opts & MONO_OPT_GSHAREDVT)
8890                 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8891 #endif
8892
8893         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8894
8895         arch_init (acfg);
8896
8897         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8898         acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8899         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8900
8901         /* Get rid of characters which cannot occur in symbols */
8902         for (p = acfg->got_symbol_base; *p; ++p) {
8903                 if (!(isalnum (*p) || *p == '_'))
8904                         *p = '_';
8905         }
8906         for (p = acfg->plt_symbol; *p; ++p) {
8907                 if (!(isalnum (*p) || *p == '_'))
8908                         *p = '_';
8909         }
8910         for (p = acfg->assembly_name_sym; *p; ++p) {
8911                 if (!(isalnum (*p) || *p == '_'))
8912                         *p = '_';
8913         }
8914
8915         acfg->method_index = 1;
8916
8917         // FIXME:
8918         /*
8919         if (acfg->aot_opts.full_aot)
8920                 mono_set_partial_sharing_supported (TRUE);
8921         */
8922
8923         collect_methods (acfg);
8924
8925         acfg->cfgs_size = acfg->methods->len + 32;
8926         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8927
8928         /* PLT offset 0 is reserved for the PLT trampoline */
8929         acfg->plt_offset = 1;
8930
8931 #ifdef ENABLE_LLVM
8932         if (acfg->llvm) {
8933                 llvm_acfg = acfg;
8934                 mono_llvm_create_aot_module (acfg->got_symbol_base);
8935         }
8936 #endif
8937
8938         /* GOT offset 0 is reserved for the address of the current assembly */
8939         {
8940                 MonoJumpInfo *ji;
8941
8942                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8943                 ji->type = MONO_PATCH_INFO_IMAGE;
8944                 ji->data.image = acfg->image;
8945
8946                 get_got_offset (acfg, ji);
8947
8948                 /* Slot 1 is reserved for the mscorlib got addr */
8949                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8950                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8951                 get_got_offset (acfg, ji);
8952
8953                 /* This is very common */
8954                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8955                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8956                 get_got_offset (acfg, ji);
8957
8958                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8959                 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8960                 get_got_offset (acfg, ji);
8961         }
8962
8963         TV_GETTIME (atv);
8964
8965         compile_methods (acfg);
8966
8967         TV_GETTIME (btv);
8968
8969         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8970
8971         TV_GETTIME (atv);
8972
8973 #ifdef ENABLE_LLVM
8974         if (acfg->llvm) {
8975                 if (acfg->aot_opts.asm_only) {
8976                         if (acfg->aot_opts.outfile) {
8977                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8978                                 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8979                         } else {
8980                                 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8981                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8982                         }
8983                 } else {
8984                         acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8985                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8986                 }
8987
8988                 emit_llvm_file (acfg);
8989         }
8990 #endif
8991
8992         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8993                 if (acfg->aot_opts.outfile)
8994                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8995                 else
8996                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8997
8998                 /* 
8999                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
9000                  * it might be in another file system so the rename () won't work.
9001                  */
9002                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9003
9004                 acfg->fp = fopen (tmp_outfile_name, "w");
9005                 if (!acfg->fp) {
9006                         aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9007                         return 1;
9008                 }
9009
9010                 acfg->w = img_writer_create (acfg->fp, TRUE);
9011                 acfg->use_bin_writer = TRUE;
9012         } else {
9013                 if (acfg->llvm) {
9014                         /* Append to the .s file created by llvm */
9015                         /* FIXME: Use multiple files instead */
9016                         acfg->fp = fopen (acfg->tmpfname, "a+");
9017                 } else {
9018                         if (acfg->aot_opts.asm_only) {
9019                                 if (acfg->aot_opts.outfile)
9020                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9021                                 else
9022                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9023                                 acfg->fp = fopen (acfg->tmpfname, "w+");
9024                         } else {
9025                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9026                                 acfg->fp = fdopen (i, "w+");
9027                         }
9028                 }
9029                 if (acfg->fp == 0) {
9030                         fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9031                         return 1;
9032                 }
9033                 acfg->w = img_writer_create (acfg->fp, FALSE);
9034                 
9035                 tmp_outfile_name = NULL;
9036                 outfile_name = NULL;
9037         }
9038
9039         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9040
9041         /* Compute symbols for methods */
9042         for (i = 0; i < acfg->nmethods; ++i) {
9043                 if (acfg->cfgs [i]) {
9044                         MonoCompile *cfg = acfg->cfgs [i];
9045                         int method_index = get_method_index (acfg, cfg->orig_method);
9046
9047                         if (COMPILE_LLVM (cfg))
9048                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9049                         else if (acfg->global_symbols)
9050                                 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
9051                         else
9052                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9053                 }
9054         }
9055
9056         if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9057                 /*
9058                  * CLANG supports GAS .file/.loc directives, so emit line number information this way
9059                  * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9060                  * .byte directives.
9061                  */
9062                 //acfg->gas_line_numbers = TRUE;
9063         }
9064
9065         if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9066                 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9067                         fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
9068                         return 1;
9069                 }
9070                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9071         }
9072
9073         img_writer_emit_start (acfg->w);
9074
9075         if (acfg->dwarf)
9076                 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9077
9078         if (acfg->thumb_mixed) {
9079                 char symbol [256];
9080                 /*
9081                  * This global symbol marks the end of THUMB code, and the beginning of ARM
9082                  * code generated by our JIT.
9083                  */
9084                 sprintf (symbol, "thumb_end");
9085                 emit_section_change (acfg, ".text", 0);
9086                 emit_alignment (acfg, 8);
9087                 emit_label (acfg, symbol);
9088                 emit_zero_bytes (acfg, 16);
9089
9090                 fprintf (acfg->fp, ".arm\n");
9091         }
9092
9093         emit_code (acfg);
9094
9095         emit_info (acfg);
9096
9097         emit_extra_methods (acfg);
9098
9099         emit_trampolines (acfg);
9100
9101         emit_class_name_table (acfg);
9102
9103         emit_got_info (acfg);
9104
9105         emit_exception_info (acfg);
9106
9107         emit_unwind_info (acfg);
9108
9109         emit_class_info (acfg);
9110
9111         emit_plt (acfg);
9112
9113         emit_image_table (acfg);
9114
9115         emit_got (acfg);
9116
9117         emit_file_info (acfg);
9118
9119         emit_blob (acfg);
9120
9121         emit_objc_selectors (acfg);
9122
9123         emit_globals (acfg);
9124
9125         emit_autoreg (acfg);
9126
9127         if (acfg->dwarf) {
9128                 emit_dwarf_info (acfg);
9129                 mono_dwarf_writer_close (acfg->dwarf);
9130         }
9131
9132         emit_mem_end (acfg);
9133
9134         if (acfg->need_pt_gnu_stack) {
9135                 /* This is required so the .so doesn't have an executable stack */
9136                 /* The bin writer already emits this */
9137                 if (!acfg->use_bin_writer)
9138                         fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
9139         }
9140
9141         TV_GETTIME (btv);
9142
9143         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9144
9145         if (acfg->llvm)
9146                 g_assert (acfg->got_offset <= acfg->final_got_size);
9147
9148         if (acfg->llvm)
9149                 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9150         else
9151                 strcpy (llvm_stats_msg, "");
9152
9153         all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
9154
9155         aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
9156                         acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9157                         acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9158                         acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9159                         acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9160                         acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9161                         acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9162                         acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9163                         acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9164                         (int)(acfg->got_offset * sizeof (gpointer)));
9165         aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n", 
9166                         acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9167                         llvm_stats_msg,
9168                         acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9169                         acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9170         if (acfg->stats.genericcount)
9171                 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9172         if (acfg->stats.abscount)
9173                 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9174         if (acfg->stats.lmfcount)
9175                 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9176         if (acfg->stats.ocount)
9177                 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9178
9179         TV_GETTIME (atv);
9180         res = img_writer_emit_writeout (acfg->w);
9181         if (res != 0) {
9182                 acfg_free (acfg);
9183                 return res;
9184         }
9185         if (acfg->use_bin_writer) {
9186                 int err = rename (tmp_outfile_name, outfile_name);
9187
9188                 if (err) {
9189                         aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9190                         return 1;
9191                 }
9192         } else {
9193                 res = compile_asm (acfg);
9194                 if (res != 0) {
9195                         acfg_free (acfg);
9196                         return res;
9197                 }
9198         }
9199         TV_GETTIME (btv);
9200         acfg->stats.link_time = TV_ELAPSED (atv, btv);
9201
9202         if (acfg->aot_opts.stats) {
9203                 int i;
9204
9205                 aot_printf (acfg, "GOT slot distribution:\n");
9206                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9207                         if (acfg->stats.got_slot_types [i])
9208                                 aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9209         }
9210
9211         aot_printf (acfg, "JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
9212
9213         acfg_free (acfg);
9214         
9215         return 0;
9216 }
9217
9218 #else
9219
9220 /* AOT disabled */
9221
9222 void*
9223 mono_aot_readonly_field_override (MonoClassField *field)
9224 {
9225         return NULL;
9226 }
9227
9228 int
9229 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9230 {
9231         return 0;
9232 }
9233
9234 #endif