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