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