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