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