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