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