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