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