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