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