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