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