Merge pull request #4716 from Unity-Technologies/eglib-msvc-targets
[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->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6138                                 if (clause->data.catch_class) {
6139                                         guint8 *buf2, *p2;
6140                                         int len;
6141
6142                                         buf2 = (guint8 *)g_malloc (4096);
6143                                         p2 = buf2;
6144                                         encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6145                                         len = p2 - buf2;
6146                                         g_assert (len < 4096);
6147                                         encode_value (len, p, &p);
6148                                         memcpy (p, buf2, len);
6149                                         p += p2 - buf2;
6150                                         g_free (buf2);
6151                                 } else {
6152                                         encode_value (0, p, &p);
6153                                 }
6154                         }
6155
6156                         /* Emit the IL ranges too, since they might not be available at runtime */
6157                         encode_value (clause->try_offset, p, &p);
6158                         encode_value (clause->try_len, p, &p);
6159                         encode_value (clause->handler_offset, p, &p);
6160                         encode_value (clause->handler_len, p, &p);
6161
6162                         /* Emit a list of nesting clauses */
6163                         for (i = 0; i < header->num_clauses; ++i) {
6164                                 gint32 cindex1 = k;
6165                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6166                                 gint32 cindex2 = i;
6167                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6168
6169                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6170                                         encode_value (i, p, &p);
6171                         }
6172                         encode_value (-1, p, &p);
6173                 }
6174         } else {
6175                 if (jinfo->num_clauses)
6176                         encode_value (jinfo->num_clauses, p, &p);
6177
6178                 for (k = 0; k < jinfo->num_clauses; ++k) {
6179                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6180
6181                         encode_value (ei->flags, p, &p);
6182 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6183                         /* Not used for catch clauses */
6184                         if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6185                                 encode_value (ei->exvar_offset, p, &p);
6186 #else
6187                         encode_value (ei->exvar_offset, p, &p);
6188 #endif
6189
6190                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6191                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6192                         else {
6193                                 if (ei->data.catch_class) {
6194                                         guint8 *buf2, *p2;
6195                                         int len;
6196
6197                                         buf2 = (guint8 *)g_malloc (4096);
6198                                         p2 = buf2;
6199                                         encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6200                                         len = p2 - buf2;
6201                                         g_assert (len < 4096);
6202                                         encode_value (len, p, &p);
6203                                         memcpy (p, buf2, len);
6204                                         p += p2 - buf2;
6205                                         g_free (buf2);
6206                                 } else {
6207                                         encode_value (0, p, &p);
6208                                 }
6209                         }
6210
6211                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6212                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6213                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6214                 }
6215         }
6216
6217         if (jinfo->has_try_block_holes) {
6218                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6219                 for (i = 0; i < table->num_holes; ++i) {
6220                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6221                         encode_value (hole->clause, p, &p);
6222                         encode_value (hole->length, p, &p);
6223                         encode_value (hole->offset, p, &p);
6224                 }
6225         }
6226
6227         if (jinfo->has_arch_eh_info) {
6228                 MonoArchEHJitInfo *eh_info;
6229
6230                 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6231                 encode_value (eh_info->stack_size, p, &p);
6232                 encode_value (eh_info->epilog_size, p, &p);
6233         }
6234
6235         if (jinfo->has_generic_jit_info) {
6236                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6237                 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6238                 guint8 *buf2, *p2;
6239                 int len;
6240
6241                 encode_value (gi->nlocs, p, &p);
6242                 if (gi->nlocs) {
6243                         for (i = 0; i < gi->nlocs; ++i) {
6244                                 MonoDwarfLocListEntry *entry = &gi->locations [i];
6245
6246                                 encode_value (entry->is_reg ? 1 : 0, p, &p);
6247                                 encode_value (entry->reg, p, &p);
6248                                 if (!entry->is_reg)
6249                                         encode_value (entry->offset, p, &p);
6250                                 if (i == 0)
6251                                         g_assert (entry->from == 0);
6252                                 else
6253                                         encode_value (entry->from, p, &p);
6254                                 encode_value (entry->to, p, &p);
6255                         }
6256                 } else {
6257                         if (!cfg->compile_llvm) {
6258                                 encode_value (gi->has_this ? 1 : 0, p, &p);
6259                                 encode_value (gi->this_reg, p, &p);
6260                                 encode_value (gi->this_offset, p, &p);
6261                         }
6262                 }
6263
6264                 /* 
6265                  * Need to encode jinfo->method too, since it is not equal to 'method'
6266                  * when using generic sharing.
6267                  */
6268                 buf2 = (guint8 *)g_malloc (4096);
6269                 p2 = buf2;
6270                 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6271                 len = p2 - buf2;
6272                 g_assert (len < 4096);
6273                 encode_value (len, p, &p);
6274                 memcpy (p, buf2, len);
6275                 p += p2 - buf2;
6276                 g_free (buf2);
6277
6278                 if (gsctx && gsctx->is_gsharedvt) {
6279                         encode_value (1, p, &p);
6280                 } else {
6281                         encode_value (0, p, &p);
6282                 }
6283         }
6284
6285         if (seq_points_size)
6286                 p += mono_seq_point_info_write (seq_points, p);
6287
6288         g_assert (debug_info_size < buf_size);
6289
6290         encode_value (debug_info_size, p, &p);
6291         if (debug_info_size) {
6292                 memcpy (p, debug_info, debug_info_size);
6293                 p += debug_info_size;
6294                 g_free (debug_info);
6295         }
6296
6297         /* GC Map */
6298         if (cfg->gc_map) {
6299                 encode_value (cfg->gc_map_size, p, &p);
6300                 /* The GC map requires 4 bytes of alignment */
6301                 while ((gsize)p % 4)
6302                         p ++;
6303                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6304                 p += cfg->gc_map_size;
6305         }
6306
6307         acfg->stats.ex_info_size += p - buf;
6308
6309         g_assert (p - buf < buf_size);
6310
6311         /* Emit info */
6312         /* The GC Map requires 4 byte alignment */
6313         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6314         g_free (buf);
6315 }
6316
6317 static guint32
6318 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6319 {
6320         MonoError error;
6321         MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6322         guint8 *p, *buf;
6323         int i, buf_size, res;
6324         gboolean no_special_static, cant_encode;
6325         gpointer iter = NULL;
6326
6327         if (!klass) {
6328                 mono_error_cleanup (&error);
6329
6330                 buf_size = 16;
6331
6332                 p = buf = (guint8 *)g_malloc (buf_size);
6333
6334                 /* Mark as unusable */
6335                 encode_value (-1, p, &p);
6336
6337                 res = add_to_blob (acfg, buf, p - buf);
6338                 g_free (buf);
6339
6340                 return res;
6341         }
6342                 
6343         buf_size = 10240 + (klass->vtable_size * 16);
6344         p = buf = (guint8 *)g_malloc (buf_size);
6345
6346         g_assert (klass);
6347
6348         mono_class_init (klass);
6349
6350         mono_class_get_nested_types (klass, &iter);
6351         g_assert (klass->nested_classes_inited);
6352
6353         mono_class_setup_vtable (klass);
6354
6355         /* 
6356          * Emit all the information which is required for creating vtables so
6357          * the runtime does not need to create the MonoMethod structures which
6358          * take up a lot of space.
6359          */
6360
6361         no_special_static = !mono_class_has_special_static_fields (klass);
6362
6363         /* Check whenever we have enough info to encode the vtable */
6364         cant_encode = FALSE;
6365         for (i = 0; i < klass->vtable_size; ++i) {
6366                 MonoMethod *cm = klass->vtable [i];
6367
6368                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6369                         cant_encode = TRUE;
6370         }
6371
6372         mono_class_has_finalizer (klass);
6373         if (mono_class_has_failure (klass))
6374                 cant_encode = TRUE;
6375
6376         if (mono_class_is_gtd (klass) || cant_encode) {
6377                 encode_value (-1, p, &p);
6378         } else {
6379                 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6380                 encode_value (klass->vtable_size, p, &p);
6381                 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);
6382                 if (klass->has_cctor)
6383                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6384                 if (klass->has_finalize)
6385                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6386  
6387                 encode_value (klass->instance_size, p, &p);
6388                 encode_value (mono_class_data_size (klass), p, &p);
6389                 encode_value (klass->packing_size, p, &p);
6390                 encode_value (klass->min_align, p, &p);
6391
6392                 for (i = 0; i < klass->vtable_size; ++i) {
6393                         MonoMethod *cm = klass->vtable [i];
6394
6395                         if (cm)
6396                                 encode_method_ref (acfg, cm, p, &p);
6397                         else
6398                                 encode_value (0, p, &p);
6399                 }
6400         }
6401
6402         acfg->stats.class_info_size += p - buf;
6403
6404         g_assert (p - buf < buf_size);
6405         res = add_to_blob (acfg, buf, p - buf);
6406         g_free (buf);
6407
6408         return res;
6409 }
6410
6411 static char*
6412 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6413 {
6414         char *debug_sym = NULL;
6415         char *prefix;
6416
6417         if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6418                 /* Need to add a prefix to create unique symbols */
6419                 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6420         } else {
6421 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6422                 prefix = mangle_symbol_alloc ("plt_");
6423 #else
6424                 prefix = g_strdup ("plt_");
6425 #endif
6426         }
6427
6428         switch (ji->type) {
6429         case MONO_PATCH_INFO_METHOD:
6430                 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6431                 break;
6432         case MONO_PATCH_INFO_INTERNAL_METHOD:
6433                 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6434                 break;
6435         case MONO_PATCH_INFO_RGCTX_FETCH:
6436                 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6437                 break;
6438         case MONO_PATCH_INFO_ICALL_ADDR:
6439         case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6440                 char *s = get_debug_sym (ji->data.method, "", cache);
6441                 
6442                 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6443                 g_free (s);
6444                 break;
6445         }
6446         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6447                 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6448                 break;
6449         default:
6450                 break;
6451         }
6452
6453         g_free (prefix);
6454
6455         return sanitize_symbol (acfg, debug_sym);
6456 }
6457
6458 /*
6459  * Calls made from AOTed code are routed through a table of jumps similar to the
6460  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6461  * control to the AOT runtime through a trampoline.
6462  */
6463 static void
6464 emit_plt (MonoAotCompile *acfg)
6465 {
6466         int i;
6467
6468         if (acfg->aot_opts.llvm_only) {
6469                 g_assert (acfg->plt_offset == 1);
6470                 return;
6471         }
6472
6473         emit_line (acfg);
6474
6475         emit_section_change (acfg, ".text", 0);
6476         emit_alignment_code (acfg, 16);
6477         emit_info_symbol (acfg, "plt");
6478         emit_label (acfg, acfg->plt_symbol);
6479
6480         for (i = 0; i < acfg->plt_offset; ++i) {
6481                 char *debug_sym = NULL;
6482                 MonoPltEntry *plt_entry = NULL;
6483
6484                 if (i == 0)
6485                         /* 
6486                          * The first plt entry is unused.
6487                          */
6488                         continue;
6489
6490                 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6491
6492                 debug_sym = plt_entry->debug_sym;
6493
6494                 if (acfg->thumb_mixed && !plt_entry->jit_used)
6495                         /* Emit only a thumb version */
6496                         continue;
6497
6498                 /* Skip plt entries not actually called */
6499                 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6500                         continue;
6501
6502                 if (acfg->llvm && !acfg->thumb_mixed) {
6503                         emit_label (acfg, plt_entry->llvm_symbol);
6504                         if (acfg->llvm) {
6505                                 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6506 #if defined(TARGET_MACH)
6507                                 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6508 #endif
6509                         }
6510                 }
6511
6512                 if (debug_sym) {
6513                         if (acfg->need_no_dead_strip) {
6514                                 emit_unset_mode (acfg);
6515                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
6516                         }
6517                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6518                         emit_label (acfg, debug_sym);
6519                 }
6520
6521                 emit_label (acfg, plt_entry->symbol);
6522
6523                 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6524
6525                 if (debug_sym)
6526                         emit_symbol_size (acfg, debug_sym, ".");
6527         }
6528
6529         if (acfg->thumb_mixed) {
6530                 /* Make sure the ARM symbols don't alias the thumb ones */
6531                 emit_zero_bytes (acfg, 16);
6532
6533                 /* 
6534                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6535                  * code.
6536                  */
6537                 for (i = 0; i < acfg->plt_offset; ++i) {
6538                         char *debug_sym = NULL;
6539                         MonoPltEntry *plt_entry = NULL;
6540
6541                         if (i == 0)
6542                                 continue;
6543
6544                         plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6545
6546                         /* Skip plt entries not actually called by LLVM code */
6547                         if (!plt_entry->llvm_used)
6548                                 continue;
6549
6550                         if (acfg->aot_opts.write_symbols) {
6551                                 if (plt_entry->debug_sym)
6552                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6553                         }
6554
6555                         if (debug_sym) {
6556 #if defined(TARGET_MACH)
6557                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
6558                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
6559 #endif
6560                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6561                                 emit_label (acfg, debug_sym);
6562                         }
6563                         fprintf (acfg->fp, "\n.thumb_func\n");
6564
6565                         emit_label (acfg, plt_entry->llvm_symbol);
6566
6567                         if (acfg->llvm)
6568                                 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6569
6570                         arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6571
6572                         if (debug_sym) {
6573                                 emit_symbol_size (acfg, debug_sym, ".");
6574                                 g_free (debug_sym);
6575                         }
6576                 }
6577         }
6578
6579         emit_symbol_size (acfg, acfg->plt_symbol, ".");
6580
6581         emit_info_symbol (acfg, "plt_end");
6582 }
6583
6584 /*
6585  * emit_trampoline_full:
6586  *
6587  *   If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6588  * create_jit_info_for_trampoline ().
6589  */
6590 static G_GNUC_UNUSED void
6591 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6592 {
6593         char start_symbol [MAX_SYMBOL_SIZE];
6594         char end_symbol [MAX_SYMBOL_SIZE];
6595         char symbol [MAX_SYMBOL_SIZE];
6596         guint32 buf_size, info_offset;
6597         MonoJumpInfo *patch_info;
6598         guint8 *buf, *p;
6599         GPtrArray *patches;
6600         char *name;
6601         guint8 *code;
6602         guint32 code_size;
6603         MonoJumpInfo *ji;
6604         GSList *unwind_ops;
6605
6606         g_assert (info);
6607
6608         name = info->name;
6609         code = info->code;
6610         code_size = info->code_size;
6611         ji = info->ji;
6612         unwind_ops = info->unwind_ops;
6613
6614         /* Emit code */
6615
6616         sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6617
6618         emit_section_change (acfg, ".text", 0);
6619         emit_global (acfg, start_symbol, TRUE);
6620         emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6621         emit_label (acfg, start_symbol);
6622
6623         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6624         emit_label (acfg, symbol);
6625
6626         /* 
6627          * The code should access everything through the GOT, so we pass
6628          * TRUE here.
6629          */
6630         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6631
6632         emit_symbol_size (acfg, start_symbol, ".");
6633
6634         if (emit_tinfo) {
6635                 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6636                 emit_label (acfg, end_symbol);
6637         }
6638
6639         /* Emit info */
6640
6641         /* Sort relocations */
6642         patches = g_ptr_array_new ();
6643         for (patch_info = ji; patch_info; patch_info = patch_info->next)
6644                 if (patch_info->type != MONO_PATCH_INFO_NONE)
6645                         g_ptr_array_add (patches, patch_info);
6646         g_ptr_array_sort (patches, compare_patches);
6647
6648         buf_size = patches->len * 128 + 128;
6649         buf = (guint8 *)g_malloc (buf_size);
6650         p = buf;
6651
6652         encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6653         g_assert (p - buf < buf_size);
6654         g_ptr_array_free (patches, TRUE);
6655
6656         sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6657
6658         info_offset = add_to_blob (acfg, buf, p - buf);
6659
6660         emit_section_change (acfg, RODATA_SECT, 0);
6661         emit_global (acfg, symbol, FALSE);
6662         emit_label (acfg, symbol);
6663
6664         emit_int32 (acfg, info_offset);
6665
6666         if (emit_tinfo) {
6667                 guint8 *encoded;
6668                 guint32 encoded_len;
6669                 guint32 uw_offset;
6670
6671                 /*
6672                  * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6673                  */
6674                 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6675                 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6676                 g_free (encoded);
6677
6678                 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6679                 emit_int32 (acfg, uw_offset);
6680         }
6681
6682         /* Emit debug info */
6683         if (unwind_ops) {
6684                 char symbol2 [MAX_SYMBOL_SIZE];
6685
6686                 sprintf (symbol, "%s", name);
6687                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6688
6689                 if (acfg->dwarf)
6690                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6691         }
6692
6693         g_free (buf);
6694 }
6695
6696 static G_GNUC_UNUSED void
6697 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6698 {
6699         emit_trampoline_full (acfg, got_offset, info, TRUE);
6700 }
6701
6702 static void
6703 emit_trampolines (MonoAotCompile *acfg)
6704 {
6705         char symbol [MAX_SYMBOL_SIZE];
6706         char end_symbol [MAX_SYMBOL_SIZE];
6707         int i, tramp_got_offset;
6708         int ntype;
6709 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6710         int tramp_type;
6711 #endif
6712
6713         if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6714                 return;
6715         
6716         g_assert (acfg->image->assembly);
6717
6718         /* Currently, we emit most trampolines into the mscorlib AOT image. */
6719         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6720 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6721                 MonoTrampInfo *info;
6722
6723                 /*
6724                  * Emit the generic trampolines.
6725                  *
6726                  * We could save some code by treating the generic trampolines as a wrapper
6727                  * method, but that approach has its own complexities, so we choose the simpler
6728                  * method.
6729                  */
6730                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6731                         /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6732 #ifdef DISABLE_REMOTING
6733                         if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6734                                 continue;
6735 #endif
6736 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6737                         if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6738                                 continue;
6739 #endif
6740                         mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6741                         emit_trampoline (acfg, acfg->got_offset, info);
6742                 }
6743
6744                 /* Emit the exception related code pieces */
6745                 mono_arch_get_restore_context (&info, TRUE);
6746                 emit_trampoline (acfg, acfg->got_offset, info);
6747                 mono_arch_get_call_filter (&info, TRUE);
6748                 emit_trampoline (acfg, acfg->got_offset, info);
6749                 mono_arch_get_throw_exception (&info, TRUE);
6750                 emit_trampoline (acfg, acfg->got_offset, info);
6751                 mono_arch_get_rethrow_exception (&info, TRUE);
6752                 emit_trampoline (acfg, acfg->got_offset, info);
6753                 mono_arch_get_throw_corlib_exception (&info, TRUE);
6754                 emit_trampoline (acfg, acfg->got_offset, info);
6755
6756 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6757                 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6758                 emit_trampoline (acfg, acfg->got_offset, info);
6759                 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6760                 emit_trampoline (acfg, acfg->got_offset, info);
6761 #endif
6762
6763 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6764                 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6765                 if (info) {
6766                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6767
6768                         /* Create a separate out trampoline for more information in stack traces */
6769                         info->name = g_strdup ("gsharedvt_out_trampoline");
6770                         emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6771                 }
6772 #endif
6773
6774 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6775                 {
6776                         GSList *l = mono_arch_get_trampolines (TRUE);
6777
6778                         while (l) {
6779                                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6780
6781                                 emit_trampoline (acfg, acfg->got_offset, info);
6782                                 l = l->next;
6783                         }
6784                 }
6785 #endif
6786
6787                 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6788                         int offset;
6789
6790                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6791                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6792                         emit_trampoline (acfg, acfg->got_offset, info);
6793                         g_free (info);
6794
6795                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6796                         mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6797                         emit_trampoline (acfg, acfg->got_offset, info);
6798                         g_free (info);
6799                 }
6800
6801 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6802                 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6803                 emit_trampoline (acfg, acfg->got_offset, info);
6804 #endif
6805
6806                 {
6807                         GSList *l;
6808
6809                         /* delegate_invoke_impl trampolines */
6810                         l = mono_arch_get_delegate_invoke_impls ();
6811                         while (l) {
6812                                 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6813
6814                                 emit_trampoline (acfg, acfg->got_offset, info);
6815                                 l = l->next;
6816                         }
6817                 }
6818
6819 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6820                 mono_arch_create_handler_block_trampoline (&info, TRUE);
6821                 emit_trampoline (acfg, acfg->got_offset, info);
6822 #endif
6823
6824 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6825
6826                 /* Emit trampolines which are numerous */
6827
6828                 /*
6829                  * These include the following:
6830                  * - specific trampolines
6831                  * - static rgctx invoke trampolines
6832                  * - imt trampolines
6833                  * These trampolines have the same code, they are parameterized by GOT 
6834                  * slots. 
6835                  * They are defined in this file, in the arch_... routines instead of
6836                  * in tramp-<ARCH>.c, since it is easier to do it this way.
6837                  */
6838
6839                 /*
6840                  * When running in aot-only mode, we can't create specific trampolines at 
6841                  * runtime, so we create a few, and save them in the AOT file. 
6842                  * Normal trampolines embed their argument as a literal inside the 
6843                  * trampoline code, we can't do that here, so instead we embed an offset
6844                  * which needs to be added to the trampoline address to get the address of
6845                  * the GOT slot which contains the argument value.
6846                  * The generated trampolines jump to the generic trampolines using another
6847                  * GOT slot, which will be setup by the AOT loader to point to the 
6848                  * generic trampoline code of the given type.
6849                  */
6850
6851                 /*
6852                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6853                  * each class).
6854                  */
6855
6856                 emit_section_change (acfg, ".text", 0);
6857
6858                 tramp_got_offset = acfg->got_offset;
6859
6860                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6861                         switch (ntype) {
6862                         case MONO_AOT_TRAMP_SPECIFIC:
6863                                 sprintf (symbol, "specific_trampolines");
6864                                 break;
6865                         case MONO_AOT_TRAMP_STATIC_RGCTX:
6866                                 sprintf (symbol, "static_rgctx_trampolines");
6867                                 break;
6868                         case MONO_AOT_TRAMP_IMT:
6869                                 sprintf (symbol, "imt_trampolines");
6870                                 break;
6871                         case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6872                                 sprintf (symbol, "gsharedvt_arg_trampolines");
6873                                 break;
6874                         default:
6875                                 g_assert_not_reached ();
6876                         }
6877
6878                         sprintf (end_symbol, "%s_e", symbol);
6879
6880                         if (acfg->aot_opts.write_symbols)
6881                                 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6882
6883                         emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6884                         emit_info_symbol (acfg, symbol);
6885
6886                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6887
6888                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6889                                 int tramp_size = 0;
6890
6891                                 switch (ntype) {
6892                                 case MONO_AOT_TRAMP_SPECIFIC:
6893                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6894                                         tramp_got_offset += 2;
6895                                 break;
6896                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
6897                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
6898                                         tramp_got_offset += 2;
6899                                         break;
6900                                 case MONO_AOT_TRAMP_IMT:
6901                                         arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6902                                         tramp_got_offset += 1;
6903                                         break;
6904                                 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6905                                         arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);                               
6906                                         tramp_got_offset += 2;
6907                                         break;
6908                                 default:
6909                                         g_assert_not_reached ();
6910                                 }
6911                                 if (!acfg->trampoline_size [ntype]) {
6912                                         g_assert (tramp_size);
6913                                         acfg->trampoline_size [ntype] = tramp_size;
6914                                 }
6915                         }
6916
6917                         emit_label (acfg, end_symbol);
6918                         emit_int32 (acfg, 0);
6919                 }
6920
6921                 arch_emit_specific_trampoline_pages (acfg);
6922
6923                 /* Reserve some entries at the end of the GOT for our use */
6924                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6925         }
6926
6927         acfg->got_offset += acfg->num_trampoline_got_entries;
6928 }
6929
6930 static gboolean
6931 str_begins_with (const char *str1, const char *str2)
6932 {
6933         int len = strlen (str2);
6934         return strncmp (str1, str2, len) == 0;
6935 }
6936
6937 void*
6938 mono_aot_readonly_field_override (MonoClassField *field)
6939 {
6940         ReadOnlyValue *rdv;
6941         for (rdv = readonly_values; rdv; rdv = rdv->next) {
6942                 char *p = rdv->name;
6943                 int len;
6944                 len = strlen (field->parent->name_space);
6945                 if (strncmp (p, field->parent->name_space, len))
6946                         continue;
6947                 p += len;
6948                 if (*p++ != '.')
6949                         continue;
6950                 len = strlen (field->parent->name);
6951                 if (strncmp (p, field->parent->name, len))
6952                         continue;
6953                 p += len;
6954                 if (*p++ != '.')
6955                         continue;
6956                 if (strcmp (p, field->name))
6957                         continue;
6958                 switch (rdv->type) {
6959                 case MONO_TYPE_I1:
6960                         return &rdv->value.i1;
6961                 case MONO_TYPE_I2:
6962                         return &rdv->value.i2;
6963                 case MONO_TYPE_I4:
6964                         return &rdv->value.i4;
6965                 default:
6966                         break;
6967                 }
6968         }
6969         return NULL;
6970 }
6971
6972 static void
6973 add_readonly_value (MonoAotOptions *opts, const char *val)
6974 {
6975         ReadOnlyValue *rdv;
6976         const char *fval;
6977         const char *tval;
6978         /* the format of val is:
6979          * namespace.typename.fieldname=type/value
6980          * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6981          */
6982         fval = strrchr (val, '/');
6983         if (!fval) {
6984                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6985                 exit (1);
6986         }
6987         tval = strrchr (val, '=');
6988         if (!tval) {
6989                 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6990                 exit (1);
6991         }
6992         rdv = g_new0 (ReadOnlyValue, 1);
6993         rdv->name = (char *)g_malloc0 (tval - val + 1);
6994         memcpy (rdv->name, val, tval - val);
6995         tval++;
6996         fval++;
6997         if (strncmp (tval, "i1", 2) == 0) {
6998                 rdv->value.i1 = atoi (fval);
6999                 rdv->type = MONO_TYPE_I1;
7000         } else if (strncmp (tval, "i2", 2) == 0) {
7001                 rdv->value.i2 = atoi (fval);
7002                 rdv->type = MONO_TYPE_I2;
7003         } else if (strncmp (tval, "i4", 2) == 0) {
7004                 rdv->value.i4 = atoi (fval);
7005                 rdv->type = MONO_TYPE_I4;
7006         } else {
7007                 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7008                 exit (1);
7009         }
7010         rdv->next = readonly_values;
7011         readonly_values = rdv;
7012 }
7013
7014 static gchar *
7015 clean_path (gchar * path)
7016 {
7017         if (!path)
7018                 return NULL;
7019
7020         if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7021                 return path;
7022
7023         gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7024         g_free (path);
7025
7026         return clean;
7027 }
7028
7029 static gchar *
7030 wrap_path (gchar * path)
7031 {
7032         int len;
7033         if (!path)
7034                 return NULL;
7035
7036         // If the string contains no spaces, just return the original string.
7037         if (strstr (path, " ") == NULL)
7038                 return path;
7039
7040         // If the string is already wrapped in quotes, return it.
7041         len = strlen (path);
7042         if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7043                 return path;
7044
7045         // If the string contains spaces, then wrap it in quotes.
7046         gchar *clean = g_strdup_printf ("\"%s\"", path);
7047
7048         return clean;
7049 }
7050
7051 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7052 static void
7053 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7054 {
7055         ptrdiff_t len = end-start;
7056         if (len > 0)
7057                 g_ptr_array_add (args, g_strndup (start, len));
7058 }
7059
7060 static GPtrArray *
7061 mono_aot_split_options (const char *aot_options)
7062 {
7063         enum MonoAotOptionState {
7064                 MONO_AOT_OPTION_STATE_DEFAULT,
7065                 MONO_AOT_OPTION_STATE_STRING,
7066                 MONO_AOT_OPTION_STATE_ESCAPE,
7067         };
7068
7069         GPtrArray *args = g_ptr_array_new ();
7070         enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7071         gchar const *opt_start = aot_options;
7072         gboolean end_of_string = FALSE;
7073         gchar cur;
7074
7075         g_return_val_if_fail (aot_options != NULL, NULL);
7076
7077         while ((cur = *aot_options) != '\0') {
7078                 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7079                         goto next;
7080
7081                 switch (cur) {
7082                 case '"':
7083                         // If we find a quote, then if we're in the default case then
7084                         // it means we've found the start of a string, if not then it
7085                         // means we've found the end of the string and should switch
7086                         // back to the default case.            
7087                         switch (state) {
7088                         case MONO_AOT_OPTION_STATE_DEFAULT:
7089                                 state = MONO_AOT_OPTION_STATE_STRING;
7090                                 break;
7091                         case MONO_AOT_OPTION_STATE_STRING:
7092                                 state = MONO_AOT_OPTION_STATE_DEFAULT;
7093                                 break;
7094                         case MONO_AOT_OPTION_STATE_ESCAPE:
7095                                 g_assert_not_reached ();
7096                                 break;
7097                         }
7098                         break;
7099                 case '\\':
7100                         // If we've found an escaping operator, then this means we
7101                         // should not process the next character if inside a string.            
7102                         if (state == MONO_AOT_OPTION_STATE_STRING) 
7103                                 state = MONO_AOT_OPTION_STATE_ESCAPE;
7104                         break;
7105                 case ',':
7106                         // If we're in the default state then this means we've found
7107                         // an option, store it for later processing.
7108                         if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7109                                 goto new_opt;
7110                         break;
7111                 }
7112
7113         next:
7114                 aot_options++;
7115         restart:
7116                 // If the next character is end of string, then process the last option.
7117                 if (*(aot_options) == '\0') {
7118                         end_of_string = TRUE;
7119                         goto new_opt;
7120                 }
7121                 continue;
7122
7123         new_opt:
7124                 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7125                 opt_start = ++aot_options;
7126                 if (end_of_string)
7127                         break;
7128                 goto restart; // Check for null and continue loop
7129         }
7130
7131         return args;
7132 }
7133
7134 static void
7135 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7136 {
7137         GPtrArray* args;
7138
7139         args = mono_aot_split_options (aot_options ? aot_options : "");
7140         for (int i = 0; i < args->len; ++i) {
7141                 const char *arg = (const char *)g_ptr_array_index (args, i);
7142
7143                 if (str_begins_with (arg, "outfile=")) {
7144                         opts->outfile = g_strdup (arg + strlen ("outfile="));
7145                 } else if (str_begins_with (arg, "llvm-outfile=")) {
7146                         opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7147                 } else if (str_begins_with (arg, "temp-path=")) {
7148                         opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7149                 } else if (str_begins_with (arg, "save-temps")) {
7150                         opts->save_temps = TRUE;
7151                 } else if (str_begins_with (arg, "keep-temps")) {
7152                         opts->save_temps = TRUE;
7153                 } else if (str_begins_with (arg, "write-symbols")) {
7154                         opts->write_symbols = TRUE;
7155                 } else if (str_begins_with (arg, "no-write-symbols")) {
7156                         opts->write_symbols = FALSE;
7157                 // Intentionally undocumented -- one-off experiment
7158                 } else if (str_begins_with (arg, "metadata-only")) {
7159                         opts->metadata_only = TRUE;
7160                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7161                         opts->bind_to_runtime_version = TRUE;
7162                 } else if (str_begins_with (arg, "full")) {
7163                         opts->mode = MONO_AOT_MODE_FULL;
7164                 } else if (str_begins_with (arg, "hybrid")) {
7165                         opts->mode = MONO_AOT_MODE_HYBRID;                      
7166                 } else if (str_begins_with (arg, "threads=")) {
7167                         opts->nthreads = atoi (arg + strlen ("threads="));
7168                 } else if (str_begins_with (arg, "static")) {
7169                         opts->static_link = TRUE;
7170                         opts->no_dlsym = TRUE;
7171                 } else if (str_begins_with (arg, "asmonly")) {
7172                         opts->asm_only = TRUE;
7173                 } else if (str_begins_with (arg, "asmwriter")) {
7174                         opts->asm_writer = TRUE;
7175                 } else if (str_begins_with (arg, "nodebug")) {
7176                         opts->nodebug = TRUE;
7177                 } else if (str_begins_with (arg, "dwarfdebug")) {
7178                         opts->dwarf_debug = TRUE;
7179                 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7180                 } else if (str_begins_with (arg, "nopagetrampolines")) {
7181                         opts->use_trampolines_page = FALSE;
7182                 } else if (str_begins_with (arg, "ntrampolines=")) {
7183                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7184                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7185                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7186                 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7187                         opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7188                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7189                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7190                 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7191                         opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7192                 } else if (str_begins_with (arg, "tool-prefix=")) {
7193                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7194                 } else if (str_begins_with (arg, "ld-flags=")) {
7195                         opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));                 
7196                 } else if (str_begins_with (arg, "soft-debug")) {
7197                         opts->soft_debug = TRUE;
7198                 // Intentionally undocumented x2-- deprecated
7199                 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7200                         fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7201                 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7202                         fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7203                 } else if (str_begins_with (arg, "msym-dir=")) {
7204                         debug_options.no_seq_points_compact_data = FALSE;
7205                         opts->gen_msym_dir = TRUE;
7206                         opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7207                 } else if (str_begins_with (arg, "direct-pinvoke")) {
7208                         opts->direct_pinvoke = TRUE;
7209                 } else if (str_begins_with (arg, "direct-icalls")) {
7210                         opts->direct_icalls = TRUE;
7211                 } else if (str_begins_with (arg, "no-direct-calls")) {
7212                         opts->no_direct_calls = TRUE;
7213                 } else if (str_begins_with (arg, "print-skipped")) {
7214                         opts->print_skipped_methods = TRUE;
7215                 } else if (str_begins_with (arg, "stats")) {
7216                         opts->stats = TRUE;
7217                 // Intentionally undocumented-- has no known function other than to debug the compiler
7218                 } else if (str_begins_with (arg, "no-instances")) {
7219                         opts->no_instances = TRUE;
7220                 // Intentionally undocumented x4-- Used for internal debugging of compiler
7221                 } else if (str_begins_with (arg, "log-generics")) {
7222                         opts->log_generics = TRUE;
7223                 } else if (str_begins_with (arg, "log-instances=")) {
7224                         opts->log_instances = TRUE;
7225                         opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7226                 } else if (str_begins_with (arg, "log-instances")) {
7227                         opts->log_instances = TRUE;
7228                 } else if (str_begins_with (arg, "internal-logfile=")) {
7229                         opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7230                 } else if (str_begins_with (arg, "mtriple=")) {
7231                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7232                 } else if (str_begins_with (arg, "llvm-path=")) {
7233                         opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7234                 } else if (!strcmp (arg, "llvm")) {
7235                         opts->llvm = TRUE;
7236                 } else if (str_begins_with (arg, "readonly-value=")) {
7237                         add_readonly_value (opts, arg + strlen ("readonly-value="));
7238                 } else if (str_begins_with (arg, "info")) {
7239                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7240                         exit (0);
7241                 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7242                 } else if (str_begins_with (arg, "gc-maps")) {
7243                         mini_gc_enable_gc_maps_for_aot ();
7244                 // Intentionally undocumented: Used for internal debugging
7245                 } else if (str_begins_with (arg, "dump")) {
7246                         opts->dump_json = TRUE;
7247                 } else if (str_begins_with (arg, "llvmonly")) {
7248                         opts->mode = MONO_AOT_MODE_FULL;
7249                         opts->llvm = TRUE;
7250                         opts->llvm_only = TRUE;
7251                 } else if (str_begins_with (arg, "data-outfile=")) {
7252                         opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7253                 } else if (str_begins_with (arg, "profile=")) {
7254                         opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7255                 } else if (!strcmp (arg, "profile-only")) {
7256                         opts->profile_only = TRUE;
7257                 } else if (!strcmp (arg, "verbose")) {
7258                         opts->verbose = TRUE;
7259                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7260                         printf ("Supported options for --aot:\n");
7261                         printf ("    asmonly\n");
7262                         printf ("    bind-to-runtime-version\n");
7263                         printf ("    bitcode\n");
7264                         printf ("    data-outfile=\n");
7265                         printf ("    direct-icalls\n");
7266                         printf ("    direct-pinvoke\n");
7267                         printf ("    dwarfdebug\n");
7268                         printf ("    full\n");
7269                         printf ("    hybrid\n");
7270                         printf ("    info\n");
7271                         printf ("    keep-temps\n");
7272                         printf ("    llvm\n");
7273                         printf ("    llvmonly\n");
7274                         printf ("    llvm-outfile=\n");
7275                         printf ("    llvm-path=\n");
7276                         printf ("    msym-dir=\n");
7277                         printf ("    mtriple\n");
7278                         printf ("    nimt-trampolines=\n");
7279                         printf ("    nodebug\n");
7280                         printf ("    no-direct-calls\n");
7281                         printf ("    no-write-symbols\n");
7282                         printf ("    nrgctx-trampolines=\n");
7283                         printf ("    nrgctx-fetch-trampolines=\n");
7284                         printf ("    ngsharedvt-trampolines=\n");
7285                         printf ("    ntrampolines=\n");
7286                         printf ("    outfile=\n");
7287                         printf ("    profile=\n");
7288                         printf ("    profile-only\n");
7289                         printf ("    print-skipped-methods\n");
7290                         printf ("    readonly-value=\n");
7291                         printf ("    save-temps\n");
7292                         printf ("    soft-debug\n");
7293                         printf ("    static\n");
7294                         printf ("    stats\n");
7295                         printf ("    temp-path=\n");
7296                         printf ("    tool-prefix=\n");
7297                         printf ("    threads=\n");
7298                         printf ("    write-symbols\n");
7299                         printf ("    verbose\n");
7300                         printf ("    help/?\n");
7301                         exit (0);
7302                 } else {
7303                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7304                         exit (1);
7305                 }
7306
7307                 g_free ((gpointer) arg);
7308         }
7309
7310         if (opts->use_trampolines_page) {
7311                 opts->ntrampolines = 0;
7312                 opts->nrgctx_trampolines = 0;
7313                 opts->nimt_trampolines = 0;
7314                 opts->ngsharedvt_arg_trampolines = 0;
7315         }
7316
7317         g_ptr_array_free (args, /*free_seg=*/TRUE);
7318 }
7319
7320 static void
7321 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7322 {
7323         MonoMethod *method = (MonoMethod*)key;
7324         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7325         MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7326         MonoJumpInfoToken *new_ji;
7327
7328         new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7329         new_ji->image = ji->image;
7330         new_ji->token = ji->token;
7331         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7332 }
7333
7334 static gboolean
7335 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7336 {
7337         if (klass->type_token)
7338                 return TRUE;
7339         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7340                 return TRUE;
7341         if (klass->rank)
7342                 return can_encode_class (acfg, klass->element_class);
7343         return FALSE;
7344 }
7345
7346 static gboolean
7347 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7348 {
7349                 if (method->wrapper_type) {
7350                         switch (method->wrapper_type) {
7351                         case MONO_WRAPPER_NONE:
7352                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7353                         case MONO_WRAPPER_XDOMAIN_INVOKE:
7354                         case MONO_WRAPPER_STFLD:
7355                         case MONO_WRAPPER_LDFLD:
7356                         case MONO_WRAPPER_LDFLDA:
7357                         case MONO_WRAPPER_STELEMREF:
7358                         case MONO_WRAPPER_PROXY_ISINST:
7359                         case MONO_WRAPPER_ALLOC:
7360                         case MONO_WRAPPER_REMOTING_INVOKE:
7361                         case MONO_WRAPPER_UNKNOWN:
7362                         case MONO_WRAPPER_WRITE_BARRIER:
7363                         case MONO_WRAPPER_DELEGATE_INVOKE:
7364                         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7365                         case MONO_WRAPPER_DELEGATE_END_INVOKE:
7366                         case MONO_WRAPPER_SYNCHRONIZED:
7367                                 break;
7368                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
7369                         case MONO_WRAPPER_CASTCLASS: {
7370                                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7371
7372                                 if (info)
7373                                         return TRUE;
7374                                 else
7375                                         return FALSE;
7376                                 break;
7377                         }
7378                         default:
7379                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7380                                 return FALSE;
7381                         }
7382                 } else {
7383                         if (!method->token) {
7384                                 /* The method is part of a constructed type like Int[,].Set (). */
7385                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7386                                         if (method->klass->rank)
7387                                                 return TRUE;
7388                                         return FALSE;
7389                                 }
7390                         }
7391                 }
7392                 return TRUE;
7393 }
7394
7395 static gboolean
7396 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7397 {
7398         switch (patch_info->type) {
7399         case MONO_PATCH_INFO_METHOD:
7400         case MONO_PATCH_INFO_METHODCONST:
7401         case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7402                 MonoMethod *method = patch_info->data.method;
7403
7404                 return can_encode_method (acfg, method);
7405         }
7406         case MONO_PATCH_INFO_VTABLE:
7407         case MONO_PATCH_INFO_CLASS:
7408         case MONO_PATCH_INFO_IID:
7409         case MONO_PATCH_INFO_ADJUSTED_IID:
7410                 if (!can_encode_class (acfg, patch_info->data.klass)) {
7411                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7412                         return FALSE;
7413                 }
7414                 break;
7415         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7416                 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7417                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7418                         return FALSE;
7419                 }
7420                 break;
7421         }
7422         case MONO_PATCH_INFO_RGCTX_FETCH:
7423         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7424                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7425
7426                 if (!can_encode_method (acfg, entry->method))
7427                         return FALSE;
7428                 if (!can_encode_patch (acfg, entry->data))
7429                         return FALSE;
7430                 break;
7431         }
7432         default:
7433                 break;
7434         }
7435
7436         return TRUE;
7437 }
7438
7439 static gboolean
7440 is_concrete_type (MonoType *t)
7441 {
7442         MonoClass *klass;
7443         int i;
7444
7445         if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7446                 return FALSE;
7447         if (t->type == MONO_TYPE_GENERICINST) {
7448                 MonoGenericContext *orig_ctx;
7449                 MonoGenericInst *inst;
7450                 MonoType *arg;
7451
7452                 if (!MONO_TYPE_ISSTRUCT (t))
7453                         return TRUE;
7454                 klass = mono_class_from_mono_type (t);
7455                 orig_ctx = &mono_class_get_generic_class (klass)->context;
7456
7457                 inst = orig_ctx->class_inst;
7458                 if (inst) {
7459                         for (i = 0; i < inst->type_argc; ++i) {
7460                                 arg = mini_get_underlying_type (inst->type_argv [i]);
7461                                 if (!is_concrete_type (arg))
7462                                         return FALSE;
7463                         }
7464                 }
7465                 inst = orig_ctx->method_inst;
7466                 if (inst) {
7467                         for (i = 0; i < inst->type_argc; ++i) {
7468                                 arg = mini_get_underlying_type (inst->type_argv [i]);
7469                                 if (!is_concrete_type (arg))
7470                                         return FALSE;
7471                         }
7472                 }
7473         }
7474         return TRUE;
7475 }
7476
7477 /* LOCKING: Assumes the loader lock is held */
7478 static void
7479 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7480 {
7481         MonoMethod *wrapper;
7482         gboolean concrete = TRUE;
7483         gboolean add_in = gsharedvt_in;
7484         gboolean add_out = gsharedvt_out;
7485
7486         if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7487                 add_in = FALSE;
7488         if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7489                 add_out = FALSE;
7490
7491         if (!add_in && !add_out)
7492                 return;
7493
7494         if (mini_is_gsharedvt_variable_signature (sig))
7495                 return;
7496
7497         if (add_in)
7498                 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7499         if (add_out)
7500                 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7501
7502         if (!sig->has_type_parameters) {
7503                 //printf ("%s\n", mono_signature_full_name (sig));
7504
7505                 if (gsharedvt_in) {
7506                         wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7507                         add_extra_method (acfg, wrapper);
7508                 }
7509                 if (gsharedvt_out) {
7510                         wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7511                         add_extra_method (acfg, wrapper);
7512                 }
7513         } else {
7514                 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7515                 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7516                 int i;
7517
7518                 //printf ("%s\n", mono_signature_full_name (sig));
7519
7520                 copy->ret = mini_get_underlying_type (sig->ret);
7521                 if (!is_concrete_type (copy->ret))
7522                         concrete = FALSE;
7523                 for (i = 0; i < sig->param_count; ++i) {
7524                         copy->params [i] = mini_get_underlying_type (sig->params [i]);
7525                         if (!is_concrete_type (copy->params [i]))
7526                                 concrete = FALSE;
7527                 }
7528                 if (concrete) {
7529                         copy->has_type_parameters = 0;
7530
7531                         if (gsharedvt_in) {
7532                                 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7533                                 add_extra_method (acfg, wrapper);
7534                         }
7535
7536                         if (gsharedvt_out) {
7537                                 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7538                                 add_extra_method (acfg, wrapper);
7539                         }
7540
7541                         //printf ("%s\n", mono_method_full_name (wrapper, 1));
7542                 }
7543         }
7544 }
7545
7546 /*
7547  * compile_method:
7548  *
7549  *   AOT compile a given method.
7550  * This function might be called by multiple threads, so it must be thread-safe.
7551  */
7552 static void
7553 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7554 {
7555         MonoCompile *cfg;
7556         MonoJumpInfo *patch_info;
7557         gboolean skip;
7558         int index, depth;
7559         MonoMethod *wrapped;
7560         GTimer *jit_timer;
7561         JitFlags flags;
7562
7563         if (acfg->aot_opts.metadata_only)
7564                 return;
7565
7566         mono_acfg_lock (acfg);
7567         index = get_method_index (acfg, method);
7568         mono_acfg_unlock (acfg);
7569
7570         /* fixme: maybe we can also precompile wrapper methods */
7571         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7572                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7573                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7574                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7575                 return;
7576         }
7577
7578         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7579                 return;
7580
7581         wrapped = mono_marshal_method_from_wrapper (method);
7582         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7583                 // FIXME: The wrapper should be generic too, but it is not
7584                 return;
7585
7586         if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7587                 return;
7588
7589         if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7590                 return;
7591
7592         InterlockedIncrement (&acfg->stats.mcount);
7593
7594 #if 0
7595         if (method->is_generic || mono_class_is_gtd (method->klass)) {
7596                 InterlockedIncrement (&acfg->stats.genericcount);
7597                 return;
7598         }
7599 #endif
7600
7601         //acfg->aot_opts.print_skipped_methods = TRUE;
7602
7603         /*
7604          * Since these methods are the only ones which are compiled with
7605          * AOT support, and they are not used by runtime startup/shutdown code,
7606          * the runtime will not see AOT methods during AOT compilation,so it
7607          * does not need to support them by creating a fake GOT etc.
7608          */
7609         flags = JIT_FLAG_AOT;
7610         if (mono_aot_mode_is_full (&acfg->aot_opts))
7611                 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7612         if (acfg->llvm)
7613                 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7614         if (acfg->aot_opts.llvm_only)
7615                 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7616         if (acfg->aot_opts.no_direct_calls)
7617                 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7618         if (acfg->aot_opts.direct_pinvoke)
7619                 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7620
7621         jit_timer = mono_time_track_start ();
7622         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7623         mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7624
7625         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7626                 if (acfg->aot_opts.print_skipped_methods)
7627                         printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7628                 InterlockedIncrement (&acfg->stats.genericcount);
7629                 return;
7630         }
7631         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7632                 /* Some instances cannot be JITted due to constraints etc. */
7633                 if (!method->is_inflated)
7634                         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));
7635                 /* Let the exception happen at runtime */
7636                 return;
7637         }
7638
7639         if (cfg->disable_aot) {
7640                 if (acfg->aot_opts.print_skipped_methods)
7641                         printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7642                 InterlockedIncrement (&acfg->stats.ocount);
7643                 return;
7644         }
7645         cfg->method_index = index;
7646
7647         /* Nullify patches which need no aot processing */
7648         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7649                 switch (patch_info->type) {
7650                 case MONO_PATCH_INFO_LABEL:
7651                 case MONO_PATCH_INFO_BB:
7652                         patch_info->type = MONO_PATCH_INFO_NONE;
7653                         break;
7654                 default:
7655                         break;
7656                 }
7657         }
7658
7659         /* Collect method->token associations from the cfg */
7660         mono_acfg_lock (acfg);
7661         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7662         mono_acfg_unlock (acfg);
7663         g_hash_table_destroy (cfg->token_info_hash);
7664         cfg->token_info_hash = NULL;
7665
7666         /*
7667          * Check for absolute addresses.
7668          */
7669         skip = FALSE;
7670         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7671                 switch (patch_info->type) {
7672                 case MONO_PATCH_INFO_ABS:
7673                         /* unable to handle this */
7674                         skip = TRUE;    
7675                         break;
7676                 default:
7677                         break;
7678                 }
7679         }
7680
7681         if (skip) {
7682                 if (acfg->aot_opts.print_skipped_methods)
7683                         printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7684                 InterlockedIncrement (&acfg->stats.abscount);
7685                 return;
7686         }
7687
7688         /* Lock for the rest of the code */
7689         mono_acfg_lock (acfg);
7690
7691         if (cfg->gsharedvt)
7692                 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7693         else if (cfg->gshared)
7694                 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7695         else if (cfg->method->wrapper_type)
7696                 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7697         else
7698                 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7699
7700         /*
7701          * Check for methods/klasses we can't encode.
7702          */
7703         skip = FALSE;
7704         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7705                 if (!can_encode_patch (acfg, patch_info))
7706                         skip = TRUE;
7707         }
7708
7709         if (skip) {
7710                 if (acfg->aot_opts.print_skipped_methods)
7711                         printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7712                 acfg->stats.ocount++;
7713                 mono_acfg_unlock (acfg);
7714                 return;
7715         }
7716
7717         if (!cfg->compile_llvm)
7718                 acfg->has_jitted_code = TRUE;
7719
7720         if (method->is_inflated && acfg->aot_opts.log_instances) {
7721                 if (acfg->instances_logfile)
7722                         fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7723                 else
7724                         printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7725         }
7726
7727         /* Adds generic instances referenced by this method */
7728         /* 
7729          * The depth is used to avoid infinite loops when generic virtual recursion is 
7730          * encountered.
7731          */
7732         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7733         if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7734                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7735                         switch (patch_info->type) {
7736                         case MONO_PATCH_INFO_RGCTX_FETCH:
7737                         case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7738                         case MONO_PATCH_INFO_METHOD: {
7739                                 MonoMethod *m = NULL;
7740
7741                                 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7742                                         MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7743
7744                                         if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7745                                                 m = e->data->data.method;
7746                                 } else {
7747                                         m = patch_info->data.method;
7748                                 }
7749
7750                                 if (!m)
7751                                         break;
7752                                 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7753                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
7754                                                   mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7755                                                 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7756                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7757                                                         if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7758                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7759                                                 } else {
7760                                                         add_extra_method_with_depth (acfg, m, depth + 1);
7761                                                         add_types_from_method_header (acfg, m);
7762                                                 }
7763                                         }
7764                                         add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7765                                 }
7766                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7767                                         WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7768
7769                                         if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7770                                                 add_extra_method_with_depth (acfg, m, depth + 1);
7771                                 }
7772                                 break;
7773                         }
7774                         case MONO_PATCH_INFO_VTABLE: {
7775                                 MonoClass *klass = patch_info->data.klass;
7776
7777                                 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7778                                         add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7779                                 break;
7780                         }
7781                         case MONO_PATCH_INFO_SFLDA: {
7782                                 MonoClass *klass = patch_info->data.field->parent;
7783
7784                                 /* The .cctor needs to run at runtime. */
7785                                 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))
7786                                         add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7787                                 break;
7788                         }
7789                         default:
7790                                 break;
7791                         }
7792                 }
7793         }
7794
7795         /* Determine whenever the method has GOT slots */
7796         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7797                 switch (patch_info->type) {
7798                 case MONO_PATCH_INFO_GOT_OFFSET:
7799                 case MONO_PATCH_INFO_NONE:
7800                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7801                 case MONO_PATCH_INFO_GC_NURSERY_START:
7802                 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7803                         break;
7804                 case MONO_PATCH_INFO_IMAGE:
7805                         /* The assembly is stored in GOT slot 0 */
7806                         if (patch_info->data.image != acfg->image)
7807                                 cfg->has_got_slots = TRUE;
7808                         break;
7809                 default:
7810                         if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7811                                 cfg->has_got_slots = TRUE;
7812                         break;
7813                 }
7814         }
7815
7816         if (!cfg->has_got_slots)
7817                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7818
7819         /* Add gsharedvt wrappers for signatures used by the method */
7820         if (acfg->aot_opts.llvm_only) {
7821                 GSList *l;
7822
7823                 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7824                         /* These only need out wrappers */
7825                         add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7826
7827                 for (l = cfg->signatures; l; l = l->next) {
7828                         MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7829
7830                         /* These only need in wrappers */
7831                         add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7832                 }
7833         }
7834
7835         /* 
7836          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7837          */
7838         /* Make a copy of the patch info which is in the mempool */
7839         {
7840                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7841
7842                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7843                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7844
7845                         if (!patches)
7846                                 patches = new_patch_info;
7847                         else
7848                                 patches_end->next = new_patch_info;
7849                         patches_end = new_patch_info;
7850                 }
7851                 cfg->patch_info = patches;
7852         }
7853         /* Make a copy of the unwind info */
7854         {
7855                 GSList *l, *unwind_ops;
7856                 MonoUnwindOp *op;
7857
7858                 unwind_ops = NULL;
7859                 for (l = cfg->unwind_ops; l; l = l->next) {
7860                         op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7861                         memcpy (op, l->data, sizeof (MonoUnwindOp));
7862                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7863                 }
7864                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7865         }
7866         /* Make a copy of the argument/local info */
7867         {
7868                 MonoError error;
7869                 MonoInst **args, **locals;
7870                 MonoMethodSignature *sig;
7871                 MonoMethodHeader *header;
7872                 int i;
7873                 
7874                 sig = mono_method_signature (method);
7875                 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7876                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7877                         args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7878                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7879                 }
7880                 cfg->args = args;
7881
7882                 header = mono_method_get_header_checked (method, &error);
7883                 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7884                 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7885                 for (i = 0; i < header->num_locals; ++i) {
7886                         locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7887                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7888                 }
7889                 mono_metadata_free_mh (header);
7890                 cfg->locals = locals;
7891         }
7892
7893         /* Free some fields used by cfg to conserve memory */
7894         mono_empty_compile (cfg);
7895
7896         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
7897
7898         while (index >= acfg->cfgs_size) {
7899                 MonoCompile **new_cfgs;
7900                 int new_size;
7901
7902                 new_size = acfg->cfgs_size * 2;
7903                 new_cfgs = g_new0 (MonoCompile*, new_size);
7904                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7905                 g_free (acfg->cfgs);
7906                 acfg->cfgs = new_cfgs;
7907                 acfg->cfgs_size = new_size;
7908         }
7909         acfg->cfgs [index] = cfg;
7910
7911         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7912
7913         mono_update_jit_stats (cfg);
7914
7915         /*
7916         if (cfg->orig_method->wrapper_type)
7917                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7918         */
7919
7920         mono_acfg_unlock (acfg);
7921
7922         InterlockedIncrement (&acfg->stats.ccount);
7923 }
7924  
7925 static mono_thread_start_return_t WINAPI
7926 compile_thread_main (gpointer user_data)
7927 {
7928         MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7929         GPtrArray *methods = ((GPtrArray **)user_data) [1];
7930         int i;
7931
7932         MonoError error;
7933         MonoInternalThread *internal = mono_thread_internal_current ();
7934         mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "AOT compiler"), TRUE, FALSE, &error);
7935         mono_error_assert_ok (&error);
7936
7937         for (i = 0; i < methods->len; ++i)
7938                 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7939
7940         return 0;
7941 }
7942  
7943 /* Used by the LLVM backend */
7944 guint32
7945 mono_aot_get_got_offset (MonoJumpInfo *ji)
7946 {
7947         return get_got_offset (llvm_acfg, TRUE, ji);
7948 }
7949
7950 /*
7951  * mono_aot_is_shared_got_offset:
7952  *
7953  *   Return whenever OFFSET refers to a GOT slot which is preinitialized
7954  * when the AOT image is loaded.
7955  */
7956 gboolean
7957 mono_aot_is_shared_got_offset (int offset)
7958 {
7959         return offset < llvm_acfg->nshared_got_entries;
7960 }
7961
7962 char*
7963 mono_aot_get_method_name (MonoCompile *cfg)
7964 {
7965         if (llvm_acfg->aot_opts.static_link)
7966                 /* Include the assembly name too to avoid duplicate symbol errors */
7967                 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7968         else
7969                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7970 }
7971
7972 /*
7973  * mono_aot_is_linkonce_method:
7974  *
7975  *   Return whenever METHOD should be emitted with linkonce linkage,
7976  * eliminating duplicate copies when compiling in static mode.
7977  */
7978 gboolean
7979 mono_aot_is_linkonce_method (MonoMethod *method)
7980 {
7981         return FALSE;
7982 #if 0
7983         WrapperInfo *info;
7984
7985         // FIXME: Add more cases
7986         if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7987                 return FALSE;
7988         info = mono_marshal_get_wrapper_info (method);
7989         if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7990                 return TRUE;
7991         return FALSE;
7992 #endif
7993 }
7994
7995 static gboolean
7996 append_mangled_type (GString *s, MonoType *t)
7997 {
7998         if (t->byref)
7999                 g_string_append_printf (s, "b");
8000         switch (t->type) {
8001         case MONO_TYPE_VOID:
8002                 g_string_append_printf (s, "void_");
8003                 break;
8004         case MONO_TYPE_I1:
8005                 g_string_append_printf (s, "i1");
8006                 break;
8007         case MONO_TYPE_U1:
8008                 g_string_append_printf (s, "u1");
8009                 break;
8010         case MONO_TYPE_I2:
8011                 g_string_append_printf (s, "i2");
8012                 break;
8013         case MONO_TYPE_U2:
8014                 g_string_append_printf (s, "u2");
8015                 break;
8016         case MONO_TYPE_I4:
8017                 g_string_append_printf (s, "i4");
8018                 break;
8019         case MONO_TYPE_U4:
8020                 g_string_append_printf (s, "u4");
8021                 break;
8022         case MONO_TYPE_I8:
8023                 g_string_append_printf (s, "i8");
8024                 break;
8025         case MONO_TYPE_U8:
8026                 g_string_append_printf (s, "u8");
8027                 break;
8028         case MONO_TYPE_I:
8029                 g_string_append_printf (s, "ii");
8030                 break;
8031         case MONO_TYPE_U:
8032                 g_string_append_printf (s, "ui");
8033                 break;
8034         case MONO_TYPE_R4:
8035                 g_string_append_printf (s, "fl");
8036                 break;
8037         case MONO_TYPE_R8:
8038                 g_string_append_printf (s, "do");
8039                 break;
8040         default: {
8041                 char *fullname = mono_type_full_name (t);
8042                 GString *temp;
8043                 char *temps;
8044                 int i, len;
8045
8046                 /*
8047                  * Have to create a mangled name which is:
8048                  * - a valid symbol
8049                  * - unique
8050                  */
8051                 temp = g_string_new ("");
8052                 len = strlen (fullname);
8053                 for (i = 0; i < len; ++i) {
8054                         char c = fullname [i];
8055                         if (isalnum (c)) {
8056                                 g_string_append_c (temp, c);
8057                         } else if (c == '_') {
8058                                 g_string_append_c (temp, '_');
8059                                 g_string_append_c (temp, '_');
8060                         } else {
8061                                 g_string_append_c (temp, '_');
8062                                 g_string_append_printf (temp, "%x", (int)c);
8063                         }
8064                 }
8065                 temps = g_string_free (temp, FALSE);
8066                 /* Include the length to avoid different length type names aliasing each other */
8067                 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8068                 g_free (temps);
8069                 return TRUE;
8070         }
8071         }
8072         return TRUE;
8073 }
8074
8075 static gboolean
8076 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8077 {
8078         int i;
8079         gboolean supported;
8080
8081         supported = append_mangled_type (s, sig->ret);
8082         if (!supported)
8083                 return FALSE;
8084         if (sig->hasthis)
8085                 g_string_append_printf (s, "this_");
8086         for (i = 0; i < sig->param_count; ++i) {
8087                 supported = append_mangled_type (s, sig->params [i]);
8088                 if (!supported)
8089                         return FALSE;
8090         }
8091
8092         return TRUE;
8093 }
8094
8095 static void
8096 append_mangled_wrapper_type (GString *s, guint32 wrapper_type) 
8097 {
8098         const char *label;
8099
8100         switch (wrapper_type) {
8101         case MONO_WRAPPER_REMOTING_INVOKE:
8102                 label = "remoting_invoke";
8103                 break;
8104         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8105                 label = "remoting_invoke_check";
8106                 break;
8107         case MONO_WRAPPER_XDOMAIN_INVOKE:
8108                 label = "remoting_invoke_xdomain";
8109                 break;
8110         case MONO_WRAPPER_PROXY_ISINST:
8111                 label = "proxy_isinst";
8112                 break;
8113         case MONO_WRAPPER_LDFLD:
8114                 label = "ldfld";
8115                 break;
8116         case MONO_WRAPPER_LDFLDA:
8117                 label = "ldflda";
8118                 break;
8119         case MONO_WRAPPER_STFLD: 
8120                 label = "stfld";
8121                 break;
8122         case MONO_WRAPPER_ALLOC:
8123                 label = "alloc";
8124                 break;
8125         case MONO_WRAPPER_WRITE_BARRIER:
8126                 label = "write_barrier";
8127                 break;
8128         case MONO_WRAPPER_STELEMREF:
8129                 label = "stelemref";
8130                 break;
8131         case MONO_WRAPPER_UNKNOWN:
8132                 label = "unknown";
8133                 break;
8134         case MONO_WRAPPER_MANAGED_TO_NATIVE:
8135                 label = "man2native";
8136                 break;
8137         case MONO_WRAPPER_SYNCHRONIZED:
8138                 label = "synch";
8139                 break;
8140         case MONO_WRAPPER_MANAGED_TO_MANAGED:
8141                 label = "man2man";
8142                 break;
8143         case MONO_WRAPPER_CASTCLASS:
8144                 label = "castclass";
8145                 break;
8146         case MONO_WRAPPER_RUNTIME_INVOKE:
8147                 label = "run_invoke";
8148                 break;
8149         case MONO_WRAPPER_DELEGATE_INVOKE:
8150                 label = "del_inv";
8151                 break;
8152         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8153                 label = "del_beg_inv";
8154                 break;
8155         case MONO_WRAPPER_DELEGATE_END_INVOKE:
8156                 label = "del_end_inv";
8157                 break;
8158         case MONO_WRAPPER_NATIVE_TO_MANAGED:
8159                 label = "native2man";
8160                 break;
8161         default:
8162                 g_assert_not_reached ();
8163         }
8164
8165         g_string_append_printf (s, "%s_", label);
8166 }
8167
8168 static void
8169 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype) 
8170 {
8171         const char *label;
8172
8173         switch (subtype) 
8174         {
8175         case WRAPPER_SUBTYPE_NONE:
8176                 return;
8177         case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8178                 label = "elem_addr";
8179                 break;
8180         case WRAPPER_SUBTYPE_STRING_CTOR:
8181                 label = "str_ctor";
8182                 break;
8183         case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8184                 label = "virt_stelem";
8185                 break;
8186         case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8187                 label = "fast_mon_enter";
8188                 break;
8189         case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8190                 label = "fast_mon_enter_4";
8191                 break;
8192         case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8193                 label = "fast_monitor_exit";
8194                 break;
8195         case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8196                 label = "ptr2struct";
8197                 break;
8198         case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8199                 label = "struct2ptr";
8200                 break;
8201         case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8202                 label = "castclass_w_cache";
8203                 break;
8204         case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8205                 label = "isinst_w_cache";
8206                 break;
8207         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8208                 label = "run_inv_norm";
8209                 break;
8210         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8211                 label = "run_inv_dyn";
8212                 break;
8213         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8214                 label = "run_inv_dir";
8215                 break;
8216         case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8217                 label = "run_inv_vir";
8218                 break;
8219         case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8220                 label = "icall";
8221                 break;
8222         case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8223                 label = "native_func_aot";
8224                 break;
8225         case WRAPPER_SUBTYPE_PINVOKE:
8226                 label = "pinvoke";
8227                 break;
8228         case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8229                 label = "synch_inner";
8230                 break;
8231         case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8232                 label = "gshared_in";
8233                 break;
8234         case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8235                 label = "gshared_out";
8236                 break;
8237         case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8238                 label = "array_acc";
8239                 break;
8240         case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8241                 label = "generic_arry_help";
8242                 break;
8243         case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8244                 label = "del_inv_virt";
8245                 break;
8246         case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8247                 label = "del_inv_bound";
8248                 break;
8249         case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8250                 label = "gsharedvt_in_sig";
8251                 break;
8252         case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8253                 label = "gsharedvt_out_sig";
8254                 break;
8255         default:
8256                 g_assert_not_reached ();
8257         }
8258
8259         g_string_append_printf (s, "%s_", label);
8260 }
8261
8262 static char *
8263 sanitize_mangled_string (const char *input)
8264 {
8265         GString *s = g_string_new ("");
8266
8267         for (int i=0; input [i] != '\0'; i++) {
8268                 char c = input [i];
8269                 switch (c) {
8270                 case '.':
8271                         g_string_append (s, "_dot_");
8272                         break;
8273                 case ' ':
8274                         g_string_append (s, "_");
8275                         break;
8276                 case '`':
8277                         g_string_append (s, "_bt_");
8278                         break;
8279                 case '<':
8280                         g_string_append (s, "_le_");
8281                         break;
8282                 case '>':
8283                         g_string_append (s, "_gt_");
8284                         break;
8285                 case '/':
8286                         g_string_append (s, "_sl_");
8287                         break;
8288                 case '[':
8289                         g_string_append (s, "_lbrack_");
8290                         break;
8291                 case ']':
8292                         g_string_append (s, "_rbrack_");
8293                         break;
8294                 case '(':
8295                         g_string_append (s, "_lparen_");
8296                         break;
8297                 case '-':
8298                         g_string_append (s, "_dash_");
8299                         break;
8300                 case ')':
8301                         g_string_append (s, "_rparen_");
8302                         break;
8303                 case ',':
8304                         g_string_append (s, "_comma_");
8305                         break;
8306                 default:
8307                         g_string_append_c (s, c);
8308                 }
8309         }
8310
8311         return g_string_free (s, FALSE);
8312 }
8313
8314 static gboolean
8315 append_mangled_klass (GString *s, MonoClass *klass)
8316 {
8317         char *klass_desc = mono_class_full_name (klass);
8318         g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8319         g_free (klass_desc);
8320
8321         // Success
8322         return TRUE;
8323 }
8324
8325 static gboolean
8326 append_mangled_method (GString *s, MonoMethod *method);
8327
8328 static gboolean
8329 append_mangled_wrapper (GString *s, MonoMethod *method) 
8330 {
8331         gboolean success = TRUE;
8332         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8333         g_string_append_printf (s, "wrapper_");
8334
8335         append_mangled_wrapper_type (s, method->wrapper_type);
8336
8337         switch (method->wrapper_type) {
8338         case MONO_WRAPPER_REMOTING_INVOKE:
8339         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8340         case MONO_WRAPPER_XDOMAIN_INVOKE: {
8341                 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8342                 g_assert (m);
8343                 success = success && append_mangled_method (s, m);
8344                 break;
8345         }
8346         case MONO_WRAPPER_PROXY_ISINST:
8347         case MONO_WRAPPER_LDFLD:
8348         case MONO_WRAPPER_LDFLDA:
8349         case MONO_WRAPPER_STFLD: {
8350                 g_assert (info);
8351                 success = success && append_mangled_klass (s, info->d.proxy.klass);
8352                 break;
8353         }
8354         case MONO_WRAPPER_ALLOC: {
8355                 /* The GC name is saved once in MonoAotFileInfo */
8356                 g_assert (info->d.alloc.alloc_type != -1);
8357                 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8358                 // SlowAlloc, etc
8359                 g_string_append_printf (s, "%s_", method->name);
8360                 break;
8361         }
8362         case MONO_WRAPPER_WRITE_BARRIER: {
8363                 break;
8364         }
8365         case MONO_WRAPPER_STELEMREF: {
8366                 append_mangled_wrapper_subtype (s, info->subtype);
8367                 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8368                         g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8369                 break;
8370         }
8371         case MONO_WRAPPER_UNKNOWN: {
8372                 append_mangled_wrapper_subtype (s, info->subtype);
8373                 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8374                         info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8375                         success = success && append_mangled_klass (s, method->klass);
8376                 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8377                         success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8378                 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8379                         success = success && append_mangled_method (s, info->d.array_accessor.method);
8380                 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8381                         append_mangled_signature (s, info->d.gsharedvt.sig);
8382                 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8383                         append_mangled_signature (s, info->d.gsharedvt.sig);
8384                 break;
8385         }
8386         case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8387                 append_mangled_wrapper_subtype (s, info->subtype);
8388                 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8389                         g_string_append_printf (s, "%s", method->name);
8390                 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8391                         success = success && append_mangled_method (s, info->d.managed_to_native.method);
8392                 } else {
8393                         g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8394                         success = success && append_mangled_method (s, info->d.managed_to_native.method);
8395                 }
8396                 break;
8397         }
8398         case MONO_WRAPPER_SYNCHRONIZED: {
8399                 MonoMethod *m;
8400
8401                 m = mono_marshal_method_from_wrapper (method);
8402                 g_assert (m);
8403                 g_assert (m != method);
8404                 success = success && append_mangled_method (s, m);
8405                 break;
8406         }
8407         case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8408                 append_mangled_wrapper_subtype (s, info->subtype);
8409
8410                 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8411                         g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8412                         g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8413                 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8414                         success = success && append_mangled_method (s, info->d.string_ctor.method);
8415                 } else {
8416                         g_assert_not_reached ();
8417                 }
8418                 break;
8419         }
8420         case MONO_WRAPPER_CASTCLASS: {
8421                 append_mangled_wrapper_subtype (s, info->subtype);
8422                 break;
8423         }
8424         case MONO_WRAPPER_RUNTIME_INVOKE: {
8425                 append_mangled_wrapper_subtype (s, info->subtype);
8426                 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8427                         success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8428                 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8429                         success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8430                 break;
8431         }
8432         case MONO_WRAPPER_DELEGATE_INVOKE:
8433         case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8434         case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8435                 if (method->is_inflated) {
8436                         /* These wrappers are identified by their class */
8437                         g_string_append_printf (s, "i_");
8438                         success = success && append_mangled_klass (s, method->klass);
8439                 } else {
8440                         WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8441
8442                         g_string_append_printf (s, "u_");
8443                         if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8444                                 append_mangled_wrapper_subtype (s, info->subtype);
8445                         g_string_append_printf (s, "u_sigstart");
8446                 }
8447                 break;
8448         }
8449         case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8450                 g_assert (info);
8451                 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8452                 success = success && append_mangled_klass (s, method->klass);
8453                 break;
8454         }
8455         default:
8456                 g_assert_not_reached ();
8457         }
8458         return success && append_mangled_signature (s, mono_method_signature (method));
8459 }
8460
8461 static void
8462 append_mangled_context (GString *str, MonoGenericContext *context)
8463 {
8464         GString *res = g_string_new ("");
8465
8466         g_string_append_printf (res, "gens_");
8467         g_string_append (res, "00");
8468
8469         gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8470         good = good || (context->method_inst && context->method_inst->type_argc > 0);
8471         g_assert (good);
8472
8473         if (context->class_inst)
8474                 mono_ginst_get_desc (res, context->class_inst);
8475         if (context->method_inst) {
8476                 if (context->class_inst)
8477                         g_string_append (res, "11");
8478                 mono_ginst_get_desc (res, context->method_inst);
8479         }
8480         g_string_append_printf (str, "gens_%s", res->str);
8481 }       
8482
8483 static gboolean
8484 append_mangled_method (GString *s, MonoMethod *method)
8485 {
8486         if (method->wrapper_type)
8487                 return append_mangled_wrapper (s, method);
8488
8489         g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8490
8491         if (method->is_inflated) {
8492                 g_string_append_printf (s, "inflated_");
8493                 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8494                 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8495
8496                 append_mangled_context (s, &imethod->context);
8497                 g_string_append_printf (s, "_declared_by_");
8498                 append_mangled_method (s, imethod->declaring);
8499         } else if (method->is_generic) {
8500                 g_string_append_printf (s, "generic_");
8501                 append_mangled_klass (s, method->klass);
8502                 g_string_append_printf (s, "_%s_", method->name);
8503
8504                 MonoGenericContainer *container = mono_method_get_generic_container (method);
8505                 g_string_append_printf (s, "_%s");
8506                 append_mangled_context (s, &container->context);
8507
8508                 return append_mangled_signature (s, mono_method_signature (method));
8509         } else {
8510                 g_string_append_printf (s, "_");
8511                 append_mangled_klass (s, method->klass);
8512                 g_string_append_printf (s, "_%s_", method->name);
8513                 if (!append_mangled_signature (s, mono_method_signature (method))) {
8514                         g_string_free (s, TRUE);
8515                         return FALSE;
8516                 }
8517         }
8518
8519         return TRUE;
8520 }
8521
8522 /*
8523  * mono_aot_get_mangled_method_name:
8524  *
8525  *   Return a unique mangled name for METHOD, or NULL.
8526  */
8527 char*
8528 mono_aot_get_mangled_method_name (MonoMethod *method)
8529 {
8530         GString *s = g_string_new ("aot_");
8531         if (!append_mangled_method (s, method)) {
8532                 g_string_free (s, TRUE);
8533                 return NULL;
8534         } else {
8535                 char *out = g_string_free (s, FALSE);
8536                 // Scrub method and class names
8537                 char *cleaned = sanitize_mangled_string (out);
8538                 g_free (out);
8539                 return cleaned;
8540         }
8541 }
8542
8543 gboolean
8544 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8545 {
8546         return is_direct_callable (llvm_acfg, NULL, patch_info);
8547 }
8548
8549 void
8550 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8551 {
8552         MonoPltEntry *plt_entry;
8553
8554         plt_entry = get_plt_entry (llvm_acfg, patch_info);
8555         plt_entry->llvm_used = FALSE;
8556 }
8557
8558 char*
8559 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8560 {
8561         const char *sym = NULL;
8562
8563         if (llvm_acfg->aot_opts.direct_icalls) {
8564                 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8565                         /* Call to a C function implementing a jit icall */
8566                         sym = mono_lookup_jit_icall_symbol ((const char *)data);
8567                 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8568                         MonoMethod *method = (MonoMethod *)data;
8569                         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8570                                 sym = mono_lookup_icall_symbol (method);
8571                         else if (llvm_acfg->aot_opts.direct_pinvoke)
8572                                 sym = get_pinvoke_import (llvm_acfg, method);
8573                 }
8574                 if (sym)
8575                         return g_strdup (sym);
8576         }
8577         return NULL;
8578 }
8579
8580 char*
8581 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8582 {
8583         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8584         MonoPltEntry *plt_entry;
8585         const char *sym = NULL;
8586
8587         ji->type = type;
8588         ji->data.target = data;
8589
8590         if (!can_encode_patch (llvm_acfg, ji))
8591                 return NULL;
8592
8593         if (llvm_acfg->aot_opts.direct_icalls) {
8594                 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8595                         /* Call to a C function implementing a jit icall */
8596                         sym = mono_lookup_jit_icall_symbol ((const char *)data);
8597                 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8598                         MonoMethod *method = (MonoMethod *)data;
8599                         if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8600                                 sym = mono_lookup_icall_symbol (method);
8601                 }
8602                 if (sym)
8603                         return g_strdup (sym);
8604         }
8605
8606         plt_entry = get_plt_entry (llvm_acfg, ji);
8607         plt_entry->llvm_used = TRUE;
8608
8609 #if defined(TARGET_MACH)
8610         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8611 #else
8612         return g_strdup_printf (plt_entry->llvm_symbol);
8613 #endif
8614 }
8615
8616 int
8617 mono_aot_get_method_index (MonoMethod *method)
8618 {
8619         g_assert (llvm_acfg);
8620         return get_method_index (llvm_acfg, method);
8621 }
8622
8623 MonoJumpInfo*
8624 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8625 {
8626         MonoJumpInfo *res;
8627
8628         mono_acfg_lock (llvm_acfg);
8629         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8630         mono_acfg_unlock (llvm_acfg);
8631
8632         return res;
8633 }
8634
8635 static int
8636 execute_system (const char * command)
8637 {
8638         int status = 0;
8639
8640 #if defined(HOST_WIN32) && defined(HAVE_SYSTEM)
8641         // We need an extra set of quotes around the whole command to properly handle commands 
8642         // with spaces since internally the command is called through "cmd /c.
8643         char * quoted_command = g_strdup_printf ("\"%s\"", command);
8644
8645         int size =  MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8646         wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8647         MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8648         status = _wsystem (wstr);
8649         g_free (wstr);
8650
8651         g_free (quoted_command);
8652 #elif defined (HAVE_SYSTEM)
8653         status = system (command);
8654 #else
8655         g_assert_not_reached ();
8656 #endif
8657
8658         return status;
8659 }
8660
8661 #ifdef ENABLE_LLVM
8662
8663 /*
8664  * emit_llvm_file:
8665  *
8666  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8667  * tools.
8668  */
8669 static gboolean
8670 emit_llvm_file (MonoAotCompile *acfg)
8671 {
8672         char *command, *opts, *tempbc, *optbc, *output_fname;
8673
8674         if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8675                 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8676                 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8677         } else {
8678                 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8679                 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8680         }
8681
8682         mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8683
8684         /*
8685          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8686          * a lot of time, and doesn't seem to save much space.
8687          * The following optimizations cannot be enabled:
8688          * - 'tailcallelim'
8689          * - 'jump-threading' changes our blockaddress references to int constants.
8690          * - 'basiccg' fails because it contains:
8691          * if (CS && !isa<IntrinsicInst>(II)) {
8692          * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8693          * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8694          * The opt list below was produced by taking the output of:
8695          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8696          * then removing tailcallelim + the global opts.
8697          * strip-dead-prototypes deletes unused intrinsics definitions.
8698          */
8699         /* The dse pass is disabled because of #13734 and #17616 */
8700         /*
8701          * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8702          * // If we have no DataLayout information around, then the size of the store
8703          *  // is inferrable from the pointee type.  If they are the same type, then
8704          * // we know that the store is safe.
8705          * if (AA.getDataLayout() == 0 &&
8706          * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8707          * return OverwriteComplete;
8708          * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8709          */
8710         if (acfg->aot_opts.llvm_only)
8711                 // FIXME: This doesn't work yet
8712                 opts = g_strdup ("");
8713         else
8714 #if LLVM_API_VERSION > 100
8715                 opts = g_strdup ("-O2 -disable-tail-calls");
8716 #else
8717                 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");
8718 #endif
8719         command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8720         aot_printf (acfg, "Executing opt: %s\n", command);
8721         if (execute_system (command) != 0)
8722                 return FALSE;
8723         g_free (opts);
8724
8725         if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8726                 /* Nothing else to do */
8727                 return TRUE;
8728
8729         if (acfg->aot_opts.llvm_only) {
8730                 /* Use the stock clang from xcode */
8731                 // FIXME: arch
8732                 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);
8733
8734                 aot_printf (acfg, "Executing clang: %s\n", command);
8735                 if (execute_system (command) != 0)
8736                         return FALSE;
8737                 return TRUE;
8738         }
8739
8740         if (!acfg->llc_args)
8741                 acfg->llc_args = g_string_new ("");
8742
8743         /* Verbose asm slows down llc greatly */
8744         g_string_append (acfg->llc_args, " -asm-verbose=false");
8745
8746         if (acfg->aot_opts.mtriple)
8747                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8748
8749         g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8750
8751         g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8752
8753 #if LLVM_API_VERSION > 100
8754         g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8755 #endif
8756
8757 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
8758         /* ios requires PIC code now */
8759         g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8760 #else
8761         if (llvm_acfg->aot_opts.static_link)
8762                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8763         else
8764                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8765 #endif
8766
8767         if (acfg->llvm_owriter) {
8768                 /* Emit an object file directly */
8769                 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8770                 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8771         } else {
8772                 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8773         }
8774         command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8775         g_free (output_fname);
8776
8777         aot_printf (acfg, "Executing llc: %s\n", command);
8778
8779         if (execute_system (command) != 0)
8780                 return FALSE;
8781         return TRUE;
8782 }
8783 #endif
8784
8785 static void
8786 emit_code (MonoAotCompile *acfg)
8787 {
8788         int oindex, i, prev_index;
8789         gboolean saved_unbox_info = FALSE;
8790         char symbol [MAX_SYMBOL_SIZE];
8791
8792         if (acfg->aot_opts.llvm_only)
8793                 return;
8794
8795 #if defined(TARGET_POWERPC64)
8796         sprintf (symbol, ".Lgot_addr");
8797         emit_section_change (acfg, ".text", 0);
8798         emit_alignment (acfg, 8);
8799         emit_label (acfg, symbol);
8800         emit_pointer (acfg, acfg->got_symbol);
8801 #endif
8802
8803         /* 
8804          * This global symbol is used to compute the address of each method using the
8805          * code_offsets array. It is also used to compute the memory ranges occupied by
8806          * AOT code, so it must be equal to the address of the first emitted method.
8807          */
8808         emit_section_change (acfg, ".text", 0);
8809         emit_alignment_code (acfg, 8);
8810         emit_info_symbol (acfg, "jit_code_start");
8811
8812         /* 
8813          * Emit some padding so the local symbol for the first method doesn't have the
8814          * same address as 'methods'.
8815          */
8816         emit_padding (acfg, 16);
8817
8818         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8819                 MonoCompile *cfg;
8820                 MonoMethod *method;
8821
8822                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8823
8824                 cfg = acfg->cfgs [i];
8825
8826                 if (!cfg)
8827                         continue;
8828
8829                 method = cfg->orig_method;
8830
8831                 /* Emit unbox trampoline */
8832                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8833                         sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8834
8835                         emit_section_change (acfg, ".text", 0);
8836
8837                         if (acfg->thumb_mixed && cfg->compile_llvm) {
8838                                 emit_set_thumb_mode (acfg);
8839                                 fprintf (acfg->fp, "\n.thumb_func\n");
8840                         }
8841
8842                         emit_label (acfg, symbol);
8843
8844                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8845
8846                         if (acfg->thumb_mixed && cfg->compile_llvm)
8847                                 emit_set_arm_mode (acfg);
8848
8849                         if (!saved_unbox_info) {
8850                                 char user_symbol [128];
8851                                 GSList *unwind_ops;
8852                                 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8853
8854                                 emit_label (acfg, "ut_end");
8855
8856                                 unwind_ops = mono_unwind_get_cie_program ();
8857                                 save_unwind_info (acfg, user_symbol, unwind_ops);
8858                                 mono_free_unwind_info (unwind_ops);
8859
8860                                 /* Save the unbox trampoline size */
8861                                 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8862
8863                                 saved_unbox_info = TRUE;
8864                         }
8865                 }
8866
8867                 if (cfg->compile_llvm)
8868                         acfg->stats.llvm_count ++;
8869                 else
8870                         emit_method_code (acfg, cfg);
8871         }
8872
8873         emit_section_change (acfg, ".text", 0);
8874         emit_alignment_code (acfg, 8);
8875         emit_info_symbol (acfg, "jit_code_end");
8876
8877         /* To distinguish it from the next symbol */
8878         emit_padding (acfg, 4);
8879
8880         /* 
8881          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8882          * from optimizing them away, since it doesn't see that code_offsets references them.
8883          * JITted methods don't need this since they are referenced using assembler local
8884          * symbols.
8885          * FIXME: This is why write-symbols doesn't work on OSX ?
8886          */
8887         if (acfg->llvm && acfg->need_no_dead_strip) {
8888                 fprintf (acfg->fp, "\n");
8889                 for (i = 0; i < acfg->nmethods; ++i) {
8890                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8891                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8892                 }
8893         }
8894
8895         /*
8896          * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8897          * This is PIE code, and the linker can update it if needed.
8898          */
8899         
8900         sprintf (symbol, "method_addresses");
8901         emit_section_change (acfg, ".text", 1);
8902         emit_alignment_code (acfg, 8);
8903         emit_info_symbol (acfg, symbol);
8904         if (acfg->aot_opts.write_symbols)
8905                 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8906         emit_unset_mode (acfg);
8907         if (acfg->need_no_dead_strip)
8908                 fprintf (acfg->fp, "    .no_dead_strip %s\n", symbol);
8909
8910         for (i = 0; i < acfg->nmethods; ++i) {
8911 #ifdef MONO_ARCH_AOT_SUPPORTED
8912                 int call_size;
8913
8914                 if (acfg->cfgs [i]) {
8915                         arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8916                 } else {
8917                         arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8918                 }
8919 #endif
8920         }
8921
8922         sprintf (symbol, "method_addresses_end");
8923         emit_label (acfg, symbol);
8924         emit_line (acfg);
8925
8926         /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8927         sprintf (symbol, "unbox_trampolines");
8928         emit_section_change (acfg, RODATA_SECT, 0);
8929         emit_alignment (acfg, 8);
8930         emit_info_symbol (acfg, symbol);
8931
8932         prev_index = -1;
8933         for (i = 0; i < acfg->nmethods; ++i) {
8934                 MonoCompile *cfg;
8935                 MonoMethod *method;
8936                 int index;
8937
8938                 cfg = acfg->cfgs [i];
8939                 if (!cfg)
8940                         continue;
8941
8942                 method = cfg->orig_method;
8943
8944                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8945                         index = get_method_index (acfg, method);
8946
8947                         emit_int32 (acfg, index);
8948                         /* Make sure the table is sorted by index */
8949                         g_assert (index > prev_index);
8950                         prev_index = index;
8951                 }
8952         }
8953         sprintf (symbol, "unbox_trampolines_end");
8954         emit_info_symbol (acfg, symbol);
8955         emit_int32 (acfg, 0);
8956
8957         /* Emit a separate table with the trampoline addresses/offsets */
8958         sprintf (symbol, "unbox_trampoline_addresses");
8959         emit_section_change (acfg, ".text", 0);
8960         emit_alignment_code (acfg, 8);
8961         emit_info_symbol (acfg, symbol);
8962
8963         for (i = 0; i < acfg->nmethods; ++i) {
8964                 MonoCompile *cfg;
8965                 MonoMethod *method;
8966                 int index;
8967
8968                 cfg = acfg->cfgs [i];
8969                 if (!cfg)
8970                         continue;
8971
8972                 method = cfg->orig_method;
8973
8974                 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8975 #ifdef MONO_ARCH_AOT_SUPPORTED
8976                         int call_size;
8977
8978                         index = get_method_index (acfg, method);
8979                         sprintf (symbol, "ut_%d", index);
8980
8981                         arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8982 #endif
8983                 }
8984         }
8985         emit_int32 (acfg, 0);
8986 }
8987
8988 static void
8989 emit_info (MonoAotCompile *acfg)
8990 {
8991         int oindex, i;
8992         gint32 *offsets;
8993
8994         offsets = g_new0 (gint32, acfg->nmethods);
8995
8996         for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8997                 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8998
8999                 if (acfg->cfgs [i]) {
9000                         emit_method_info (acfg, acfg->cfgs [i]);
9001                         offsets [i] = acfg->cfgs [i]->method_info_offset;
9002                 } else {
9003                         offsets [i] = 0;
9004                 }
9005         }
9006
9007         acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9008
9009         g_free (offsets);
9010 }
9011
9012 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9013
9014 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9015 #define mix(a,b,c) { \
9016         a -= c;  a ^= rot(c, 4);  c += b; \
9017         b -= a;  b ^= rot(a, 6);  a += c; \
9018         c -= b;  c ^= rot(b, 8);  b += a; \
9019         a -= c;  a ^= rot(c,16);  c += b; \
9020         b -= a;  b ^= rot(a,19);  a += c; \
9021         c -= b;  c ^= rot(b, 4);  b += a; \
9022 }
9023 #define final(a,b,c) { \
9024         c ^= b; c -= rot(b,14); \
9025         a ^= c; a -= rot(c,11); \
9026         b ^= a; b -= rot(a,25); \
9027         c ^= b; c -= rot(b,16); \
9028         a ^= c; a -= rot(c,4);  \
9029         b ^= a; b -= rot(a,14); \
9030         c ^= b; c -= rot(b,24); \
9031 }
9032
9033 static guint
9034 mono_aot_type_hash (MonoType *t1)
9035 {
9036         guint hash = t1->type;
9037
9038         hash |= t1->byref << 6; /* do not collide with t1->type values */
9039         switch (t1->type) {
9040         case MONO_TYPE_VALUETYPE:
9041         case MONO_TYPE_CLASS:
9042         case MONO_TYPE_SZARRAY:
9043                 /* check if the distribution is good enough */
9044                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9045         case MONO_TYPE_PTR:
9046                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9047         case MONO_TYPE_ARRAY:
9048                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9049         case MONO_TYPE_GENERICINST:
9050                 return ((hash << 5) - hash) ^ 0;
9051         default:
9052                 return hash;
9053         }
9054 }
9055
9056 /*
9057  * mono_aot_method_hash:
9058  *
9059  *   Return a hash code for methods which only depends on metadata.
9060  */
9061 guint32
9062 mono_aot_method_hash (MonoMethod *method)
9063 {
9064         MonoMethodSignature *sig;
9065         MonoClass *klass;
9066         int i, hindex;
9067         int hashes_count;
9068         guint32 *hashes_start, *hashes;
9069         guint32 a, b, c;
9070         MonoGenericInst *class_ginst = NULL;
9071         MonoGenericInst *ginst = NULL;
9072
9073         /* Similar to the hash in mono_method_get_imt_slot () */
9074
9075         sig = mono_method_signature (method);
9076
9077         if (mono_class_is_ginst (method->klass))
9078                 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9079         if (method->is_inflated)
9080                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9081
9082         hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9083         hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9084         hashes = hashes_start;
9085
9086         /* Some wrappers are assigned to random classes */
9087         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9088                 klass = method->klass;
9089         else
9090                 klass = mono_defaults.object_class;
9091
9092         if (!method->wrapper_type) {
9093                 char *full_name;
9094
9095                 if (mono_class_is_ginst (klass))
9096                         full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9097                 else
9098                         full_name = mono_type_full_name (&klass->byval_arg);
9099
9100                 hashes [0] = mono_metadata_str_hash (full_name);
9101                 hashes [1] = 0;
9102                 g_free (full_name);
9103         } else {
9104                 hashes [0] = mono_metadata_str_hash (klass->name);
9105                 hashes [1] = mono_metadata_str_hash (klass->name_space);
9106         }
9107         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9108                 /* The method name includes a stringified pointer */
9109                 hashes [2] = 0;
9110         else
9111                 hashes [2] = mono_metadata_str_hash (method->name);
9112         hashes [3] = method->wrapper_type;
9113         hashes [4] = mono_aot_type_hash (sig->ret);
9114         hindex = 5;
9115         for (i = 0; i < sig->param_count; i++) {
9116                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9117         }
9118         if (class_ginst) {
9119                 for (i = 0; i < class_ginst->type_argc; ++i)
9120                         hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9121         }
9122         if (ginst) {
9123                 for (i = 0; i < ginst->type_argc; ++i)
9124                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9125         }               
9126         g_assert (hindex == hashes_count);
9127
9128         /* Setup internal state */
9129         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9130
9131         /* Handle most of the hashes */
9132         while (hashes_count > 3) {
9133                 a += hashes [0];
9134                 b += hashes [1];
9135                 c += hashes [2];
9136                 mix (a,b,c);
9137                 hashes_count -= 3;
9138                 hashes += 3;
9139         }
9140
9141         /* Handle the last 3 hashes (all the case statements fall through) */
9142         switch (hashes_count) { 
9143         case 3 : c += hashes [2];
9144         case 2 : b += hashes [1];
9145         case 1 : a += hashes [0];
9146                 final (a,b,c);
9147         case 0: /* nothing left to add */
9148                 break;
9149         }
9150         
9151         g_free (hashes_start);
9152         
9153         return c;
9154 }
9155 #undef rot
9156 #undef mix
9157 #undef final
9158
9159 /*
9160  * mono_aot_get_array_helper_from_wrapper;
9161  *
9162  * Get the helper method in Array called by an array wrapper method.
9163  */
9164 MonoMethod*
9165 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9166 {
9167         MonoMethod *m;
9168         const char *prefix;
9169         MonoGenericContext ctx;
9170         MonoType *args [16];
9171         char *mname, *iname, *s, *s2, *helper_name = NULL;
9172
9173         prefix = "System.Collections.Generic";
9174         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9175         s2 = strstr (s, "`1.");
9176         g_assert (s2);
9177         s2 [0] = '\0';
9178         iname = s;
9179         mname = s2 + 3;
9180
9181         //printf ("X: %s %s\n", iname, mname);
9182
9183         if (!strcmp (iname, "IList"))
9184                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9185         else
9186                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9187         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9188         g_assert (m);
9189         g_free (helper_name);
9190         g_free (s);
9191
9192         if (m->is_generic) {
9193                 MonoError error;
9194                 memset (&ctx, 0, sizeof (ctx));
9195                 args [0] = &method->klass->element_class->byval_arg;
9196                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9197                 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
9198                 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9199         }
9200
9201         return m;
9202 }
9203
9204 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9205
9206 typedef struct HashEntry {
9207     guint32 key, value, index;
9208         struct HashEntry *next;
9209 } HashEntry;
9210
9211 /*
9212  * emit_extra_methods:
9213  *
9214  * Emit methods which are not in the METHOD table, like wrappers.
9215  */
9216 static void
9217 emit_extra_methods (MonoAotCompile *acfg)
9218 {
9219         int i, table_size, buf_size;
9220         guint8 *p, *buf;
9221         guint32 *info_offsets;
9222         guint32 hash;
9223         GPtrArray *table;
9224         HashEntry *entry, *new_entry;
9225         int nmethods, max_chain_length;
9226         int *chain_lengths;
9227
9228         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9229
9230         /* Emit method info */
9231         nmethods = 0;
9232         for (i = 0; i < acfg->extra_methods->len; ++i) {
9233                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9234                 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9235
9236                 if (!cfg)
9237                         continue;
9238
9239                 buf_size = 10240;
9240                 p = buf = (guint8 *)g_malloc (buf_size);
9241
9242                 nmethods ++;
9243
9244                 method = cfg->method_to_register;
9245
9246                 encode_method_ref (acfg, method, p, &p);
9247
9248                 g_assert ((p - buf) < buf_size);
9249
9250                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9251                 g_free (buf);
9252         }
9253
9254         /*
9255          * Construct a chained hash table for mapping indexes in extra_method_info to
9256          * method indexes.
9257          */
9258         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9259         table = g_ptr_array_sized_new (table_size);
9260         for (i = 0; i < table_size; ++i)
9261                 g_ptr_array_add (table, NULL);
9262         chain_lengths = g_new0 (int, table_size);
9263         max_chain_length = 0;
9264         for (i = 0; i < acfg->extra_methods->len; ++i) {
9265                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9266                 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9267                 guint32 key, value;
9268
9269                 if (!cfg)
9270                         continue;
9271
9272                 key = info_offsets [i];
9273                 value = get_method_index (acfg, method);
9274
9275                 hash = mono_aot_method_hash (method) % table_size;
9276                 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9277
9278                 chain_lengths [hash] ++;
9279                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9280
9281                 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9282                 new_entry->key = key;
9283                 new_entry->value = value;
9284
9285                 entry = (HashEntry *)g_ptr_array_index (table, hash);
9286                 if (entry == NULL) {
9287                         new_entry->index = hash;
9288                         g_ptr_array_index (table, hash) = new_entry;
9289                 } else {
9290                         while (entry->next)
9291                                 entry = entry->next;
9292                         
9293                         entry->next = new_entry;
9294                         new_entry->index = table->len;
9295                         g_ptr_array_add (table, new_entry);
9296                 }
9297         }
9298         g_free (chain_lengths);
9299
9300         //printf ("MAX: %d\n", max_chain_length);
9301
9302         buf_size = table->len * 12 + 4;
9303         p = buf = (guint8 *)g_malloc (buf_size);
9304         encode_int (table_size, p, &p);
9305
9306         for (i = 0; i < table->len; ++i) {
9307                 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9308
9309                 if (entry == NULL) {
9310                         encode_int (0, p, &p);
9311                         encode_int (0, p, &p);
9312                         encode_int (0, p, &p);
9313                 } else {
9314                         //g_assert (entry->key > 0);
9315                         encode_int (entry->key, p, &p);
9316                         encode_int (entry->value, p, &p);
9317                         if (entry->next)
9318                                 encode_int (entry->next->index, p, &p);
9319                         else
9320                                 encode_int (0, p, &p);
9321                 }
9322         }
9323         g_assert (p - buf <= buf_size);
9324
9325         /* Emit the table */
9326         emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9327
9328         g_free (buf);
9329
9330         /* 
9331          * Emit a table reverse mapping method indexes to their index in extra_method_info.
9332          * This is used by mono_aot_find_jit_info ().
9333          */
9334         buf_size = acfg->extra_methods->len * 8 + 4;
9335         p = buf = (guint8 *)g_malloc (buf_size);
9336         encode_int (acfg->extra_methods->len, p, &p);
9337         for (i = 0; i < acfg->extra_methods->len; ++i) {
9338                 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9339
9340                 encode_int (get_method_index (acfg, method), p, &p);
9341                 encode_int (info_offsets [i], p, &p);
9342         }
9343         emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9344
9345         g_free (buf);
9346         g_free (info_offsets);
9347         g_ptr_array_free (table, TRUE);
9348 }       
9349
9350 static void
9351 generate_aotid (guint8* aotid)
9352 {
9353         gpointer rand_handle;
9354         MonoError error;
9355
9356         mono_rand_open ();
9357         rand_handle = mono_rand_init (NULL, 0);
9358
9359         mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
9360         mono_error_assert_ok (&error);
9361
9362         mono_rand_close (rand_handle);
9363 }
9364
9365 static void
9366 emit_exception_info (MonoAotCompile *acfg)
9367 {
9368         int i;
9369         gint32 *offsets;
9370         SeqPointData sp_data;
9371         gboolean seq_points_to_file = FALSE;
9372
9373         offsets = g_new0 (gint32, acfg->nmethods);
9374         for (i = 0; i < acfg->nmethods; ++i) {
9375                 if (acfg->cfgs [i]) {
9376                         MonoCompile *cfg = acfg->cfgs [i];
9377
9378                         // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9379                         // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9380                         gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9381                                 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9382                         gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9383                         
9384                         emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9385                         offsets [i] = cfg->ex_info_offset;
9386
9387                         if (method_seq_points_to_file) {
9388                                 if (!seq_points_to_file) {
9389                                         mono_seq_point_data_init (&sp_data, acfg->nmethods);
9390                                         seq_points_to_file = TRUE;
9391                                 }
9392                                 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9393                         }
9394                 } else {
9395                         offsets [i] = 0;
9396                 }
9397         }
9398
9399         if (seq_points_to_file) {
9400                 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9401                 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9402                 char *image_basename = g_path_get_basename (acfg->image->name);
9403                 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9404                 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9405
9406                 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9407                         fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9408                         exit (1);
9409                 }
9410
9411                 mono_seq_point_data_write (&sp_data, aot_file_path);
9412                 mono_seq_point_data_free (&sp_data);
9413
9414                 g_free (aotid);
9415                 g_free (dir);
9416                 g_free (image_basename);
9417                 g_free (aot_file);
9418                 g_free (aot_file_path);
9419         }
9420
9421         acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9422         g_free (offsets);
9423 }
9424
9425 static void
9426 emit_unwind_info (MonoAotCompile *acfg)
9427 {
9428         int i;
9429         char symbol [128];
9430
9431         if (acfg->aot_opts.llvm_only) {
9432                 g_assert (acfg->unwind_ops->len == 0);
9433                 return;
9434         }
9435
9436         /* 
9437          * The unwind info contains a lot of duplicates so we emit each unique
9438          * entry once, and only store the offset from the start of the table in the
9439          * exception info.
9440          */
9441
9442         sprintf (symbol, "unwind_info");
9443         emit_section_change (acfg, RODATA_SECT, 1);
9444         emit_alignment (acfg, 8);
9445         emit_info_symbol (acfg, symbol);
9446
9447         for (i = 0; i < acfg->unwind_ops->len; ++i) {
9448                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9449                 guint8 *unwind_info;
9450                 guint32 unwind_info_len;
9451                 guint8 buf [16];
9452                 guint8 *p;
9453
9454                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9455
9456                 p = buf;
9457                 encode_value (unwind_info_len, p, &p);
9458                 emit_bytes (acfg, buf, p - buf);
9459                 emit_bytes (acfg, unwind_info, unwind_info_len);
9460
9461                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9462         }
9463 }
9464
9465 static void
9466 emit_class_info (MonoAotCompile *acfg)
9467 {
9468         int i;
9469         gint32 *offsets;
9470
9471         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9472         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9473                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9474
9475         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);
9476         g_free (offsets);
9477 }
9478
9479 typedef struct ClassNameTableEntry {
9480         guint32 token, index;
9481         struct ClassNameTableEntry *next;
9482 } ClassNameTableEntry;
9483
9484 static void
9485 emit_class_name_table (MonoAotCompile *acfg)
9486 {
9487         int i, table_size, buf_size;
9488         guint32 token, hash;
9489         MonoClass *klass;
9490         GPtrArray *table;
9491         char *full_name;
9492         guint8 *buf, *p;
9493         ClassNameTableEntry *entry, *new_entry;
9494
9495         /*
9496          * Construct a chained hash table for mapping class names to typedef tokens.
9497          */
9498         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9499         table = g_ptr_array_sized_new (table_size);
9500         for (i = 0; i < table_size; ++i)
9501                 g_ptr_array_add (table, NULL);
9502         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9503                 MonoError error;
9504                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9505                 klass = mono_class_get_checked (acfg->image, token, &error);
9506                 if (!klass) {
9507                         mono_error_cleanup (&error);
9508                         continue;
9509                 }
9510                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9511                 hash = mono_metadata_str_hash (full_name) % table_size;
9512                 g_free (full_name);
9513
9514                 /* FIXME: Allocate from the mempool */
9515                 new_entry = g_new0 (ClassNameTableEntry, 1);
9516                 new_entry->token = token;
9517
9518                 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9519                 if (entry == NULL) {
9520                         new_entry->index = hash;
9521                         g_ptr_array_index (table, hash) = new_entry;
9522                 } else {
9523                         while (entry->next)
9524                                 entry = entry->next;
9525                         
9526                         entry->next = new_entry;
9527                         new_entry->index = table->len;
9528                         g_ptr_array_add (table, new_entry);
9529                 }
9530         }
9531
9532         /* Emit the table */
9533         buf_size = table->len * 4 + 4;
9534         p = buf = (guint8 *)g_malloc0 (buf_size);
9535
9536         /* FIXME: Optimize memory usage */
9537         g_assert (table_size < 65000);
9538         encode_int16 (table_size, p, &p);
9539         g_assert (table->len < 65000);
9540         for (i = 0; i < table->len; ++i) {
9541                 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9542
9543                 if (entry == NULL) {
9544                         encode_int16 (0, p, &p);
9545                         encode_int16 (0, p, &p);
9546                 } else {
9547                         encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9548                         if (entry->next)
9549                                 encode_int16 (entry->next->index, p, &p);
9550                         else
9551                                 encode_int16 (0, p, &p);
9552                 }
9553                 g_free (entry);
9554         }
9555         g_assert (p - buf <= buf_size);
9556         g_ptr_array_free (table, TRUE);
9557
9558         emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9559
9560         g_free (buf);
9561 }
9562
9563 static void
9564 emit_image_table (MonoAotCompile *acfg)
9565 {
9566         int i, buf_size;
9567         guint8 *buf, *p;
9568
9569         /*
9570          * The image table is small but referenced in a lot of places.
9571          * So we emit it at once, and reference its elements by an index.
9572          */
9573         buf_size = acfg->image_table->len * 28 + 4;
9574         for (i = 0; i < acfg->image_table->len; i++) {
9575                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9576                 MonoAssemblyName *aname = &image->assembly->aname;
9577
9578                 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9579         }
9580
9581         buf = p = (guint8 *)g_malloc0 (buf_size);
9582         encode_int (acfg->image_table->len, p, &p);
9583         for (i = 0; i < acfg->image_table->len; i++) {
9584                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9585                 MonoAssemblyName *aname = &image->assembly->aname;
9586
9587                 /* FIXME: Support multi-module assemblies */
9588                 g_assert (image->assembly->image == image);
9589
9590                 encode_string (image->assembly_name, p, &p);
9591                 encode_string (image->guid, p, &p);
9592                 encode_string (aname->culture ? aname->culture : "", p, &p);
9593                 encode_string ((const char*)aname->public_key_token, p, &p);
9594
9595                 while (GPOINTER_TO_UINT (p) % 8 != 0)
9596                         p ++;
9597
9598                 encode_int (aname->flags, p, &p);
9599                 encode_int (aname->major, p, &p);
9600                 encode_int (aname->minor, p, &p);
9601                 encode_int (aname->build, p, &p);
9602                 encode_int (aname->revision, p, &p);
9603         }
9604         g_assert (p - buf <= buf_size);
9605
9606         emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9607
9608         g_free (buf);
9609 }
9610
9611 static void
9612 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9613 {
9614         int i, first_plt_got_patch = 0, buf_size;
9615         guint8 *p, *buf;
9616         guint32 *got_info_offsets;
9617         GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9618
9619         /* Add the patches needed by the PLT to the GOT */
9620         if (!llvm) {
9621                 acfg->plt_got_offset_base = acfg->got_offset;
9622                 first_plt_got_patch = info->got_patches->len;
9623                 for (i = 1; i < acfg->plt_offset; ++i) {
9624                         MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9625
9626                         g_ptr_array_add (info->got_patches, plt_entry->ji);
9627
9628                         acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9629                 }
9630
9631                 acfg->got_offset += acfg->plt_offset;
9632         }
9633
9634         /**
9635          * FIXME: 
9636          * - optimize offsets table.
9637          * - reduce number of exported symbols.
9638          * - emit info for a klass only once.
9639          * - determine when a method uses a GOT slot which is guaranteed to be already 
9640          *   initialized.
9641          * - clean up and document the code.
9642          * - use String.Empty in class libs.
9643          */
9644
9645         /* Encode info required to decode shared GOT entries */
9646         buf_size = info->got_patches->len * 128;
9647         p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9648         got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9649         if (!llvm) {
9650                 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9651                 /* Unused */
9652                 if (acfg->plt_offset)
9653                         acfg->plt_got_info_offsets [0] = 0;
9654         }
9655         for (i = 0; i < info->got_patches->len; ++i) {
9656                 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9657                 guint8 *p2;
9658
9659                 p = buf;
9660
9661                 encode_value (ji->type, p, &p);
9662                 p2 = p;
9663                 encode_patch (acfg, ji, p, &p);
9664                 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9665                 g_assert (p - buf <= buf_size);
9666                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9667
9668                 if (!llvm && i >= first_plt_got_patch)
9669                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9670                 acfg->stats.got_info_size += p - buf;
9671         }
9672
9673         /* Emit got_info_offsets table */
9674
9675         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9676         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);
9677 }
9678
9679 static void
9680 emit_got (MonoAotCompile *acfg)
9681 {
9682         char symbol [MAX_SYMBOL_SIZE];
9683
9684         if (acfg->aot_opts.llvm_only)
9685                 return;
9686
9687         /* Don't make GOT global so accesses to it don't need relocations */
9688         sprintf (symbol, "%s", acfg->got_symbol);
9689
9690 #ifdef TARGET_MACH
9691         emit_unset_mode (acfg);
9692         fprintf (acfg->fp, ".section __DATA, __bss\n");
9693         emit_alignment (acfg, 8);
9694         if (acfg->llvm)
9695                 emit_info_symbol (acfg, "jit_got");
9696         fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9697 #else
9698         emit_section_change (acfg, ".bss", 0);
9699         emit_alignment (acfg, 8);
9700         if (acfg->aot_opts.write_symbols)
9701                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9702         emit_label (acfg, symbol);
9703         if (acfg->llvm)
9704                 emit_info_symbol (acfg, "jit_got");
9705         if (acfg->got_offset > 0)
9706                 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9707 #endif
9708
9709         sprintf (symbol, "got_end");
9710         emit_label (acfg, symbol);
9711 }
9712
9713 typedef struct GlobalsTableEntry {
9714         guint32 value, index;
9715         struct GlobalsTableEntry *next;
9716 } GlobalsTableEntry;
9717
9718 #ifdef TARGET_WIN32_MSVC
9719 #define DLL_ENTRY_POINT "DllMain"
9720
9721 static void
9722 emit_library_info (MonoAotCompile *acfg)
9723 {
9724         // Only include for shared libraries linked directly from generated object.
9725         if (link_shared_library (acfg)) {
9726                 char    *name = NULL;
9727                 char    symbol [MAX_SYMBOL_SIZE];
9728
9729                 // Ask linker to export all global symbols.
9730                 emit_section_change (acfg, ".drectve", 0);
9731                 for (guint i = 0; i < acfg->globals->len; ++i) {
9732                         name = (char *)g_ptr_array_index (acfg->globals, i);
9733                         g_assert (name != NULL);
9734                         sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9735                         emit_string (acfg, symbol);
9736                 }
9737
9738                 // Emit DLLMain function, needed by MSVC linker for DLL's.
9739                 // NOTE, DllMain should not go into exports above.
9740                 emit_section_change (acfg, ".text", 0);
9741                 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9742                 emit_label (acfg, DLL_ENTRY_POINT);
9743
9744                 // Simple implementation of DLLMain, just returning TRUE.
9745                 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9746                 fprintf (acfg->fp, "movl $1, %%eax\n");
9747                 fprintf (acfg->fp, "ret\n");
9748
9749                 // Inform linker about our dll entry function.
9750                 emit_section_change (acfg, ".drectve", 0);
9751                 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9752                 return;
9753         }
9754 }
9755
9756 #else
9757
9758 static inline void
9759 emit_library_info (MonoAotCompile *acfg)
9760 {
9761         return;
9762 }
9763 #endif
9764
9765 static void
9766 emit_globals (MonoAotCompile *acfg)
9767 {
9768         int i, table_size;
9769         guint32 hash;
9770         GPtrArray *table;
9771         char symbol [1024];
9772         GlobalsTableEntry *entry, *new_entry;
9773
9774         if (!acfg->aot_opts.static_link)
9775                 return;
9776
9777         if (acfg->aot_opts.llvm_only) {
9778                 g_assert (acfg->globals->len == 0);
9779                 return;
9780         }
9781
9782         /* 
9783          * When static linking, we emit a table containing our globals.
9784          */
9785
9786         /*
9787          * Construct a chained hash table for mapping global names to their index in
9788          * the globals table.
9789          */
9790         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9791         table = g_ptr_array_sized_new (table_size);
9792         for (i = 0; i < table_size; ++i)
9793                 g_ptr_array_add (table, NULL);
9794         for (i = 0; i < acfg->globals->len; ++i) {
9795                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9796
9797                 hash = mono_metadata_str_hash (name) % table_size;
9798
9799                 /* FIXME: Allocate from the mempool */
9800                 new_entry = g_new0 (GlobalsTableEntry, 1);
9801                 new_entry->value = i;
9802
9803                 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9804                 if (entry == NULL) {
9805                         new_entry->index = hash;
9806                         g_ptr_array_index (table, hash) = new_entry;
9807                 } else {
9808                         while (entry->next)
9809                                 entry = entry->next;
9810                         
9811                         entry->next = new_entry;
9812                         new_entry->index = table->len;
9813                         g_ptr_array_add (table, new_entry);
9814                 }
9815         }
9816
9817         /* Emit the table */
9818         sprintf (symbol, ".Lglobals_hash");
9819         emit_section_change (acfg, RODATA_SECT, 0);
9820         emit_alignment (acfg, 8);
9821         emit_label (acfg, symbol);
9822
9823         /* FIXME: Optimize memory usage */
9824         g_assert (table_size < 65000);
9825         emit_int16 (acfg, table_size);
9826         for (i = 0; i < table->len; ++i) {
9827                 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9828
9829                 if (entry == NULL) {
9830                         emit_int16 (acfg, 0);
9831                         emit_int16 (acfg, 0);
9832                 } else {
9833                         emit_int16 (acfg, entry->value + 1);
9834                         if (entry->next)
9835                                 emit_int16 (acfg, entry->next->index);
9836                         else
9837                                 emit_int16 (acfg, 0);
9838                 }
9839         }
9840
9841         /* Emit the names */
9842         for (i = 0; i < acfg->globals->len; ++i) {
9843                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9844
9845                 sprintf (symbol, "name_%d", i);
9846                 emit_section_change (acfg, RODATA_SECT, 1);
9847 #ifdef TARGET_MACH
9848                 emit_alignment (acfg, 4);
9849 #endif
9850                 emit_label (acfg, symbol);
9851                 emit_string (acfg, name);
9852         }
9853
9854         /* Emit the globals table */
9855         sprintf (symbol, "globals");
9856         emit_section_change (acfg, ".data", 0);
9857         /* This is not a global, since it is accessed by the init function */
9858         emit_alignment (acfg, 8);
9859         emit_info_symbol (acfg, symbol);
9860
9861         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9862         emit_pointer (acfg, symbol);
9863
9864         for (i = 0; i < acfg->globals->len; ++i) {
9865                 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9866
9867                 sprintf (symbol, "name_%d", i);
9868                 emit_pointer (acfg, symbol);
9869
9870                 g_assert (strlen (name) < sizeof (symbol));
9871                 sprintf (symbol, "%s", name);
9872                 emit_pointer (acfg, symbol);
9873         }
9874         /* Null terminate the table */
9875         emit_int32 (acfg, 0);
9876         emit_int32 (acfg, 0);
9877 }
9878
9879 static void
9880 emit_mem_end (MonoAotCompile *acfg)
9881 {
9882         char symbol [128];
9883
9884         if (acfg->aot_opts.llvm_only)
9885                 return;
9886
9887         sprintf (symbol, "mem_end");
9888         emit_section_change (acfg, ".text", 1);
9889         emit_alignment_code (acfg, 8);
9890         emit_label (acfg, symbol);
9891 }
9892
9893 static void
9894 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9895 {
9896         int i;
9897
9898         info->version = MONO_AOT_FILE_VERSION;
9899         info->plt_got_offset_base = acfg->plt_got_offset_base;
9900         info->got_size = acfg->got_offset * sizeof (gpointer);
9901         info->plt_size = acfg->plt_offset;
9902         info->nmethods = acfg->nmethods;
9903         info->flags = acfg->flags;
9904         info->opts = acfg->opts;
9905         info->simd_opts = acfg->simd_opts;
9906         info->gc_name_index = acfg->gc_name_offset;
9907         info->datafile_size = acfg->datafile_offset;
9908         for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9909                 info->table_offsets [i] = acfg->table_offsets [i];
9910         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9911                 info->num_trampolines [i] = acfg->num_trampolines [i];
9912         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9913                 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9914         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9915                 info->trampoline_size [i] = acfg->trampoline_size [i];
9916         info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9917
9918         info->double_align = MONO_ABI_ALIGNOF (double);
9919         info->long_align = MONO_ABI_ALIGNOF (gint64);
9920         info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9921         info->tramp_page_size = acfg->tramp_page_size;
9922         info->nshared_got_entries = acfg->nshared_got_entries;
9923         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9924                 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9925
9926         memcpy(&info->aotid, acfg->image->aotid, 16);
9927 }
9928
9929 static void
9930 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9931 {
9932         char symbol [MAX_SYMBOL_SIZE];
9933         int i, sindex;
9934         const char **symbols;
9935
9936         symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9937         sindex = 0;
9938         symbols [sindex ++] = acfg->got_symbol;
9939         if (acfg->llvm) {
9940                 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9941                 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9942         } else {
9943                 symbols [sindex ++] = NULL;
9944                 symbols [sindex ++] = NULL;
9945         }
9946         /* llvm_get_method */
9947         symbols [sindex ++] = NULL;
9948         /* llvm_get_unbox_tramp */
9949         symbols [sindex ++] = NULL;
9950         if (!acfg->aot_opts.llvm_only) {
9951                 symbols [sindex ++] = "jit_code_start";
9952                 symbols [sindex ++] = "jit_code_end";
9953                 symbols [sindex ++] = "method_addresses";
9954         } else {
9955                 symbols [sindex ++] = NULL;
9956                 symbols [sindex ++] = NULL;
9957                 symbols [sindex ++] = NULL;
9958         }
9959         if (acfg->data_outfile) {
9960                 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9961                         symbols [sindex ++] = NULL;
9962         } else {
9963                 symbols [sindex ++] = "blob";
9964                 symbols [sindex ++] = "class_name_table";
9965                 symbols [sindex ++] = "class_info_offsets";
9966                 symbols [sindex ++] = "method_info_offsets";
9967                 symbols [sindex ++] = "ex_info_offsets";
9968                 symbols [sindex ++] = "extra_method_info_offsets";
9969                 symbols [sindex ++] = "extra_method_table";
9970                 symbols [sindex ++] = "got_info_offsets";
9971                 if (acfg->llvm)
9972                         symbols [sindex ++] = "llvm_got_info_offsets";
9973                 else
9974                         symbols [sindex ++] = NULL;
9975                 symbols [sindex ++] = "image_table";
9976         }
9977         symbols [sindex ++] = "mem_end";
9978         symbols [sindex ++] = "assembly_guid";
9979         symbols [sindex ++] = "runtime_version";
9980         if (acfg->num_trampoline_got_entries) {
9981                 symbols [sindex ++] = "specific_trampolines";
9982                 symbols [sindex ++] = "static_rgctx_trampolines";
9983                 symbols [sindex ++] = "imt_trampolines";
9984                 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9985         } else {
9986                 symbols [sindex ++] = NULL;
9987                 symbols [sindex ++] = NULL;
9988                 symbols [sindex ++] = NULL;
9989                 symbols [sindex ++] = NULL;
9990         }
9991         if (acfg->aot_opts.static_link) {
9992                 symbols [sindex ++] = "globals";
9993         } else {
9994                 symbols [sindex ++] = NULL;
9995         }
9996         symbols [sindex ++] = "assembly_name";
9997         symbols [sindex ++] = "plt";
9998         symbols [sindex ++] = "plt_end";
9999         symbols [sindex ++] = "unwind_info";
10000         if (!acfg->aot_opts.llvm_only) {
10001                 symbols [sindex ++] = "unbox_trampolines";
10002                 symbols [sindex ++] = "unbox_trampolines_end";
10003                 symbols [sindex ++] = "unbox_trampoline_addresses";
10004         } else {
10005                 symbols [sindex ++] = NULL;
10006                 symbols [sindex ++] = NULL;
10007                 symbols [sindex ++] = NULL;
10008         }
10009
10010         g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10011
10012         sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10013         emit_section_change (acfg, ".data", 0);
10014         emit_alignment (acfg, 8);
10015         emit_label (acfg, symbol);
10016         if (!acfg->aot_opts.static_link)
10017                 emit_global (acfg, symbol, FALSE);
10018
10019         /* The data emitted here must match MonoAotFileInfo. */
10020
10021         emit_int32 (acfg, info->version);
10022         emit_int32 (acfg, info->dummy);
10023
10024         /* 
10025          * We emit pointers to our data structures instead of emitting global symbols which
10026          * point to them, to reduce the number of globals, and because using globals leads to
10027          * various problems (i.e. arm/thumb).
10028          */
10029         for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10030                 emit_pointer (acfg, symbols [i]);
10031
10032         emit_int32 (acfg, info->plt_got_offset_base);
10033         emit_int32 (acfg, info->got_size);
10034         emit_int32 (acfg, info->plt_size);
10035         emit_int32 (acfg, info->nmethods);
10036         emit_int32 (acfg, info->flags);
10037         emit_int32 (acfg, info->opts);
10038         emit_int32 (acfg, info->simd_opts);
10039         emit_int32 (acfg, info->gc_name_index);
10040         emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10041         emit_int32 (acfg, info->double_align);
10042         emit_int32 (acfg, info->long_align);
10043         emit_int32 (acfg, info->generic_tramp_num);
10044         emit_int32 (acfg, info->tramp_page_size);
10045         emit_int32 (acfg, info->nshared_got_entries);
10046         emit_int32 (acfg, info->datafile_size);
10047
10048         for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10049                 emit_int32 (acfg, info->table_offsets [i]);
10050         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10051                 emit_int32 (acfg, info->num_trampolines [i]);
10052         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10053                 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10054         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10055                 emit_int32 (acfg, info->trampoline_size [i]);
10056         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10057                 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10058
10059         emit_bytes (acfg, info->aotid, 16);
10060
10061         if (acfg->aot_opts.static_link) {
10062                 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10063                 emit_alignment (acfg, sizeof (gpointer));
10064                 emit_label (acfg, acfg->static_linking_symbol);
10065                 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10066         }
10067 }
10068
10069 /*
10070  * Emit a structure containing all the information not stored elsewhere.
10071  */
10072 static void
10073 emit_file_info (MonoAotCompile *acfg)
10074 {
10075         char *build_info;
10076         MonoAotFileInfo *info;
10077
10078         if (acfg->aot_opts.bind_to_runtime_version) {
10079                 build_info = mono_get_runtime_build_info ();
10080                 emit_string_symbol (acfg, "runtime_version", build_info);
10081                 g_free (build_info);
10082         } else {
10083                 emit_string_symbol (acfg, "runtime_version", "");
10084         }
10085
10086         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10087
10088         /* Emit a string holding the assembly name */
10089         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10090
10091         info = g_new0 (MonoAotFileInfo, 1);
10092         init_aot_file_info (acfg, info);
10093
10094         if (acfg->aot_opts.static_link) {
10095                 char symbol [MAX_SYMBOL_SIZE];
10096                 char *p;
10097
10098                 /*
10099                  * Emit a global symbol which can be passed by an embedding app to
10100                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
10101                  * structure.
10102                  */
10103                 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10104
10105                 /* Get rid of characters which cannot occur in symbols */
10106                 p = symbol;
10107                 for (p = symbol; *p; ++p) {
10108                         if (!(isalnum (*p) || *p == '_'))
10109                                 *p = '_';
10110                 }
10111                 acfg->static_linking_symbol = g_strdup (symbol);
10112         }
10113
10114         if (acfg->llvm)
10115                 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10116         else
10117                 emit_aot_file_info (acfg, info);
10118 }
10119
10120 static void
10121 emit_blob (MonoAotCompile *acfg)
10122 {
10123         acfg->blob_closed = TRUE;
10124
10125         emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10126 }
10127
10128 static void
10129 emit_objc_selectors (MonoAotCompile *acfg)
10130 {
10131         int i;
10132         char symbol [128];
10133
10134         if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10135                 return;
10136
10137         /*
10138          * From
10139          * cat > foo.m << EOF
10140          * void *ret ()
10141          * {
10142          * return @selector(print:);
10143          * }
10144          * EOF
10145          */
10146
10147         mono_img_writer_emit_unset_mode (acfg->w);
10148         g_assert (acfg->fp);
10149         fprintf (acfg->fp, ".section    __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10150         fprintf (acfg->fp, ".align      3\n");
10151         for (i = 0; i < acfg->objc_selectors->len; ++i) {
10152                 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10153                 emit_label (acfg, symbol);
10154                 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10155                 emit_pointer (acfg, symbol);
10156
10157         }
10158         fprintf (acfg->fp, ".section    __TEXT,__cstring,cstring_literals\n");
10159         for (i = 0; i < acfg->objc_selectors->len; ++i) {
10160                 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10161                 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10162         }
10163
10164         fprintf (acfg->fp, ".section    __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10165         fprintf (acfg->fp, ".align      3\n");
10166         fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10167         fprintf (acfg->fp, ".long       0\n");
10168         fprintf (acfg->fp, ".long       16\n");
10169 }
10170
10171 static void
10172 emit_dwarf_info (MonoAotCompile *acfg)
10173 {
10174 #ifdef EMIT_DWARF_INFO
10175         int i;
10176         char symbol2 [128];
10177
10178         /* DIEs for methods */
10179         for (i = 0; i < acfg->nmethods; ++i) {
10180                 MonoCompile *cfg = acfg->cfgs [i];
10181
10182                 if (!cfg)
10183                         continue;
10184
10185                 // FIXME: LLVM doesn't define .Lme_...
10186                 if (cfg->compile_llvm)
10187                         continue;
10188
10189                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10190
10191                 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 ()));
10192         }
10193 #endif
10194 }
10195
10196 static gboolean
10197 collect_methods (MonoAotCompile *acfg)
10198 {
10199         int mindex, i;
10200         MonoImage *image = acfg->image;
10201
10202         /* Collect methods */
10203         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10204                 MonoError error;
10205                 MonoMethod *method;
10206                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10207
10208                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10209
10210                 if (!method) {
10211                         aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
10212                         aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10213                         mono_error_cleanup (&error);
10214                         return FALSE;
10215                 }
10216                         
10217                 /* Load all methods eagerly to skip the slower lazy loading code */
10218                 mono_class_setup_methods (method->klass);
10219
10220                 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10221                         /* Compile the wrapper instead */
10222                         /* We do this here instead of add_wrappers () because it is easy to do it here */
10223                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10224                         method = wrapper;
10225                 }
10226
10227                 /* FIXME: Some mscorlib methods don't have debug info */
10228                 /*
10229                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10230                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10231                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10232                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10233                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10234                                 if (!mono_debug_lookup_method (method)) {
10235                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10236                                         exit (1);
10237                                 }
10238                         }
10239                 }
10240                 */
10241
10242                 if (method->is_generic || mono_class_is_gtd (method->klass))
10243                         /* Compile the ref shared version instead */
10244                         method = mini_get_shared_method (method);
10245
10246                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10247                 add_method_with_index (acfg, method, i, FALSE);
10248                 acfg->method_index ++;
10249         }
10250
10251         /* gsharedvt methods */
10252         for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10253                 MonoError error;
10254                 MonoMethod *method;
10255                 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10256
10257                 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10258                         continue;
10259
10260                 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10261                 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
10262
10263                 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10264                         MonoMethod *gshared;
10265
10266                         gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10267                         add_extra_method (acfg, gshared);
10268                 }
10269         }
10270
10271         if (mono_aot_mode_is_full (&acfg->aot_opts))
10272                 add_generic_instances (acfg);
10273
10274         if (mono_aot_mode_is_full (&acfg->aot_opts))
10275                 add_wrappers (acfg);
10276         return TRUE;
10277 }
10278
10279 static void
10280 compile_methods (MonoAotCompile *acfg)
10281 {
10282         int i, methods_len;
10283
10284         if (acfg->aot_opts.nthreads > 0) {
10285                 GPtrArray *frag;
10286                 int len, j;
10287                 GPtrArray *threads;
10288                 MonoThreadHandle *thread_handle;
10289                 gpointer *user_data;
10290                 MonoMethod **methods;
10291
10292                 methods_len = acfg->methods->len;
10293
10294                 len = acfg->methods->len / acfg->aot_opts.nthreads;
10295                 g_assert (len > 0);
10296                 /* 
10297                  * Partition the list of methods into fragments, and hand it to threads to
10298                  * process.
10299                  */
10300                 threads = g_ptr_array_new ();
10301                 /* Make a copy since acfg->methods is modified by compile_method () */
10302                 methods = g_new0 (MonoMethod*, methods_len);
10303                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
10304                 for (i = 0; i < methods_len; ++i)
10305                         methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
10306                 i = 0;
10307                 while (i < methods_len) {
10308                         MonoError error;
10309                         MonoInternalThread *thread;
10310
10311                         frag = g_ptr_array_new ();
10312                         for (j = 0; j < len; ++j) {
10313                                 if (i < methods_len) {
10314                                         g_ptr_array_add (frag, methods [i]);
10315                                         i ++;
10316                                 }
10317                         }
10318
10319                         user_data = g_new0 (gpointer, 3);
10320                         user_data [0] = acfg;
10321                         user_data [1] = frag;
10322                         
10323                         thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
10324                         mono_error_assert_ok (&error);
10325
10326                         thread_handle = mono_threads_open_thread_handle (thread->handle);
10327                         g_ptr_array_add (threads, thread_handle);
10328                 }
10329                 g_free (methods);
10330
10331                 for (i = 0; i < threads->len; ++i) {
10332                         mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
10333                         mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
10334                 }
10335         } else {
10336                 methods_len = 0;
10337         }
10338
10339         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
10340         for (i = methods_len; i < acfg->methods->len; ++i) {
10341                 /* This can add new methods to acfg->methods */
10342                 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
10343         }
10344 }
10345
10346 static int
10347 compile_asm (MonoAotCompile *acfg)
10348 {
10349         char *command, *objfile;
10350         char *outfile_name, *tmp_outfile_name, *llvm_ofile;
10351         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
10352         char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
10353
10354 #ifdef TARGET_WIN32_MSVC
10355 #define AS_OPTIONS "-c -x assembler"
10356 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
10357 #define AS_OPTIONS "--64"
10358 #elif defined(TARGET_POWERPC64)
10359 #define AS_OPTIONS "-a64 -mppc64"
10360 #elif defined(sparc) && SIZEOF_VOID_P == 8
10361 #define AS_OPTIONS "-xarch=v9"
10362 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10363 #define AS_OPTIONS "-arch i386"
10364 #else
10365 #define AS_OPTIONS ""
10366 #endif
10367
10368 #ifdef __native_client_codegen__
10369 #if defined(TARGET_AMD64)
10370 #define AS_NAME "nacl64-as"
10371 #else
10372 #define AS_NAME "nacl-as"
10373 #endif
10374 #elif defined(TARGET_OSX)
10375 #define AS_NAME "clang"
10376 #elif defined(TARGET_WIN32_MSVC)
10377 #define AS_NAME "clang.exe"
10378 #else
10379 #define AS_NAME "as"
10380 #endif
10381
10382 #ifdef TARGET_WIN32_MSVC
10383 #define AS_OBJECT_FILE_SUFFIX "obj"
10384 #else
10385 #define AS_OBJECT_FILE_SUFFIX "o"
10386 #endif
10387
10388 #if defined(sparc)
10389 #define LD_NAME "ld"
10390 #define LD_OPTIONS "-shared -G"
10391 #elif defined(__ppc__) && defined(TARGET_MACH)
10392 #define LD_NAME "gcc"
10393 #define LD_OPTIONS "-dynamiclib"
10394 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10395 #define LD_NAME "clang"
10396 #define LD_OPTIONS "--shared"
10397 #elif defined(TARGET_WIN32_MSVC)
10398 #define LD_NAME "link.exe"
10399 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
10400 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10401 #define LD_NAME "gcc"
10402 #define LD_OPTIONS "-shared"
10403 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10404 #define LD_NAME "clang"
10405 #define LD_OPTIONS "-m32 -dynamiclib"
10406 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10407 #define LD_NAME "gcc"
10408 #define LD_OPTIONS "--shared"
10409 #elif defined(TARGET_POWERPC64)
10410 #define LD_OPTIONS "-m elf64ppc"
10411 #endif
10412
10413 #ifndef LD_OPTIONS
10414 #define LD_OPTIONS ""
10415 #endif
10416
10417         if (acfg->aot_opts.asm_only) {
10418                 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10419                 if (acfg->aot_opts.static_link)
10420                         aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10421                 if (acfg->llvm)
10422                         aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10423                 return 0;
10424         }
10425
10426         if (acfg->aot_opts.static_link) {
10427                 if (acfg->aot_opts.outfile)
10428                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10429                 else
10430                         objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
10431         } else {
10432                 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
10433         }
10434
10435 #ifdef TARGET_OSX
10436         g_string_append (acfg->as_args, "-c -x assembler");
10437 #endif
10438
10439         command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10440                         acfg->as_args ? acfg->as_args->str : "", 
10441                         wrap_path (objfile), wrap_path (acfg->tmpfname));
10442         aot_printf (acfg, "Executing the native assembler: %s\n", command);
10443         if (execute_system (command) != 0) {
10444                 g_free (command);
10445                 g_free (objfile);
10446                 return 1;
10447         }
10448
10449         if (acfg->llvm && !acfg->llvm_owriter) {
10450                 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10451                         acfg->as_args ? acfg->as_args->str : "",
10452                         wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10453                 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10454                 if (execute_system (command) != 0) {
10455                         g_free (command);
10456                         g_free (objfile);
10457                         return 1;
10458                 }
10459         }
10460
10461         g_free (command);
10462
10463         if (acfg->aot_opts.static_link) {
10464                 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10465                 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10466                 g_free (objfile);
10467                 return 0;
10468         }
10469
10470         if (acfg->aot_opts.outfile)
10471                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10472         else
10473                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10474
10475         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10476
10477         if (acfg->llvm) {
10478                 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10479         } else {
10480                 llvm_ofile = g_strdup ("");
10481         }
10482
10483         /* replace the ; flags separators with spaces */
10484         g_strdelimit (ld_flags, ";", ' ');
10485
10486         if (acfg->aot_opts.llvm_only)
10487                 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10488
10489 #ifdef TARGET_WIN32_MSVC
10490         g_assert (tmp_outfile_name != NULL);
10491         g_assert (objfile != NULL);
10492         command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10493                 ld_flags, tmp_outfile_name, objfile);
10494 #elif defined(LD_NAME)
10495         command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10496                 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10497                 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10498 #else
10499         // Default (linux)
10500         if (acfg->aot_opts.tool_prefix) {
10501                 /* Cross compiling */
10502                 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10503                                                                    wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10504                                                                    wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10505         } else {
10506                 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10507                                                                           wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10508                                                                           wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10509
10510                 if (acfg->aot_opts.llvm_only) {
10511                         command = g_strdup_printf ("clang++ %s", args);
10512                 } else {
10513                         command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10514                 }
10515                 g_free (args);
10516         }
10517 #endif
10518         aot_printf (acfg, "Executing the native linker: %s\n", command);
10519         if (execute_system (command) != 0) {
10520                 g_free (tmp_outfile_name);
10521                 g_free (outfile_name);
10522                 g_free (command);
10523                 g_free (objfile);
10524                 g_free (ld_flags);
10525                 return 1;
10526         }
10527
10528         g_free (command);
10529
10530         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10531         printf ("Stripping the binary: %s\n", com);
10532         execute_system (com);
10533         g_free (com);*/
10534
10535 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10536         /* 
10537          * gas generates 'mapping symbols' each time code and data is mixed, which 
10538          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10539          */
10540         command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10541         aot_printf (acfg, "Stripping the binary: %s\n", command);
10542         if (execute_system (command) != 0) {
10543                 g_free (tmp_outfile_name);
10544                 g_free (outfile_name);
10545                 g_free (command);
10546                 g_free (objfile);
10547                 return 1;
10548         }
10549 #endif
10550
10551         if (0 != rename (tmp_outfile_name, outfile_name)) {
10552                 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10553                         /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10554                         unlink (outfile_name);
10555                         rename (tmp_outfile_name, outfile_name);
10556                 }
10557         }
10558
10559 #if defined(TARGET_MACH)
10560         command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10561         aot_printf (acfg, "Executing dsymutil: %s\n", command);
10562         if (execute_system (command) != 0) {
10563                 return 1;
10564         }
10565 #endif
10566
10567         if (!acfg->aot_opts.save_temps)
10568                 unlink (objfile);
10569
10570         g_free (tmp_outfile_name);
10571         g_free (outfile_name);
10572         g_free (objfile);
10573
10574         if (acfg->aot_opts.save_temps)
10575                 aot_printf (acfg, "Retained input file.\n");
10576         else
10577                 unlink (acfg->tmpfname);
10578
10579         return 0;
10580 }
10581
10582 static guint8
10583 profread_byte (FILE *infile)
10584 {
10585         guint8 i;
10586         int res;
10587
10588         res = fread (&i, 1, 1, infile);
10589         g_assert (res == 1);
10590         return i;
10591 }
10592
10593 static int
10594 profread_int (FILE *infile)
10595 {
10596         int i, res;
10597
10598         res = fread (&i, 4, 1, infile);
10599         g_assert (res == 1);
10600         return i;
10601 }
10602
10603 static char*
10604 profread_string (FILE *infile)
10605 {
10606         int len, res;
10607         char buf [1024];
10608         char *pbuf;
10609
10610         len = profread_int (infile);
10611         if (len + 1 > 1024)
10612                 pbuf = g_malloc (len + 1);
10613         else
10614                 pbuf = buf;
10615         res = fread (pbuf, 1, len, infile);
10616         g_assert (res == len);
10617         pbuf [len] = '\0';
10618         if (pbuf == buf)
10619                 return g_strdup (buf);
10620         else
10621                 return pbuf;
10622 }
10623
10624 static void
10625 load_profile_file (MonoAotCompile *acfg, char *filename)
10626 {
10627         FILE *infile;
10628         char buf [1024];
10629         int res, len, version;
10630         char magic [32];
10631
10632         infile = fopen (filename, "r");
10633         if (!infile) {
10634                 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10635                 exit (1);
10636         }
10637
10638         printf ("Using profile data file '%s'\n", filename);
10639
10640         sprintf (magic, AOT_PROFILER_MAGIC);
10641         len = strlen (magic);
10642         res = fread (buf, 1, len, infile);
10643         magic [len] = '\0';
10644         buf [len] = '\0';
10645         if ((res != len) || strcmp (buf, magic) != 0) {
10646                 printf ("Profile file has wrong header: '%s'.\n", buf);
10647                 fclose (infile);
10648                 exit (1);
10649         }
10650         guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10651         version = profread_int (infile);
10652         if (version != expected_version) {
10653                 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10654                 fclose (infile);
10655                 exit (1);
10656         }
10657
10658         ProfileData *data = g_new0 (ProfileData, 1);
10659         data->images = g_hash_table_new (NULL, NULL);
10660         data->classes = g_hash_table_new (NULL, NULL);
10661         data->ginsts = g_hash_table_new (NULL, NULL);
10662         data->methods = g_hash_table_new (NULL, NULL);
10663
10664         while (TRUE) {
10665                 int type = profread_byte (infile);
10666                 int id = profread_int (infile);
10667
10668                 if (type == AOTPROF_RECORD_NONE)
10669                         break;
10670
10671                 switch (type) {
10672                 case AOTPROF_RECORD_IMAGE: {
10673                         ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10674                         idata->name = profread_string (infile);
10675                         char *mvid = profread_string (infile);
10676                         g_free (mvid);
10677                         g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10678                         break;
10679                 }
10680                 case AOTPROF_RECORD_GINST: {
10681                         int i;
10682                         int len = profread_int (infile);
10683
10684                         GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10685                         gdata->argc = len;
10686                         gdata->argv = g_new0 (ClassProfileData*, len);
10687
10688                         for (i = 0; i < len; ++i) {
10689                                 int class_id = profread_int (infile);
10690
10691                                 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10692                                 g_assert (gdata->argv [i]);
10693                         }
10694                         g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10695                         break;
10696                 }
10697                 case AOTPROF_RECORD_TYPE: {
10698                         int type = profread_byte (infile);
10699
10700                         switch (type) {
10701                         case MONO_TYPE_CLASS: {
10702                                 int image_id = profread_int (infile);
10703                                 int ginst_id = profread_int (infile);
10704                                 char *class_name = profread_string (infile);
10705
10706                                 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10707                                 g_assert (image);
10708
10709                                 char *p = strrchr (class_name, '.');
10710                                 g_assert (p);
10711                                 *p = '\0';
10712
10713                                 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10714                                 cdata->image = image;
10715                                 cdata->ns = g_strdup (class_name);
10716                                 cdata->name = g_strdup (p + 1);
10717
10718                                 if (ginst_id != -1) {
10719                                         cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10720                                         g_assert (cdata->inst);
10721                                 }
10722                                 g_free (class_name);
10723
10724                                 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10725                                 break;
10726                         }
10727 #if 0
10728                         case MONO_TYPE_SZARRAY: {
10729                                 int elem_id = profread_int (infile);
10730                                 // FIXME:
10731                                 break;
10732                         }
10733 #endif
10734                         default:
10735                                 g_assert_not_reached ();
10736                                 break;
10737                         }
10738                         break;
10739                 }
10740                 case AOTPROF_RECORD_METHOD: {
10741                         int class_id = profread_int (infile);
10742                         int ginst_id = profread_int (infile);
10743                         int param_count = profread_int (infile);
10744                         char *method_name = profread_string (infile);
10745                         char *sig = profread_string (infile);
10746
10747                         ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10748                         g_assert (klass);
10749
10750                         MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10751                         mdata->id = id;
10752                         mdata->klass = klass;
10753                         mdata->name = method_name;
10754                         mdata->signature = sig;
10755                         mdata->param_count = param_count;
10756
10757                         if (ginst_id != -1) {
10758                                 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10759                                 g_assert (mdata->inst);
10760                         }
10761                         g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10762                         break;
10763                 }
10764                 default:
10765                         printf ("%d\n", type);
10766                         g_assert_not_reached ();
10767                         break;
10768                 }
10769         }
10770
10771         fclose (infile);
10772         acfg->profile_data = g_list_append (acfg->profile_data, data);
10773 }
10774
10775 static void
10776 resolve_class (ClassProfileData *cdata);
10777
10778 static void
10779 resolve_ginst (GInstProfileData *inst_data)
10780 {
10781         int i;
10782
10783         if (inst_data->inst)
10784                 return;
10785
10786         for (i = 0; i < inst_data->argc; ++i) {
10787                 resolve_class (inst_data->argv [i]);
10788                 if (!inst_data->argv [i]->klass)
10789                         return;
10790         }
10791         MonoType **args = g_new0 (MonoType*, inst_data->argc);
10792         for (i = 0; i < inst_data->argc; ++i)
10793                 args [i] = &inst_data->argv [i]->klass->byval_arg;
10794
10795         inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10796 }
10797
10798 static void
10799 resolve_class (ClassProfileData *cdata)
10800 {
10801         MonoError error;
10802         MonoClass *klass;
10803
10804         if (!cdata->image->image)
10805                 return;
10806
10807         klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10808         if (!klass) {
10809                 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10810                 return;
10811         }
10812         if (cdata->inst) {
10813                 resolve_ginst (cdata->inst);
10814                 if (!cdata->inst->inst)
10815                         return;
10816                 MonoGenericContext ctx;
10817
10818                 memset (&ctx, 0, sizeof (ctx));
10819                 ctx.class_inst = cdata->inst->inst;
10820                 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10821         } else {
10822                 cdata->klass = klass;
10823         }
10824 }
10825
10826 /*
10827  * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10828  */
10829 static void
10830 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10831 {
10832         GHashTableIter iter;
10833         gpointer key, value;
10834         int i;
10835
10836         if (!data)
10837                 return;
10838
10839         /* Images */
10840         GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10841         g_hash_table_iter_init (&iter, data->images);
10842         while (g_hash_table_iter_next (&iter, &key, &value)) {
10843                 ImageProfileData *idata = (ImageProfileData*)value;
10844
10845                 for (i = 0; i < assemblies->len; ++i) {
10846                         MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10847
10848                         if (!strcmp (ass->aname.name, idata->name)) {
10849                                 idata->image = ass->image;
10850                                 break;
10851                         }
10852                 }
10853         }
10854         g_ptr_array_free (assemblies, TRUE);
10855
10856         /* Classes */
10857         g_hash_table_iter_init (&iter, data->classes);
10858         while (g_hash_table_iter_next (&iter, &key, &value)) {
10859                 ClassProfileData *cdata = (ClassProfileData*)value;
10860
10861                 if (!cdata->image->image) {
10862                         if (acfg->aot_opts.verbose)
10863                                 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10864                         continue;
10865                 }
10866
10867                 resolve_class (cdata);
10868                 /*
10869                 if (cdata->klass)
10870                         printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10871                 */
10872         }
10873
10874         /* Methods */
10875         g_hash_table_iter_init (&iter, data->methods);
10876         while (g_hash_table_iter_next (&iter, &key, &value)) {
10877                 MethodProfileData *mdata = (MethodProfileData*)value;
10878                 MonoClass *klass;
10879                 MonoMethod *m;
10880                 gpointer miter;
10881
10882                 resolve_class (mdata->klass);
10883                 klass = mdata->klass->klass;
10884                 if (!klass) {
10885                         if (acfg->aot_opts.verbose)
10886                                 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10887                         continue;
10888                 }
10889                 miter = NULL;
10890                 while ((m = mono_class_get_methods (klass, &miter))) {
10891                         MonoError error;
10892
10893                         if (strcmp (m->name, mdata->name))
10894                                 continue;
10895                         MonoMethodSignature *sig = mono_method_signature (m);
10896                         if (!sig)
10897                                 continue;
10898                         if (sig->param_count != mdata->param_count)
10899                                 continue;
10900                         if (mdata->inst) {
10901                                 resolve_ginst (mdata->inst);
10902                                 if (!mdata->inst->inst)
10903                                         continue;
10904                                 MonoGenericContext ctx;
10905
10906                                 memset (&ctx, 0, sizeof (ctx));
10907                                 ctx.method_inst = mdata->inst->inst;
10908
10909                                 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10910                                 if (!m)
10911                                         continue;
10912                                 sig = mono_method_signature_checked (m, &error);
10913                                 if (!is_ok (&error)) {
10914                                         mono_error_cleanup (&error);
10915                                         continue;
10916                                 }
10917                         }
10918                         char *sig_str = mono_signature_full_name (sig);
10919                         gboolean match = !strcmp (sig_str, mdata->signature);
10920                         g_free (sig_str);
10921                         if (!match)
10922
10923                                 continue;
10924                         //printf ("%s\n", mono_method_full_name (m, 1));
10925                         mdata->method = m;
10926                         break;
10927                 }
10928                 if (!mdata->method) {
10929                         if (acfg->aot_opts.verbose)
10930                                 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10931                 }
10932         }
10933 }
10934
10935 static gboolean
10936 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10937 {
10938         int i;
10939
10940         for (i = 0; i < inst->type_argc; ++i) {
10941                 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10942                 if (k->image == image)
10943                         return TRUE;
10944                 if (mono_class_is_ginst (k)) {
10945                         MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10946                         if (inst_references_image (kinst, image))
10947                                 return TRUE;
10948                 }
10949         }
10950         return FALSE;
10951 }
10952
10953 static gboolean
10954 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10955 {
10956         int i;
10957
10958         for (i = 0; i < inst->type_argc; ++i) {
10959                 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10960                 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10961                         return FALSE;
10962         }
10963         return TRUE;
10964 }
10965
10966 static void
10967 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10968 {
10969         GHashTableIter iter;
10970         gpointer key, value;
10971         int count = 0;
10972
10973         if (!data)
10974                 return;
10975
10976         if (acfg->aot_opts.profile_only) {
10977                 /* Add methods referenced by the profile */
10978                 g_hash_table_iter_init (&iter, data->methods);
10979                 while (g_hash_table_iter_next (&iter, &key, &value)) {
10980                         MethodProfileData *mdata = (MethodProfileData*)value;
10981                         MonoMethod *m = mdata->method;
10982
10983                         if (!m)
10984                                 continue;
10985                         if (m->is_inflated)
10986                                 continue;
10987                         add_extra_method (acfg, m);
10988                         g_hash_table_insert (acfg->profile_methods, m, m);
10989                         count ++;
10990                 }
10991         }
10992
10993         /*
10994          * Add method instances 'related' to this assembly to the AOT image.
10995          */
10996         g_hash_table_iter_init (&iter, data->methods);
10997         while (g_hash_table_iter_next (&iter, &key, &value)) {
10998                 MethodProfileData *mdata = (MethodProfileData*)value;
10999                 MonoMethod *m = mdata->method;
11000                 MonoGenericContext *ctx;
11001
11002                 if (!m)
11003                         continue;
11004                 if (!m->is_inflated)
11005                         continue;
11006
11007                 ctx = mono_method_get_context (m);
11008                 /* For simplicity, add instances which reference the assembly we are compiling */
11009                 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
11010                          (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
11011                         !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11012                         //printf ("%s\n", mono_method_full_name (m, TRUE));
11013                         add_extra_method (acfg, m);
11014                         count ++;
11015                 } else if (m->klass->image == acfg->image &&
11016                         ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11017                          (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11018                         !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE))  {
11019                         /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11020                         //printf ("%s\n", mono_method_full_name (m, TRUE));
11021                         add_extra_method (acfg, m);
11022                         count ++;
11023                 }
11024                 /*
11025                  * FIXME: We might skip some instances, for example:
11026                  * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11027                  * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11028                  */
11029         }
11030
11031         printf ("Added %d methods from profile.\n", count);
11032 }
11033
11034 static void
11035 init_got_info (GotInfo *info)
11036 {
11037         int i;
11038
11039         info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11040         info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11041         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11042                 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11043         info->got_patches = g_ptr_array_new ();
11044 }
11045
11046 static MonoAotCompile*
11047 acfg_create (MonoAssembly *ass, guint32 opts)
11048 {
11049         MonoImage *image = ass->image;
11050         MonoAotCompile *acfg;
11051
11052         acfg = g_new0 (MonoAotCompile, 1);
11053         acfg->methods = g_ptr_array_new ();
11054         acfg->method_indexes = g_hash_table_new (NULL, NULL);
11055         acfg->method_depth = g_hash_table_new (NULL, NULL);
11056         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11057         acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11058         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11059         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11060         acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11061         acfg->image_hash = g_hash_table_new (NULL, NULL);
11062         acfg->image_table = g_ptr_array_new ();
11063         acfg->globals = g_ptr_array_new ();
11064         acfg->image = image;
11065         acfg->opts = opts;
11066         /* TODO: Write out set of SIMD instructions used, rather than just those available */
11067         acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11068         acfg->mempool = mono_mempool_new ();
11069         acfg->extra_methods = g_ptr_array_new ();
11070         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11071         acfg->unwind_ops = g_ptr_array_new ();
11072         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11073         acfg->method_order = g_ptr_array_new ();
11074         acfg->export_names = g_hash_table_new (NULL, NULL);
11075         acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11076         acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11077         acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11078         acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11079         acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11080         acfg->profile_methods = g_hash_table_new (NULL, NULL);
11081         mono_os_mutex_init_recursive (&acfg->mutex);
11082
11083         init_got_info (&acfg->got_info);
11084         init_got_info (&acfg->llvm_got_info);
11085
11086         return acfg;
11087 }
11088
11089 static void
11090 got_info_free (GotInfo *info)
11091 {
11092         int i;
11093
11094         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11095                 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11096         g_free (info->patch_to_got_offset_by_type);
11097         g_hash_table_destroy (info->patch_to_got_offset);
11098         g_ptr_array_free (info->got_patches, TRUE);
11099 }
11100
11101 static void
11102 acfg_free (MonoAotCompile *acfg)
11103 {
11104         int i;
11105
11106         mono_img_writer_destroy (acfg->w);
11107         for (i = 0; i < acfg->nmethods; ++i)
11108                 if (acfg->cfgs [i])
11109                         mono_destroy_compile (acfg->cfgs [i]);
11110
11111         g_free (acfg->cfgs);
11112
11113         g_free (acfg->static_linking_symbol);
11114         g_free (acfg->got_symbol);
11115         g_free (acfg->plt_symbol);
11116         g_ptr_array_free (acfg->methods, TRUE);
11117         g_ptr_array_free (acfg->image_table, TRUE);
11118         g_ptr_array_free (acfg->globals, TRUE);
11119         g_ptr_array_free (acfg->unwind_ops, TRUE);
11120         g_hash_table_destroy (acfg->method_indexes);
11121         g_hash_table_destroy (acfg->method_depth);
11122         g_hash_table_destroy (acfg->plt_offset_to_entry);
11123         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11124                 if (acfg->patch_to_plt_entry [i])
11125                         g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11126         }
11127         g_free (acfg->patch_to_plt_entry);
11128         g_hash_table_destroy (acfg->method_to_cfg);
11129         g_hash_table_destroy (acfg->token_info_hash);
11130         g_hash_table_destroy (acfg->method_to_pinvoke_import);
11131         g_hash_table_destroy (acfg->image_hash);
11132         g_hash_table_destroy (acfg->unwind_info_offsets);
11133         g_hash_table_destroy (acfg->method_label_hash);
11134         if (acfg->typespec_classes)
11135                 g_hash_table_destroy (acfg->typespec_classes);
11136         g_hash_table_destroy (acfg->export_names);
11137         g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11138         g_hash_table_destroy (acfg->klass_blob_hash);
11139         g_hash_table_destroy (acfg->method_blob_hash);
11140         got_info_free (&acfg->got_info);
11141         got_info_free (&acfg->llvm_got_info);
11142         mono_mempool_destroy (acfg->mempool);
11143         g_free (acfg);
11144 }
11145
11146 #define WRAPPER(e,n) n,
11147 static const char* const
11148 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11149 #include "mono/metadata/wrapper-types.h"
11150         NULL
11151 };
11152
11153 static G_GNUC_UNUSED const char*
11154 get_wrapper_type_name (int type)
11155 {
11156         return wrapper_type_names [type];
11157 }
11158
11159 //#define DUMP_PLT
11160 //#define DUMP_GOT
11161
11162 static void aot_dump (MonoAotCompile *acfg)
11163 {
11164         FILE *dumpfile;
11165         char * dumpname;
11166
11167         JsonWriter writer;
11168         mono_json_writer_init (&writer);
11169
11170         mono_json_writer_object_begin(&writer);
11171
11172         // Methods
11173         mono_json_writer_indent (&writer);
11174         mono_json_writer_object_key(&writer, "methods");
11175         mono_json_writer_array_begin (&writer);
11176
11177         int i;
11178         for (i = 0; i < acfg->nmethods; ++i) {
11179                 MonoCompile *cfg;
11180                 MonoMethod *method;
11181                 MonoClass *klass;
11182
11183                 cfg = acfg->cfgs [i];
11184                 if (!cfg)
11185                         continue;
11186
11187                 method = cfg->orig_method;
11188
11189                 mono_json_writer_indent (&writer);
11190                 mono_json_writer_object_begin(&writer);
11191
11192                 mono_json_writer_indent (&writer);
11193                 mono_json_writer_object_key(&writer, "name");
11194                 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11195
11196                 mono_json_writer_indent (&writer);
11197                 mono_json_writer_object_key(&writer, "signature");
11198                 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11199
11200                 mono_json_writer_indent (&writer);
11201                 mono_json_writer_object_key(&writer, "code_size");
11202                 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11203
11204                 klass = method->klass;
11205
11206                 mono_json_writer_indent (&writer);
11207                 mono_json_writer_object_key(&writer, "class");
11208                 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11209
11210                 mono_json_writer_indent (&writer);
11211                 mono_json_writer_object_key(&writer, "namespace");
11212                 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11213
11214                 mono_json_writer_indent (&writer);
11215                 mono_json_writer_object_key(&writer, "wrapper_type");
11216                 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11217
11218                 mono_json_writer_indent_pop (&writer);
11219                 mono_json_writer_indent (&writer);
11220                 mono_json_writer_object_end (&writer);
11221                 mono_json_writer_printf (&writer, ",\n");
11222         }
11223
11224         mono_json_writer_indent_pop (&writer);
11225         mono_json_writer_indent (&writer);
11226         mono_json_writer_array_end (&writer);
11227         mono_json_writer_printf (&writer, ",\n");
11228
11229         // PLT entries
11230 #ifdef DUMP_PLT
11231         mono_json_writer_indent_push (&writer);
11232         mono_json_writer_indent (&writer);
11233         mono_json_writer_object_key(&writer, "plt");
11234         mono_json_writer_array_begin (&writer);
11235
11236         for (i = 0; i < acfg->plt_offset; ++i) {
11237                 MonoPltEntry *plt_entry = NULL;
11238                 MonoJumpInfo *ji;
11239
11240                 if (i == 0)
11241                         /* 
11242                          * The first plt entry is unused.
11243                          */
11244                         continue;
11245
11246                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11247                 ji = plt_entry->ji;
11248
11249                 mono_json_writer_indent (&writer);
11250                 mono_json_writer_printf (&writer, "{ ");
11251                 mono_json_writer_object_key(&writer, "symbol");
11252                 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11253         }
11254
11255         mono_json_writer_indent_pop (&writer);
11256         mono_json_writer_indent (&writer);
11257         mono_json_writer_array_end (&writer);
11258         mono_json_writer_printf (&writer, ",\n");
11259 #endif
11260
11261         // GOT entries
11262 #ifdef DUMP_GOT
11263         mono_json_writer_indent_push (&writer);
11264         mono_json_writer_indent (&writer);
11265         mono_json_writer_object_key(&writer, "got");
11266         mono_json_writer_array_begin (&writer);
11267
11268         mono_json_writer_indent_push (&writer);
11269         for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11270                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11271
11272                 mono_json_writer_indent (&writer);
11273                 mono_json_writer_printf (&writer, "{ ");
11274                 mono_json_writer_object_key(&writer, "patch_name");
11275                 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11276         }
11277
11278         mono_json_writer_indent_pop (&writer);
11279         mono_json_writer_indent (&writer);
11280         mono_json_writer_array_end (&writer);
11281         mono_json_writer_printf (&writer, ",\n");
11282 #endif
11283
11284         mono_json_writer_indent_pop (&writer);
11285         mono_json_writer_indent (&writer);
11286         mono_json_writer_object_end (&writer);
11287
11288         dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11289         dumpfile = fopen (dumpname, "w+");
11290         g_free (dumpname);
11291
11292         fprintf (dumpfile, "%s", writer.text->str);
11293         fclose (dumpfile);
11294
11295         mono_json_writer_destroy (&writer);
11296 }
11297
11298 static const char *preinited_jit_icalls[] = {
11299         "mono_aot_init_llvm_method",
11300         "mono_aot_init_gshared_method_this",
11301         "mono_aot_init_gshared_method_mrgctx",
11302         "mono_aot_init_gshared_method_vtable",
11303         "mono_llvm_throw_corlib_exception",
11304         "mono_init_vtable_slot",
11305         "mono_helper_ldstr_mscorlib"
11306 };
11307
11308 static void
11309 add_preinit_got_slots (MonoAotCompile *acfg)
11310 {
11311         MonoJumpInfo *ji;
11312         int i;
11313
11314         /*
11315          * Allocate the first few GOT entries to information which is needed frequently, or it is needed
11316          * during method initialization etc.
11317          */
11318
11319         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11320         ji->type = MONO_PATCH_INFO_IMAGE;
11321         ji->data.image = acfg->image;
11322         get_got_offset (acfg, FALSE, ji);
11323         get_got_offset (acfg, TRUE, ji);
11324
11325         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11326         ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
11327         get_got_offset (acfg, FALSE, ji);
11328         get_got_offset (acfg, TRUE, ji);
11329
11330         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11331         ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
11332         get_got_offset (acfg, FALSE, ji);
11333         get_got_offset (acfg, TRUE, ji);
11334
11335         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11336         ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
11337         get_got_offset (acfg, FALSE, ji);
11338         get_got_offset (acfg, TRUE, ji);
11339
11340         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11341         ji->type = MONO_PATCH_INFO_AOT_MODULE;
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_GC_NURSERY_BITS;
11347         get_got_offset (acfg, FALSE, ji);
11348         get_got_offset (acfg, TRUE, ji);
11349
11350         for (i = 0; i < TLS_KEY_NUM; i++) {
11351                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11352                 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
11353                 ji->data.index = i;
11354                 get_got_offset (acfg, FALSE, ji);
11355                 get_got_offset (acfg, TRUE, ji);
11356
11357                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11358                 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
11359                 ji->data.index = i;
11360                 get_got_offset (acfg, FALSE, ji);
11361                 get_got_offset (acfg, TRUE, ji);
11362         }
11363
11364         ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11365         ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
11366         get_got_offset (acfg, FALSE, ji);
11367         get_got_offset (acfg, TRUE, ji);
11368
11369         for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
11370                 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
11371                 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11372                 ji->data.name = preinited_jit_icalls [i];
11373                 get_got_offset (acfg, FALSE, ji);
11374                 get_got_offset (acfg, TRUE, ji);
11375         }
11376
11377         acfg->nshared_got_entries = acfg->got_offset;
11378 }
11379
11380 int
11381 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11382 {
11383         MonoImage *image = ass->image;
11384         int i, res;
11385         gint64 all_sizes;
11386         MonoAotCompile *acfg;
11387         char *outfile_name, *tmp_outfile_name, *p;
11388         char llvm_stats_msg [256];
11389         TV_DECLARE (atv);
11390         TV_DECLARE (btv);
11391
11392         acfg = acfg_create (ass, opts);
11393
11394         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
11395         acfg->aot_opts.write_symbols = TRUE;
11396         acfg->aot_opts.ntrampolines = 4096;
11397         acfg->aot_opts.nrgctx_trampolines = 4096;
11398         acfg->aot_opts.nimt_trampolines = 512;
11399         acfg->aot_opts.nrgctx_fetch_trampolines = 128;
11400         acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
11401         acfg->aot_opts.llvm_path = g_strdup ("");
11402         acfg->aot_opts.temp_path = g_strdup ("");
11403 #ifdef MONOTOUCH
11404         acfg->aot_opts.use_trampolines_page = TRUE;
11405 #endif
11406
11407         mono_aot_parse_options (aot_options, &acfg->aot_opts);
11408
11409         if (acfg->aot_opts.logfile) {
11410                 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
11411         }
11412
11413         if (acfg->aot_opts.data_outfile) {
11414                 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
11415                 if (!acfg->data_outfile) {
11416                         aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
11417                         return 1;
11418                 }
11419                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
11420         }
11421
11422         //acfg->aot_opts.print_skipped_methods = TRUE;
11423
11424 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
11425         if (acfg->opts & MONO_OPT_GSHAREDVT) {
11426                 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
11427                 return 1;
11428         }
11429         if (acfg->aot_opts.llvm_only) {
11430                 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
11431                 return 1;
11432         }
11433 #else
11434         if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11435                 acfg->opts |= MONO_OPT_GSHAREDVT;
11436 #endif
11437
11438 #if !defined(ENABLE_LLVM)
11439         if (acfg->aot_opts.llvm_only) {
11440                 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11441                 return 1;
11442         }
11443 #endif
11444
11445         if (acfg->opts & MONO_OPT_GSHAREDVT)
11446                 mono_set_generic_sharing_vt_supported (TRUE);
11447
11448         aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11449
11450         generate_aotid ((guint8*) &acfg->image->aotid);
11451
11452         char *aotid = mono_guid_to_string (acfg->image->aotid);
11453         aot_printf (acfg, "AOTID %s\n", aotid);
11454         g_free (aotid);
11455
11456 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11457         if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11458                 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11459                 return 1;
11460         }
11461 #endif
11462
11463         if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11464                 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11465                 return 1;
11466         }
11467
11468         if (acfg->aot_opts.static_link)
11469                 acfg->aot_opts.asm_writer = TRUE;
11470
11471         if (acfg->aot_opts.soft_debug) {
11472                 MonoDebugOptions *opt = mini_get_debug_options ();
11473
11474                 opt->mdb_optimizations = TRUE;
11475                 opt->gen_sdb_seq_points = TRUE;
11476
11477                 if (!mono_debug_enabled ()) {
11478                         aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11479                         return 1;
11480                 }
11481                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11482         }
11483
11484         if (mono_use_llvm || acfg->aot_opts.llvm) {
11485                 acfg->llvm = TRUE;
11486                 acfg->aot_opts.asm_writer = TRUE;
11487                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11488
11489                 if (acfg->aot_opts.soft_debug) {
11490                         aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11491                         return 1;
11492                 }
11493
11494                 mini_llvm_init ();
11495
11496                 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11497                         aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11498                         return 1;
11499                 }
11500         }
11501
11502         if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11503                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11504                 acfg->is_full_aot = TRUE;
11505         }
11506
11507         if (mono_threads_is_coop_enabled ())
11508                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11509
11510         if (acfg->aot_opts.instances_logfile_path) {
11511                 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11512                 if (!acfg->instances_logfile) {
11513                         aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11514                         return 1;
11515                 }
11516         }
11517
11518         if (acfg->aot_opts.profile_files) {
11519                 GList *l;
11520
11521                 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11522                         load_profile_file (acfg, (char*)l->data);
11523                 }
11524         }
11525
11526         {
11527                 int method_index;
11528
11529        for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11530                    g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11531        }
11532         }
11533
11534         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11535 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11536         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11537 #endif
11538         acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11539 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11540         if (acfg->opts & MONO_OPT_GSHAREDVT)
11541                 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11542 #endif
11543
11544         acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11545
11546         arch_init (acfg);
11547
11548         if (mono_use_llvm || acfg->aot_opts.llvm) {
11549
11550                 /*
11551                  * Emit all LLVM code into a separate assembly/object file and link with it
11552                  * normally.
11553                  */
11554                 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11555                         acfg->llvm_owriter = TRUE;
11556                 } else if (acfg->aot_opts.llvm_outfile) {
11557                         int len = strlen (acfg->aot_opts.llvm_outfile);
11558
11559                         if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11560                                 acfg->llvm_owriter = TRUE;
11561                 }
11562         }
11563
11564         if (acfg->llvm && acfg->thumb_mixed)
11565                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11566         if (acfg->aot_opts.llvm_only)
11567                 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11568
11569         acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11570         /* Get rid of characters which cannot occur in symbols */
11571         for (p = acfg->assembly_name_sym; *p; ++p) {
11572                 if (!(isalnum (*p) || *p == '_'))
11573                         *p = '_';
11574         }
11575
11576         acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11577         acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11578         acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11579         if (acfg->llvm) {
11580                 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11581                 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11582         }
11583
11584         acfg->method_index = 1;
11585
11586         if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11587                 mono_set_partial_sharing_supported (TRUE);
11588
11589         res = collect_methods (acfg);
11590         if (!res)
11591                 return 1;
11592
11593         {
11594                 GList *l;
11595
11596                 for (l = acfg->profile_data; l; l = l->next)
11597                         resolve_profile_data (acfg, (ProfileData*)l->data);
11598                 for (l = acfg->profile_data; l; l = l->next)
11599                         add_profile_instances (acfg, (ProfileData*)l->data);
11600         }
11601
11602         acfg->cfgs_size = acfg->methods->len + 32;
11603         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11604
11605         /* PLT offset 0 is reserved for the PLT trampoline */
11606         acfg->plt_offset = 1;
11607         add_preinit_got_slots (acfg);
11608
11609 #ifdef ENABLE_LLVM
11610         if (acfg->llvm) {
11611                 llvm_acfg = acfg;
11612                 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11613         }
11614 #endif
11615
11616         TV_GETTIME (atv);
11617
11618         compile_methods (acfg);
11619
11620         TV_GETTIME (btv);
11621
11622         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11623
11624         TV_GETTIME (atv);
11625
11626 #ifdef ENABLE_LLVM
11627         if (acfg->llvm) {
11628                 if (acfg->aot_opts.asm_only) {
11629                         if (acfg->aot_opts.outfile) {
11630                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11631                                 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11632                         } else {
11633                                 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11634                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11635                         }
11636                         g_assert (acfg->aot_opts.llvm_outfile);
11637                         acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11638                         if (acfg->llvm_owriter)
11639                                 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11640                         else
11641                                 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11642                 } else {
11643                         acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11644                                 g_strdup_printf ("%s", "temp") :
11645                                 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11646                                 
11647                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11648                         acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11649                         acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11650                 }
11651         }
11652 #endif
11653
11654         if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11655                 if (acfg->aot_opts.outfile)
11656                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11657                 else
11658                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11659                 acfg->fp = fopen (acfg->tmpfname, "w+");
11660         } else {
11661                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11662                 acfg->fp = fdopen (i, "w+");
11663         }
11664         if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11665                 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11666                 return 1;
11667         }
11668         if (acfg->fp)
11669                 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11670
11671         tmp_outfile_name = NULL;
11672         outfile_name = NULL;
11673
11674         /* Compute symbols for methods */
11675         for (i = 0; i < acfg->nmethods; ++i) {
11676                 if (acfg->cfgs [i]) {
11677                         MonoCompile *cfg = acfg->cfgs [i];
11678                         int method_index = get_method_index (acfg, cfg->orig_method);
11679
11680                         if (COMPILE_LLVM (cfg))
11681                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11682                         else if (acfg->global_symbols || acfg->llvm)
11683                                 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11684                         else
11685                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11686                         cfg->asm_debug_symbol = cfg->asm_symbol;
11687                 }
11688         }
11689
11690         if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11691                 /*
11692                  * CLANG supports GAS .file/.loc directives, so emit line number information this way
11693                  */
11694                 acfg->gas_line_numbers = TRUE;
11695         }
11696
11697 #ifdef EMIT_DWARF_INFO
11698         if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11699                 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11700                         aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11701                         return 1;
11702                 }
11703                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11704         }
11705 #endif /* EMIT_DWARF_INFO */
11706
11707         if (acfg->w)
11708                 mono_img_writer_emit_start (acfg->w);
11709
11710         if (acfg->dwarf)
11711                 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11712
11713         emit_code (acfg);
11714
11715         emit_info (acfg);
11716
11717         emit_extra_methods (acfg);
11718
11719         emit_trampolines (acfg);
11720
11721         emit_class_name_table (acfg);
11722
11723         emit_got_info (acfg, FALSE);
11724         if (acfg->llvm)
11725                 emit_got_info (acfg, TRUE);
11726
11727         emit_exception_info (acfg);
11728
11729         emit_unwind_info (acfg);
11730
11731         emit_class_info (acfg);
11732
11733         emit_plt (acfg);
11734
11735         emit_image_table (acfg);
11736
11737         emit_got (acfg);
11738
11739         {
11740                 /*
11741                  * The managed allocators are GC specific, so can't use an AOT image created by one GC
11742                  * in another.
11743                  */
11744                 const char *gc_name = mono_gc_get_gc_name ();
11745                 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11746         }
11747
11748         emit_blob (acfg);
11749
11750         emit_objc_selectors (acfg);
11751
11752         emit_globals (acfg);
11753
11754         emit_file_info (acfg);
11755
11756         emit_library_info (acfg);
11757
11758         if (acfg->dwarf) {
11759                 emit_dwarf_info (acfg);
11760                 mono_dwarf_writer_close (acfg->dwarf);
11761         }
11762
11763         emit_mem_end (acfg);
11764
11765         if (acfg->need_pt_gnu_stack) {
11766                 /* This is required so the .so doesn't have an executable stack */
11767                 /* The bin writer already emits this */
11768                 fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
11769         }
11770
11771         if (acfg->aot_opts.data_outfile)
11772                 fclose (acfg->data_outfile);
11773
11774 #ifdef ENABLE_LLVM
11775         if (acfg->llvm) {
11776                 gboolean res;
11777
11778                 res = emit_llvm_file (acfg);
11779                 if (!res)
11780                         return 1;
11781         }
11782 #endif
11783
11784         TV_GETTIME (btv);
11785
11786         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11787
11788         if (acfg->llvm)
11789                 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11790         else
11791                 strcpy (llvm_stats_msg, "");
11792
11793         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;
11794
11795         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",
11796                                 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11797                                 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11798                                 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11799                                 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11800                                 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11801                                 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,
11802                                 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11803                                 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11804                         (int)(acfg->got_offset * sizeof (gpointer)));
11805         aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n", 
11806                         acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11807                         llvm_stats_msg,
11808                         acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11809                         acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11810         if (acfg->stats.genericcount)
11811                 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11812         if (acfg->stats.abscount)
11813                 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11814         if (acfg->stats.lmfcount)
11815                 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11816         if (acfg->stats.ocount)
11817                 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11818
11819         TV_GETTIME (atv);
11820         if (acfg->w) {
11821                 res = mono_img_writer_emit_writeout (acfg->w);
11822                 if (res != 0) {
11823                         acfg_free (acfg);
11824                         return res;
11825                 }
11826                 res = compile_asm (acfg);
11827                 if (res != 0) {
11828                         acfg_free (acfg);
11829                         return res;
11830                 }
11831         }
11832         TV_GETTIME (btv);
11833         acfg->stats.link_time = TV_ELAPSED (atv, btv);
11834
11835         if (acfg->aot_opts.stats) {
11836                 int i;
11837
11838                 aot_printf (acfg, "GOT slot distribution:\n");
11839                 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11840                         if (acfg->stats.got_slot_types [i])
11841                                 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]);
11842                 aot_printf (acfg, "\nMethod stats:\n");
11843                 aot_printf (acfg, "\tNormal:    %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11844                 aot_printf (acfg, "\tInstance:  %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11845                 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11846                 aot_printf (acfg, "\tWrapper:   %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11847         }
11848
11849         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);
11850
11851         if (acfg->aot_opts.dump_json)
11852                 aot_dump (acfg);
11853
11854         acfg_free (acfg);
11855         
11856         return 0;
11857 }
11858
11859 #else
11860
11861 /* AOT disabled */
11862
11863 void*
11864 mono_aot_readonly_field_override (MonoClassField *field)
11865 {
11866         return NULL;
11867 }
11868
11869 int
11870 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11871 {
11872         return 0;
11873 }
11874
11875 gboolean
11876 mono_aot_is_shared_got_offset (int offset)
11877 {
11878         return FALSE;
11879 }
11880
11881 #endif