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