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