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