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