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