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