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