Increase an aot buffer size again.
[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         GList *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_MONO_ENTER, p, &p);
2052                         } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2053                                 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2054                         } else if (strcmp (method->name, "PtrToStructure") == 0) {
2055                                 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2056                                 encode_klass_ref (acfg, method->klass, p, &p);
2057                         } else if (strcmp (method->name, "StructureToPtr") == 0) {
2058                                 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2059                                 encode_klass_ref (acfg, method->klass, p, &p);
2060                         } else {
2061                                 g_assert_not_reached ();
2062                         }
2063                         break;
2064                 case MONO_WRAPPER_SYNCHRONIZED:
2065                 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2066                 case MONO_WRAPPER_RUNTIME_INVOKE: {
2067                         MonoMethod *m;
2068
2069                         m = mono_marshal_method_from_wrapper (method);
2070                         g_assert (m);
2071                         g_assert (m != method);
2072                         encode_method_ref (acfg, m, p, &p);
2073                         break;
2074                 }
2075                 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2076                         if (!strcmp (method->name, "ElementAddr")) {
2077                                 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2078
2079                                 g_assert (info);
2080                                 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2081                                 encode_value (info->rank, p, &p);
2082                                 encode_value (info->elem_size, p, &p);
2083                         } else {
2084                                 g_assert_not_reached ();
2085                         }
2086                         break;
2087                 case MONO_WRAPPER_CASTCLASS:
2088                         if (!strcmp (method->name, "__castclass_with_cache")) {
2089                                 encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
2090                         } else {
2091                                 g_assert_not_reached ();
2092                         }
2093                         break;
2094                 default:
2095                         g_assert_not_reached ();
2096                 }
2097         } else if (mono_method_signature (method)->is_inflated) {
2098                 /* 
2099                  * This is a generic method, find the original token which referenced it and
2100                  * encode that.
2101                  * Obtain the token from information recorded by the JIT.
2102                  */
2103                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2104                 if (ji) {
2105                         image_index = get_image_index (acfg, ji->image);
2106                         g_assert (image_index < MAX_IMAGE_INDEX);
2107                         token = ji->token;
2108
2109                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2110                         encode_value (image_index, p, &p);
2111                         encode_value (token, p, &p);
2112                 } else {
2113                         MonoMethod *declaring;
2114                         MonoGenericContext *context = mono_method_get_context (method);
2115
2116                         g_assert (method->is_inflated);
2117                         declaring = ((MonoMethodInflated*)method)->declaring;
2118
2119                         /*
2120                          * This might be a non-generic method of a generic instance, which 
2121                          * doesn't have a token since the reference is generated by the JIT 
2122                          * like Nullable:Box/Unbox, or by generic sharing.
2123                          */
2124
2125                         encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2126                         /* Encode the klass */
2127                         encode_klass_ref (acfg, method->klass, p, &p);
2128                         /* Encode the method */
2129                         image_index = get_image_index (acfg, method->klass->image);
2130                         g_assert (image_index < MAX_IMAGE_INDEX);
2131                         g_assert (declaring->token);
2132                         token = declaring->token;
2133                         g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2134                         encode_value (image_index, p, &p);
2135                         encode_value (token, p, &p);
2136                         encode_generic_context (acfg, context, p, &p);
2137                 }
2138         } else if (token == 0) {
2139                 /* This might be a method of a constructed type like int[,].Set */
2140                 /* Obtain the token from information recorded by the JIT */
2141                 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2142                 if (ji) {
2143                         image_index = get_image_index (acfg, ji->image);
2144                         g_assert (image_index < MAX_IMAGE_INDEX);
2145                         token = ji->token;
2146
2147                         encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2148                         encode_value (image_index, p, &p);
2149                         encode_value (token, p, &p);
2150                 } else {
2151                         /* Array methods */
2152                         g_assert (method->klass->rank);
2153
2154                         /* Encode directly */
2155                         encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2156                         encode_klass_ref (acfg, method->klass, p, &p);
2157                         if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2158                                 encode_value (0, p, &p);
2159                         else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2160                                 encode_value (1, p, &p);
2161                         else if (!strcmp (method->name, "Get"))
2162                                 encode_value (2, p, &p);
2163                         else if (!strcmp (method->name, "Address"))
2164                                 encode_value (3, p, &p);
2165                         else if (!strcmp (method->name, "Set"))
2166                                 encode_value (4, p, &p);
2167                         else
2168                                 g_assert_not_reached ();
2169                 }
2170         } else {
2171                 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2172                 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2173         }
2174         *endbuf = p;
2175 }
2176
2177 static gint
2178 compare_patches (gconstpointer a, gconstpointer b)
2179 {
2180         int i, j;
2181
2182         i = (*(MonoJumpInfo**)a)->ip.i;
2183         j = (*(MonoJumpInfo**)b)->ip.i;
2184
2185         if (i < j)
2186                 return -1;
2187         else
2188                 if (i > j)
2189                         return 1;
2190         else
2191                 return 0;
2192 }
2193
2194 static G_GNUC_UNUSED char*
2195 patch_to_string (MonoJumpInfo *patch_info)
2196 {
2197         GString *str;
2198
2199         str = g_string_new ("");
2200
2201         g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2202
2203         switch (patch_info->type) {
2204         case MONO_PATCH_INFO_VTABLE:
2205                 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2206                 break;
2207         default:
2208                 break;
2209         }
2210         g_string_append_printf (str, ")");
2211         return g_string_free (str, FALSE);
2212 }
2213
2214 /*
2215  * is_plt_patch:
2216  *
2217  *   Return whenever PATCH_INFO refers to a direct call, and thus requires a
2218  * PLT entry.
2219  */
2220 static inline gboolean
2221 is_plt_patch (MonoJumpInfo *patch_info)
2222 {
2223         switch (patch_info->type) {
2224         case MONO_PATCH_INFO_METHOD:
2225         case MONO_PATCH_INFO_INTERNAL_METHOD:
2226         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2227         case MONO_PATCH_INFO_ICALL_ADDR:
2228         case MONO_PATCH_INFO_CLASS_INIT:
2229         case MONO_PATCH_INFO_RGCTX_FETCH:
2230         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2231         case MONO_PATCH_INFO_MONITOR_ENTER:
2232         case MONO_PATCH_INFO_MONITOR_EXIT:
2233         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2234                 return TRUE;
2235         default:
2236                 return FALSE;
2237         }
2238 }
2239
2240 /*
2241  * get_plt_symbol:
2242  *
2243  *   Return the symbol identifying the plt entry PLT_OFFSET.
2244  */
2245 static char*
2246 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2247 {
2248 #ifdef __APPLE__
2249         /* 
2250          * The Apple linker reorganizes object files, so it doesn't like branches to local
2251          * labels, since those have no relocations.
2252          */
2253         return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2254 #else
2255         return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2256 #endif
2257 }
2258
2259 /*
2260  * get_plt_entry:
2261  *
2262  *   Return a PLT entry which belongs to the method identified by PATCH_INFO.
2263  */
2264 static MonoPltEntry*
2265 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2266 {
2267         MonoPltEntry *res;
2268
2269         if (!is_plt_patch (patch_info))
2270                 return NULL;
2271
2272         res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2273
2274         // FIXME: This breaks the calculation of final_got_size         
2275         if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2276                 /* 
2277                  * Allocate a separate PLT slot for each such patch, since some plt
2278                  * entries will refer to the method itself, and some will refer to the
2279                  * wrapper.
2280                  */
2281                 res = NULL;
2282         }
2283
2284         if (!res) {
2285                 MonoJumpInfo *new_ji;
2286
2287                 g_assert (!acfg->final_got_size);
2288
2289                 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2290
2291                 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2292                 res->plt_offset = acfg->plt_offset;
2293                 res->ji = new_ji;
2294                 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2295                 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2296
2297                 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2298
2299                 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2300
2301                 acfg->plt_offset ++;
2302         }
2303
2304         return res;
2305 }
2306
2307 /**
2308  * get_got_offset:
2309  *
2310  *   Returns the offset of the GOT slot where the runtime object resulting from resolving
2311  * JI could be found if it exists, otherwise allocates a new one.
2312  */
2313 static guint32
2314 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2315 {
2316         guint32 got_offset;
2317
2318         got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2319         if (got_offset)
2320                 return got_offset - 1;
2321
2322         got_offset = acfg->got_offset;
2323         acfg->got_offset ++;
2324
2325         if (acfg->final_got_size)
2326                 g_assert (got_offset < acfg->final_got_size);
2327
2328         acfg->stats.got_slots ++;
2329         acfg->stats.got_slot_types [ji->type] ++;
2330
2331         g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2332         g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2333         g_ptr_array_add (acfg->got_patches, ji);
2334
2335         return got_offset;
2336 }
2337
2338 /* Add a method to the list of methods which need to be emitted */
2339 static void
2340 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2341 {
2342         g_assert (method);
2343         if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2344                 g_ptr_array_add (acfg->methods, method);
2345                 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2346                 acfg->nmethods = acfg->methods->len + 1;
2347         }
2348
2349         if (method->wrapper_type || extra)
2350                 g_ptr_array_add (acfg->extra_methods, method);
2351 }
2352
2353 static guint32
2354 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2355 {
2356         int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2357         
2358         g_assert (index);
2359
2360         return index - 1;
2361 }
2362
2363 static int
2364 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2365 {
2366         int index;
2367
2368         index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2369         if (index)
2370                 return index - 1;
2371
2372         index = acfg->method_index;
2373         add_method_with_index (acfg, method, index, extra);
2374
2375         /* FIXME: Fix quadratic behavior */
2376         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2377
2378         g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2379
2380         acfg->method_index ++;
2381
2382         return index;
2383 }
2384
2385 static int
2386 add_method (MonoAotCompile *acfg, MonoMethod *method)
2387 {
2388         return add_method_full (acfg, method, FALSE, 0);
2389 }
2390
2391 static void
2392 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2393 {
2394         add_method_full (acfg, method, TRUE, 0);
2395 }
2396
2397 static void
2398 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2399 {
2400         add_method_full (acfg, method, TRUE, depth);
2401 }
2402
2403 static void
2404 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2405 {
2406         MonoAotCompile *acfg = user_data;
2407         MonoJitICallInfo *callinfo = value;
2408         MonoMethod *wrapper;
2409         char *name;
2410
2411         if (!callinfo->sig)
2412                 return;
2413
2414         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2415         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2416         g_free (name);
2417
2418         add_method (acfg, wrapper);
2419 }
2420
2421 static MonoMethod*
2422 get_runtime_invoke_sig (MonoMethodSignature *sig)
2423 {
2424         MonoMethodBuilder *mb;
2425         MonoMethod *m;
2426
2427         mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2428         m = mono_mb_create_method (mb, sig, 16);
2429         return mono_marshal_get_runtime_invoke (m, FALSE);
2430 }
2431
2432 static gboolean
2433 can_marshal_struct (MonoClass *klass)
2434 {
2435         MonoClassField *field;
2436         gboolean can_marshal = TRUE;
2437         gpointer iter = NULL;
2438
2439         if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2440                 return FALSE;
2441
2442         /* Only allow a few field types to avoid asserts in the marshalling code */
2443         while ((field = mono_class_get_fields (klass, &iter))) {
2444                 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2445                         continue;
2446
2447                 switch (field->type->type) {
2448                 case MONO_TYPE_I4:
2449                 case MONO_TYPE_U4:
2450                 case MONO_TYPE_I1:
2451                 case MONO_TYPE_U1:
2452                 case MONO_TYPE_BOOLEAN:
2453                 case MONO_TYPE_I2:
2454                 case MONO_TYPE_U2:
2455                 case MONO_TYPE_CHAR:
2456                 case MONO_TYPE_I8:
2457                 case MONO_TYPE_U8:
2458                 case MONO_TYPE_I:
2459                 case MONO_TYPE_U:
2460                 case MONO_TYPE_PTR:
2461                 case MONO_TYPE_R4:
2462                 case MONO_TYPE_R8:
2463                 case MONO_TYPE_STRING:
2464                         break;
2465                 case MONO_TYPE_VALUETYPE:
2466                         if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2467                                 can_marshal = FALSE;
2468                         break;
2469                 default:
2470                         can_marshal = FALSE;
2471                         break;
2472                 }
2473         }
2474
2475         /* Special cases */
2476         /* Its hard to compute whenever these can be marshalled or not */
2477         if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2478                 return TRUE;
2479
2480         return can_marshal;
2481 }
2482
2483 static void
2484 add_wrappers (MonoAotCompile *acfg)
2485 {
2486         MonoMethod *method, *m;
2487         int i, j;
2488         MonoMethodSignature *sig, *csig;
2489         guint32 token;
2490
2491         /* 
2492          * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2493          * so there is only one wrapper of a given type, or inlining their contents into their
2494          * callers.
2495          */
2496
2497         /* 
2498          * FIXME: This depends on the fact that different wrappers have different 
2499          * names.
2500          */
2501
2502         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2503                 MonoMethod *method;
2504                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2505                 gboolean skip = FALSE;
2506
2507                 method = mono_get_method (acfg->image, token, NULL);
2508
2509                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2510                         (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2511                         (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2512                         skip = TRUE;
2513
2514                 if (method->is_generic || method->klass->generic_container)
2515                         skip = TRUE;
2516
2517                 /* Skip methods which can not be handled by get_runtime_invoke () */
2518                 sig = mono_method_signature (method);
2519                 if (!sig)
2520                         continue;
2521                 if ((sig->ret->type == MONO_TYPE_PTR) ||
2522                         (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2523                         skip = TRUE;
2524
2525                 for (j = 0; j < sig->param_count; j++) {
2526                         if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2527                                 skip = TRUE;
2528                 }
2529
2530 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2531                 if (!method->klass->contextbound) {
2532                         MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2533                         gboolean has_nullable = FALSE;
2534
2535                         for (j = 0; j < sig->param_count; j++) {
2536                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2537                                         has_nullable = TRUE;
2538                         }
2539
2540                         if (info && !has_nullable) {
2541                                 /* Supported by the dynamic runtime-invoke wrapper */
2542                                 skip = TRUE;
2543                                 g_free (info);
2544                         }
2545                 }
2546 #endif
2547
2548                 if (!skip) {
2549                         //printf ("%s\n", mono_method_full_name (method, TRUE));
2550                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2551                 }
2552         }
2553
2554         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2555 #ifdef MONO_ARCH_HAVE_TLS_GET
2556                 MonoMethodDesc *desc;
2557                 MonoMethod *orig_method;
2558                 int nallocators;
2559 #endif
2560
2561                 /* Runtime invoke wrappers */
2562
2563                 /* void runtime-invoke () [.cctor] */
2564                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2565                 csig->ret = &mono_defaults.void_class->byval_arg;
2566                 add_method (acfg, get_runtime_invoke_sig (csig));
2567
2568                 /* void runtime-invoke () [Finalize] */
2569                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2570                 csig->hasthis = 1;
2571                 csig->ret = &mono_defaults.void_class->byval_arg;
2572                 add_method (acfg, get_runtime_invoke_sig (csig));
2573
2574                 /* void runtime-invoke (string) [exception ctor] */
2575                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2576                 csig->hasthis = 1;
2577                 csig->ret = &mono_defaults.void_class->byval_arg;
2578                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2579                 add_method (acfg, get_runtime_invoke_sig (csig));
2580
2581                 /* void runtime-invoke (string, string) [exception ctor] */
2582                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2583                 csig->hasthis = 1;
2584                 csig->ret = &mono_defaults.void_class->byval_arg;
2585                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2586                 csig->params [1] = &mono_defaults.string_class->byval_arg;
2587                 add_method (acfg, get_runtime_invoke_sig (csig));
2588
2589                 /* string runtime-invoke () [Exception.ToString ()] */
2590                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2591                 csig->hasthis = 1;
2592                 csig->ret = &mono_defaults.string_class->byval_arg;
2593                 add_method (acfg, get_runtime_invoke_sig (csig));
2594
2595                 /* void runtime-invoke (string, Exception) [exception ctor] */
2596                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2597                 csig->hasthis = 1;
2598                 csig->ret = &mono_defaults.void_class->byval_arg;
2599                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2600                 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2601                 add_method (acfg, get_runtime_invoke_sig (csig));
2602
2603                 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2604                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2605                 csig->hasthis = 1;
2606                 csig->ret = &(mono_class_from_name (
2607                                                                                         mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2608                 csig->params [0] = &mono_defaults.string_class->byval_arg;
2609                 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2610                 add_method (acfg, get_runtime_invoke_sig (csig));
2611
2612                 /* runtime-invoke used by finalizers */
2613                 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2614
2615                 /* This is used by mono_runtime_capture_context () */
2616                 method = mono_get_context_capture_method ();
2617                 if (method)
2618                         add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2619
2620 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2621                 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2622 #endif
2623
2624                 /* JIT icall wrappers */
2625                 /* FIXME: locking */
2626                 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2627
2628                 /* stelemref */
2629                 add_method (acfg, mono_marshal_get_stelemref ());
2630
2631 #ifdef MONO_ARCH_HAVE_TLS_GET
2632                 /* Managed Allocators */
2633                 nallocators = mono_gc_get_managed_allocator_types ();
2634                 for (i = 0; i < nallocators; ++i) {
2635                         m = mono_gc_get_managed_allocator_by_type (i);
2636                         if (m)
2637                                 add_method (acfg, m);
2638                 }
2639
2640                 /* Monitor Enter/Exit */
2641                 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2642                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2643                 g_assert (orig_method);
2644                 mono_method_desc_free (desc);
2645                 method = mono_monitor_get_fast_path (orig_method);
2646                 if (method)
2647                         add_method (acfg, method);
2648
2649                 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2650                 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2651                 g_assert (orig_method);
2652                 mono_method_desc_free (desc);
2653                 method = mono_monitor_get_fast_path (orig_method);
2654                 if (method)
2655                         add_method (acfg, method);
2656 #endif
2657
2658                 /* Stelemref wrappers */
2659                 /* There is only a constant number of these, iterating over all types should handle them all */
2660                 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2661                         MonoClass *klass;
2662                 
2663                         token = MONO_TOKEN_TYPE_DEF | (i + 1);
2664                         klass = mono_class_get (acfg->image, token);
2665                         if (klass)
2666                                 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2667                 }
2668
2669                 /* castclass_with_check wrapper */
2670                 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2671         }
2672
2673         /* 
2674          * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2675          * we use the original method instead at runtime.
2676          * Since full-aot doesn't support remoting, this is not a problem.
2677          */
2678 #if 0
2679         /* remoting-invoke wrappers */
2680         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2681                 MonoMethodSignature *sig;
2682                 
2683                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2684                 method = mono_get_method (acfg->image, token, NULL);
2685
2686                 sig = mono_method_signature (method);
2687
2688                 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2689                         m = mono_marshal_get_remoting_invoke_with_check (method);
2690
2691                         add_method (acfg, m);
2692                 }
2693         }
2694 #endif
2695
2696         /* delegate-invoke wrappers */
2697         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2698                 MonoClass *klass;
2699                 
2700                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2701                 klass = mono_class_get (acfg->image, token);
2702
2703                 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2704                         method = mono_get_delegate_invoke (klass);
2705
2706                         m = mono_marshal_get_delegate_invoke (method, NULL);
2707
2708                         add_method (acfg, m);
2709
2710                         method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2711                         add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2712
2713                         method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2714                         add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2715                 }
2716         }
2717
2718         /* Synchronized wrappers */
2719         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2720                 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2721                 method = mono_get_method (acfg->image, token, NULL);
2722
2723                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2724                         add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2725         }
2726
2727         /* pinvoke wrappers */
2728         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2729                 MonoMethod *method;
2730                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2731
2732                 method = mono_get_method (acfg->image, token, NULL);
2733
2734                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2735                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2736                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2737                 }
2738         }
2739  
2740         /* native-to-managed wrappers */
2741         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2742                 MonoMethod *method;
2743                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2744                 MonoCustomAttrInfo *cattr;
2745                 int j;
2746
2747                 method = mono_get_method (acfg->image, token, NULL);
2748
2749                 /* 
2750                  * Only generate native-to-managed wrappers for methods which have an
2751                  * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2752                  * name to avoid defining a new assembly to contain it.
2753                  */
2754                 cattr = mono_custom_attrs_from_method (method);
2755
2756                 if (cattr) {
2757                         for (j = 0; j < cattr->num_attrs; ++j)
2758                                 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2759                                         break;
2760                         if (j < cattr->num_attrs) {
2761                                 MonoCustomAttrEntry *e = &cattr->attrs [j];
2762                                 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2763                                 const char *p = (const char*)e->data;
2764                                 int slen;
2765                                 char *n;
2766                                 MonoType *t;
2767                                 MonoClass *klass;
2768
2769                                 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2770
2771                                 g_assert (sig->param_count == 1);
2772                                 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2773
2774                                 /* 
2775                                  * Decode the cattr manually since we can't create objects
2776                                  * during aot compilation.
2777                                  */
2778                                         
2779                                 /* Skip prolog */
2780                                 p += 2;
2781
2782                                 /* From load_cattr_value () in reflection.c */
2783                                 slen = mono_metadata_decode_value (p, &p);
2784                                 n = g_memdup (p, slen + 1);
2785                                 n [slen] = 0;
2786                                 t = mono_reflection_type_from_name (n, acfg->image);
2787                                 g_assert (t);
2788                                 g_free (n);
2789
2790                                 klass = mono_class_from_mono_type (t);
2791                                 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2792
2793                                 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2794                         }
2795                 }
2796
2797                 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2798                         (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2799                         add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2800                 }
2801         }
2802
2803         /* StructureToPtr/PtrToStructure wrappers */
2804         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2805                 MonoClass *klass;
2806                 
2807                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2808                 klass = mono_class_get (acfg->image, token);
2809
2810                 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2811                         add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2812                         add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2813                 }
2814         }
2815 }
2816
2817 static gboolean
2818 has_type_vars (MonoClass *klass)
2819 {
2820         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2821                 return TRUE;
2822         if (klass->rank)
2823                 return has_type_vars (klass->element_class);
2824         if (klass->generic_class) {
2825                 MonoGenericContext *context = &klass->generic_class->context;
2826                 if (context->class_inst) {
2827                         int i;
2828
2829                         for (i = 0; i < context->class_inst->type_argc; ++i)
2830                                 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2831                                         return TRUE;
2832                 }
2833         }
2834         return FALSE;
2835 }
2836
2837 static gboolean
2838 method_has_type_vars (MonoMethod *method)
2839 {
2840         if (has_type_vars (method->klass))
2841                 return TRUE;
2842
2843         if (method->is_inflated) {
2844                 MonoGenericContext *context = mono_method_get_context (method);
2845                 if (context->method_inst) {
2846                         int i;
2847
2848                         for (i = 0; i < context->method_inst->type_argc; ++i)
2849                                 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2850                                         return TRUE;
2851                 }
2852         }
2853         return FALSE;
2854 }
2855
2856 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2857
2858 static void
2859 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2860 {
2861         /* This might lead to a huge code blowup so only do it if neccesary */
2862         if (!acfg->aot_opts.full_aot && !force)
2863                 return;
2864
2865         add_generic_class_with_depth (acfg, klass, 0);
2866 }
2867
2868 static gboolean
2869 check_type_depth (MonoType *t, int depth)
2870 {
2871         int i;
2872
2873         if (depth > 8)
2874                 return TRUE;
2875
2876         switch (t->type) {
2877         case MONO_TYPE_GENERICINST: {
2878                 MonoGenericClass *gklass = t->data.generic_class;
2879                 MonoGenericInst *ginst = gklass->context.class_inst;
2880
2881                 if (ginst) {
2882                         for (i = 0; i < ginst->type_argc; ++i) {
2883                                 if (check_type_depth (ginst->type_argv [i], depth + 1))
2884                                         return TRUE;
2885                         }
2886                 }
2887                 break;
2888         }
2889         default:
2890                 break;
2891         }
2892
2893         return FALSE;
2894 }
2895
2896 /*
2897  * add_generic_class:
2898  *
2899  *   Add all methods of a generic class.
2900  */
2901 static void
2902 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2903 {
2904         MonoMethod *method;
2905         gpointer iter;
2906
2907         mono_class_init (klass);
2908
2909         if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2910                 return;
2911
2912         if (has_type_vars (klass))
2913                 return;
2914
2915         if (!klass->generic_class && !klass->rank)
2916                 return;
2917
2918         if (check_type_depth (&klass->byval_arg, 0))
2919                 return;
2920
2921         iter = NULL;
2922         while ((method = mono_class_get_methods (klass, &iter))) {
2923                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2924                         /* Already added */
2925                         continue;
2926
2927                 if (method->is_generic)
2928                         /* FIXME: */
2929                         continue;
2930
2931                 /*
2932                  * FIXME: Instances which are referenced by these methods are not added,
2933                  * for example Array.Resize<int> for List<int>.Add ().
2934                  */
2935                 add_extra_method_with_depth (acfg, method, depth + 1);
2936         }
2937
2938         if (klass->delegate) {
2939                 method = mono_get_delegate_invoke (klass);
2940
2941                 method = mono_marshal_get_delegate_invoke (method, NULL);
2942
2943                 add_method (acfg, method);
2944         }
2945
2946         /* 
2947          * For ICollection<T>, add instances of the helper methods
2948          * in Array, since a T[] could be cast to ICollection<T>.
2949          */
2950         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2951                 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2952                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2953                 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2954                 gpointer iter;
2955                 char *name_prefix;
2956
2957                 if (!strcmp (klass->name, "IEnumerator`1"))
2958                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2959                 else
2960                         name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2961
2962                 /* Add the T[]/InternalEnumerator class */
2963                 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2964                         MonoClass *nclass;
2965
2966                         iter = NULL;
2967                         while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2968                                 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2969                                         break;
2970                         }
2971                         g_assert (nclass);
2972                         nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2973                         add_generic_class (acfg, nclass, FALSE);
2974                 }
2975
2976                 iter = NULL;
2977                 while ((method = mono_class_get_methods (array_class, &iter))) {
2978                         if (strstr (method->name, name_prefix)) {
2979                                 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2980                                 add_extra_method_with_depth (acfg, m, depth);
2981                         }
2982                 }
2983
2984                 g_free (name_prefix);
2985         }
2986
2987         /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2988         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2989                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2990                 MonoClass *icomparable, *gcomparer;
2991                 MonoGenericContext ctx;
2992                 MonoType *args [16];
2993
2994                 memset (&ctx, 0, sizeof (ctx));
2995
2996                 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2997                 g_assert (icomparable);
2998                 args [0] = &tclass->byval_arg;
2999                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3000
3001                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3002                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3003                         g_assert (gcomparer);
3004                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3005                 }
3006         }
3007
3008         /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3009         if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3010                 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3011                 MonoClass *iface, *gcomparer;
3012                 MonoGenericContext ctx;
3013                 MonoType *args [16];
3014
3015                 memset (&ctx, 0, sizeof (ctx));
3016
3017                 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3018                 g_assert (iface);
3019                 args [0] = &tclass->byval_arg;
3020                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3021
3022                 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3023                         gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3024                         g_assert (gcomparer);
3025                         add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3026                 }
3027         }
3028 }
3029
3030 static void
3031 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3032 {
3033         int i;
3034         MonoGenericContext ctx;
3035         MonoType *args [16];
3036
3037         memset (&ctx, 0, sizeof (ctx));
3038
3039         for (i = 0; i < ninsts; ++i) {
3040                 args [0] = insts [i];
3041                 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3042                 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3043         }
3044 }
3045
3046 /*
3047  * add_generic_instances:
3048  *
3049  *   Add instances referenced by the METHODSPEC/TYPESPEC table.
3050  */
3051 static void
3052 add_generic_instances (MonoAotCompile *acfg)
3053 {
3054         int i;
3055         guint32 token;
3056         MonoMethod *method;
3057         MonoMethodHeader *header;
3058         MonoMethodSignature *sig;
3059         MonoGenericContext *context;
3060
3061         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3062                 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3063                 method = mono_get_method (acfg->image, token, NULL);
3064
3065                 if (!method)
3066                         continue;
3067
3068                 if (method->klass->image != acfg->image)
3069                         continue;
3070
3071                 context = mono_method_get_context (method);
3072
3073                 if (context && ((context->class_inst && context->class_inst->is_open)))
3074                         continue;
3075
3076                 /*
3077                  * For open methods, create an instantiation which can be passed to the JIT.
3078                  * FIXME: Handle class_inst as well.
3079                  */
3080                 if (context && context->method_inst && context->method_inst->is_open) {
3081                         MonoGenericContext shared_context;
3082                         MonoGenericInst *inst;
3083                         MonoType **type_argv;
3084                         int i;
3085                         MonoMethod *declaring_method;
3086                         gboolean supported = TRUE;
3087
3088                         /* Check that the context doesn't contain open constructed types */
3089                         if (context->class_inst) {
3090                                 inst = context->class_inst;
3091                                 for (i = 0; i < inst->type_argc; ++i) {
3092                                         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)
3093                                                 continue;
3094                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3095                                                 supported = FALSE;
3096                                 }
3097                         }
3098                         if (context->method_inst) {
3099                                 inst = context->method_inst;
3100                                 for (i = 0; i < inst->type_argc; ++i) {
3101                                         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)
3102                                                 continue;
3103                                         if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3104                                                 supported = FALSE;
3105                                 }
3106                         }
3107
3108                         if (!supported)
3109                                 continue;
3110
3111                         memset (&shared_context, 0, sizeof (MonoGenericContext));
3112
3113                         inst = context->class_inst;
3114                         if (inst) {
3115                                 type_argv = g_new0 (MonoType*, inst->type_argc);
3116                                 for (i = 0; i < inst->type_argc; ++i) {
3117                                         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)
3118                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
3119                                         else
3120                                                 type_argv [i] = inst->type_argv [i];
3121                                 }
3122                                 
3123                                 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3124                                 g_free (type_argv);
3125                         }
3126
3127                         inst = context->method_inst;
3128                         if (inst) {
3129                                 type_argv = g_new0 (MonoType*, inst->type_argc);
3130                                 for (i = 0; i < inst->type_argc; ++i) {
3131                                         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)
3132                                                 type_argv [i] = &mono_defaults.object_class->byval_arg;
3133                                         else
3134                                                 type_argv [i] = inst->type_argv [i];
3135                                 }
3136
3137                                 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3138                                 g_free (type_argv);
3139                         }
3140
3141                         if (method->is_generic || method->klass->generic_container)
3142                                 declaring_method = method;
3143                         else
3144                                 declaring_method = mono_method_get_declaring_generic_method (method);
3145
3146                         method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3147                 }
3148
3149                 /* 
3150                  * If the method is fully sharable, it was already added in place of its
3151                  * generic definition.
3152                  */
3153                 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3154                         continue;
3155
3156                 /*
3157                  * FIXME: Partially shared methods are not shared here, so we end up with
3158                  * many identical methods.
3159                  */
3160                 add_extra_method (acfg, method);
3161         }
3162
3163         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3164                 MonoClass *klass;
3165
3166                 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3167
3168                 klass = mono_class_get (acfg->image, token);
3169                 if (!klass || klass->rank)
3170                         continue;
3171
3172                 add_generic_class (acfg, klass, FALSE);
3173         }
3174
3175         /* Add types of args/locals */
3176         for (i = 0; i < acfg->methods->len; ++i) {
3177                 int j, depth;
3178
3179                 method = g_ptr_array_index (acfg->methods, i);
3180
3181                 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3182
3183                 sig = mono_method_signature (method);
3184
3185                 if (sig) {
3186                         for (j = 0; j < sig->param_count; ++j)
3187                                 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3188                                         add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3189                 }
3190
3191                 header = mono_method_get_header (method);
3192
3193                 if (header) {
3194                         for (j = 0; j < header->num_locals; ++j)
3195                                 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3196                                         add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3197                 }
3198         }
3199
3200         if (acfg->image == mono_defaults.corlib) {
3201                 MonoClass *klass;
3202                 MonoType *insts [256];
3203                 int ninsts = 0;
3204
3205                 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3206                 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3207                 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3208                 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3209                 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3210                 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3211                 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3212                 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3213                 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3214                 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3215                 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3216                 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3217
3218                 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3219                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3220                 if (klass)
3221                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3222                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3223                 if (klass)
3224                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3225
3226                 /* Add instances of the array generic interfaces for primitive types */
3227                 /* This will add instances of the InternalArray_ helper methods in Array too */
3228                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3229                 if (klass)
3230                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3231                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3232                 if (klass)
3233                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3234                 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3235                 if (klass)
3236                         add_instances_of (acfg, klass, insts, ninsts, TRUE);
3237
3238                 /* 
3239                  * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3240                  * used for all instances of GetGenericValueImpl by the AOT runtime.
3241                  */
3242                 {
3243                         MonoGenericContext ctx;
3244                         MonoType *args [16];
3245                         MonoMethod *get_method;
3246                         MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3247
3248                         get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3249
3250                         if (get_method) {
3251                                 memset (&ctx, 0, sizeof (ctx));
3252                                 args [0] = &mono_defaults.object_class->byval_arg;
3253                                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3254                                 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3255                         }
3256                 }
3257
3258                 /* Same for CompareExchange<T> */
3259                 {
3260                         MonoGenericContext ctx;
3261                         MonoType *args [16];
3262                         MonoMethod *cas_method;
3263                         MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3264                         gpointer iter = NULL;
3265
3266                         while ((cas_method = mono_class_get_methods (interlocked_klass, &iter))) {
3267                                 if (!strcmp (cas_method->name, "CompareExchange") && cas_method->is_generic) {
3268                                         memset (&ctx, 0, sizeof (ctx));
3269                                         args [0] = &mono_defaults.object_class->byval_arg;
3270                                         ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3271                                         add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (cas_method, &ctx), TRUE, TRUE));
3272                                 }
3273                         }
3274                 }
3275         }
3276 }
3277
3278 /*
3279  * is_direct_callable:
3280  *
3281  *   Return whenever the method identified by JI is directly callable without 
3282  * going through the PLT.
3283  */
3284 static gboolean
3285 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3286 {
3287         if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3288                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3289                 if (callee_cfg) {
3290                         gboolean direct_callable = TRUE;
3291
3292                         if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3293                                 direct_callable = FALSE;
3294                         if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3295                                 // FIXME: Maybe call the wrapper directly ?
3296                                 direct_callable = FALSE;
3297
3298                         if (direct_callable)
3299                                 return TRUE;
3300                 }
3301         }
3302
3303         return FALSE;
3304 }
3305
3306 /*
3307  * emit_and_reloc_code:
3308  *
3309  *   Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3310  * is true, calls are made through the GOT too. This is used for emitting trampolines
3311  * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3312  * since trampolines are needed to make PTL work.
3313  */
3314 static void
3315 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3316 {
3317         int i, pindex, start_index, method_index;
3318         GPtrArray *patches;
3319         MonoJumpInfo *patch_info;
3320         MonoMethodHeader *header;
3321         gboolean skip, direct_call;
3322         guint32 got_slot;
3323         char direct_call_target [1024];
3324
3325         if (method) {
3326                 header = mono_method_get_header (method);
3327
3328                 method_index = get_method_index (acfg, method);
3329         }
3330
3331         /* Collect and sort relocations */
3332         patches = g_ptr_array_new ();
3333         for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3334                 g_ptr_array_add (patches, patch_info);
3335         g_ptr_array_sort (patches, compare_patches);
3336
3337         start_index = 0;
3338         for (i = 0; i < code_len; i++) {
3339                 patch_info = NULL;
3340                 for (pindex = start_index; pindex < patches->len; ++pindex) {
3341                         patch_info = g_ptr_array_index (patches, pindex);
3342                         if (patch_info->ip.i >= i)
3343                                 break;
3344                 }
3345
3346 #ifdef MONO_ARCH_AOT_SUPPORTED
3347                 skip = FALSE;
3348                 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3349                         start_index = pindex;
3350
3351                         switch (patch_info->type) {
3352                         case MONO_PATCH_INFO_NONE:
3353                                 break;
3354                         case MONO_PATCH_INFO_GOT_OFFSET: {
3355                                 int code_size;
3356  
3357                                 arch_emit_got_offset (acfg, code + i, &code_size);
3358                                 i += code_size - 1;
3359                                 skip = TRUE;
3360                                 patch_info->type = MONO_PATCH_INFO_NONE;
3361                                 break;
3362                         }
3363                         default: {
3364                                 /*
3365                                  * If this patch is a call, try emitting a direct call instead of
3366                                  * through a PLT entry. This is possible if the called method is in
3367                                  * the same assembly and requires no initialization.
3368                                  */
3369                                 direct_call = FALSE;
3370                                 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3371                                         if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3372                                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3373                                                 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3374                                                 direct_call = TRUE;
3375                                                 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3376                                                 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3377                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3378                                                 acfg->stats.direct_calls ++;
3379                                         }
3380
3381                                         acfg->stats.all_calls ++;
3382                                 }
3383
3384                                 if (!got_only && !direct_call) {
3385                                         MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3386                                         if (plt_entry) {
3387                                                 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3388                                                 direct_call = TRUE;
3389                                                 sprintf (direct_call_target, "%s", plt_entry->symbol);
3390                 
3391                                                 /* Nullify the patch */
3392                                                 patch_info->type = MONO_PATCH_INFO_NONE;
3393                                                 plt_entry->jit_used = TRUE;
3394                                         }
3395                                 }
3396
3397                                 if (direct_call) {
3398                                         int call_size;
3399
3400                                         arch_emit_direct_call (acfg, direct_call_target, &call_size);
3401                                         i += call_size - 1;
3402                                 } else {
3403                                         int code_size;
3404
3405                                         got_slot = get_got_offset (acfg, patch_info);
3406
3407                                         arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3408                                         i += code_size - 1;
3409                                 }
3410                                 skip = TRUE;
3411                         }
3412                         }
3413                 }
3414 #endif /* MONO_ARCH_AOT_SUPPORTED */
3415
3416                 if (!skip) {
3417                         /* Find next patch */
3418                         patch_info = NULL;
3419                         for (pindex = start_index; pindex < patches->len; ++pindex) {
3420                                 patch_info = g_ptr_array_index (patches, pindex);
3421                                 if (patch_info->ip.i >= i)
3422                                         break;
3423                         }
3424
3425                         /* Try to emit multiple bytes at once */
3426                         if (pindex < patches->len && patch_info->ip.i > i) {
3427                                 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3428                                 i = patch_info->ip.i - 1;
3429                         } else {
3430                                 emit_bytes (acfg, code + i, 1);
3431                         }
3432                 }
3433         }
3434 }
3435
3436 /*
3437  * sanitize_symbol:
3438  *
3439  *   Modify SYMBOL so it only includes characters permissible in symbols.
3440  */
3441 static void
3442 sanitize_symbol (char *symbol)
3443 {
3444         int i, len = strlen (symbol);
3445
3446         for (i = 0; i < len; ++i)
3447                 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3448                         symbol [i] = '_';
3449 }
3450
3451 static char*
3452 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3453 {
3454         char *name1, *name2, *cached;
3455         int i, j, len, count;
3456
3457         name1 = mono_method_full_name (method, TRUE);
3458         len = strlen (name1);
3459         name2 = malloc (strlen (prefix) + len + 16);
3460         memcpy (name2, prefix, strlen (prefix));
3461         j = strlen (prefix);
3462         for (i = 0; i < len; ++i) {
3463                 if (isalnum (name1 [i])) {
3464                         name2 [j ++] = name1 [i];
3465                 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3466                         i += 2;
3467                 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3468                         name2 [j ++] = '_';
3469                         i++;
3470                 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3471                 } else
3472                         name2 [j ++] = '_';
3473         }
3474         name2 [j] = '\0';
3475
3476         g_free (name1);
3477
3478         count = 0;
3479         while (g_hash_table_lookup (cache, name2)) {
3480                 sprintf (name2 + j, "_%d", count);
3481                 count ++;
3482         }
3483
3484         cached = g_strdup (name2);
3485         g_hash_table_insert (cache, cached, cached);
3486
3487         return name2;
3488 }
3489
3490 static void
3491 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3492 {
3493         MonoMethod *method;
3494         int method_index;
3495         guint8 *code;
3496         char *debug_sym = NULL;
3497         char symbol [128];
3498         int func_alignment = AOT_FUNC_ALIGNMENT;
3499         MonoMethodHeader *header;
3500
3501         method = cfg->orig_method;
3502         code = cfg->native_code;
3503         header = cfg->header;
3504
3505         method_index = get_method_index (acfg, method);
3506
3507         /* Make the labels local */
3508         sprintf (symbol, "%s", cfg->asm_symbol);
3509
3510         emit_section_change (acfg, ".text", 0);
3511         emit_alignment (acfg, func_alignment);
3512         emit_label (acfg, symbol);
3513
3514         if (acfg->aot_opts.write_symbols) {
3515                 /* 
3516                  * Write a C style symbol for every method, this has two uses:
3517                  * - it works on platforms where the dwarf debugging info is not
3518                  *   yet supported.
3519                  * - it allows the setting of breakpoints of aot-ed methods.
3520                  */
3521                 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3522
3523                 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3524                 if (acfg->need_no_dead_strip)
3525                         fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
3526                 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3527                 emit_label (acfg, debug_sym);
3528         }
3529
3530         if (cfg->verbose_level > 0)
3531                 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3532
3533         acfg->stats.code_size += cfg->code_len;
3534
3535         acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3536
3537         emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3538
3539         emit_line (acfg);
3540
3541         if (acfg->aot_opts.write_symbols) {
3542                 emit_symbol_size (acfg, debug_sym, ".");
3543                 g_free (debug_sym);
3544         }
3545
3546         sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3547         emit_label (acfg, symbol);
3548 }
3549
3550 /**
3551  * encode_patch:
3552  *
3553  *  Encode PATCH_INFO into its disk representation.
3554  */
3555 static void
3556 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3557 {
3558         guint8 *p = buf;
3559
3560         switch (patch_info->type) {
3561         case MONO_PATCH_INFO_NONE:
3562                 break;
3563         case MONO_PATCH_INFO_IMAGE:
3564                 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3565                 break;
3566         case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3567         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3568         case MONO_PATCH_INFO_CASTCLASS_CACHE:
3569                 break;
3570         case MONO_PATCH_INFO_METHOD_REL:
3571                 encode_value ((gint)patch_info->data.offset, p, &p);
3572                 break;
3573         case MONO_PATCH_INFO_SWITCH: {
3574                 gpointer *table = (gpointer *)patch_info->data.table->table;
3575                 int k;
3576
3577                 encode_value (patch_info->data.table->table_size, p, &p);
3578                 for (k = 0; k < patch_info->data.table->table_size; k++)
3579                         encode_value ((int)(gssize)table [k], p, &p);
3580                 break;
3581         }
3582         case MONO_PATCH_INFO_METHODCONST:
3583         case MONO_PATCH_INFO_METHOD:
3584         case MONO_PATCH_INFO_METHOD_JUMP:
3585         case MONO_PATCH_INFO_ICALL_ADDR:
3586         case MONO_PATCH_INFO_METHOD_RGCTX:
3587                 encode_method_ref (acfg, patch_info->data.method, p, &p);
3588                 break;
3589         case MONO_PATCH_INFO_INTERNAL_METHOD:
3590         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3591                 guint32 len = strlen (patch_info->data.name);
3592
3593                 encode_value (len, p, &p);
3594
3595                 memcpy (p, patch_info->data.name, len);
3596                 p += len;
3597                 *p++ = '\0';
3598                 break;
3599         }
3600         case MONO_PATCH_INFO_LDSTR: {
3601                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3602                 guint32 token = patch_info->data.token->token;
3603                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3604                 encode_value (image_index, p, &p);
3605                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3606                 break;
3607         }
3608         case MONO_PATCH_INFO_RVA:
3609         case MONO_PATCH_INFO_DECLSEC:
3610         case MONO_PATCH_INFO_LDTOKEN:
3611         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3612                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3613                 encode_value (patch_info->data.token->token, p, &p);
3614                 encode_value (patch_info->data.token->has_context, p, &p);
3615                 if (patch_info->data.token->has_context)
3616                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3617                 break;
3618         case MONO_PATCH_INFO_EXC_NAME: {
3619                 MonoClass *ex_class;
3620
3621                 ex_class =
3622                         mono_class_from_name (mono_defaults.exception_class->image,
3623                                                                   "System", patch_info->data.target);
3624                 g_assert (ex_class);
3625                 encode_klass_ref (acfg, ex_class, p, &p);
3626                 break;
3627         }
3628         case MONO_PATCH_INFO_R4:
3629                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3630                 break;
3631         case MONO_PATCH_INFO_R8:
3632                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3633                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3634                 break;
3635         case MONO_PATCH_INFO_VTABLE:
3636         case MONO_PATCH_INFO_CLASS:
3637         case MONO_PATCH_INFO_IID:
3638         case MONO_PATCH_INFO_ADJUSTED_IID:
3639                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3640                 break;
3641         case MONO_PATCH_INFO_CLASS_INIT:
3642         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3643                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3644                 break;
3645         case MONO_PATCH_INFO_FIELD:
3646         case MONO_PATCH_INFO_SFLDA:
3647                 encode_field_info (acfg, patch_info->data.field, p, &p);
3648                 break;
3649         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3650                 break;
3651         case MONO_PATCH_INFO_RGCTX_FETCH: {
3652                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3653
3654                 encode_method_ref (acfg, entry->method, p, &p);
3655                 encode_value (entry->in_mrgctx, p, &p);
3656                 encode_value (entry->info_type, p, &p);
3657                 encode_value (entry->data->type, p, &p);
3658                 encode_patch (acfg, entry->data, p, &p);
3659                 break;
3660         }
3661         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3662         case MONO_PATCH_INFO_MONITOR_ENTER:
3663         case MONO_PATCH_INFO_MONITOR_EXIT:
3664         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3665                 break;
3666         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3667                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3668                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3669                 break;
3670         default:
3671                 g_warning ("unable to handle jump info %d", patch_info->type);
3672                 g_assert_not_reached ();
3673         }
3674
3675         *endbuf = p;
3676 }
3677
3678 static void
3679 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3680 {
3681         guint8 *p = buf;
3682         guint32 pindex, offset;
3683         MonoJumpInfo *patch_info;
3684
3685         encode_value (n_patches, p, &p);
3686
3687         for (pindex = 0; pindex < patches->len; ++pindex) {
3688                 patch_info = g_ptr_array_index (patches, pindex);
3689
3690                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3691                         /* Nothing to do */
3692                         continue;
3693
3694                 offset = get_got_offset (acfg, patch_info);
3695                 encode_value (offset, p, &p);
3696         }
3697
3698         *endbuf = p;
3699 }
3700
3701 static void
3702 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3703 {
3704         MonoMethod *method;
3705         GList *l;
3706         int pindex, buf_size, n_patches;
3707         guint8 *code;
3708         GPtrArray *patches;
3709         MonoJumpInfo *patch_info;
3710         MonoMethodHeader *header;
3711         guint32 method_index;
3712         guint8 *p, *buf;
3713         guint32 first_got_offset;
3714
3715         method = cfg->orig_method;
3716         code = cfg->native_code;
3717         header = mono_method_get_header (method);
3718
3719         method_index = get_method_index (acfg, method);
3720
3721         /* Sort relocations */
3722         patches = g_ptr_array_new ();
3723         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3724                 g_ptr_array_add (patches, patch_info);
3725         g_ptr_array_sort (patches, compare_patches);
3726
3727         first_got_offset = acfg->cfgs [method_index]->got_offset;
3728
3729         /**********************/
3730         /* Encode method info */
3731         /**********************/
3732
3733         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3734         p = buf = g_malloc (buf_size);
3735
3736         if (mono_class_get_cctor (method->klass))
3737                 encode_klass_ref (acfg, method->klass, p, &p);
3738         else
3739                 /* Not needed when loading the method */
3740                 encode_value (0, p, &p);
3741
3742         /* String table */
3743         if (cfg->opt & MONO_OPT_SHARED) {
3744                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3745                 for (l = cfg->ldstr_list; l; l = l->next) {
3746                         encode_value ((long)l->data, p, &p);
3747                 }
3748         }
3749         else
3750                 /* Used only in shared mode */
3751                 g_assert (!cfg->ldstr_list);
3752
3753         n_patches = 0;
3754         for (pindex = 0; pindex < patches->len; ++pindex) {
3755                 patch_info = g_ptr_array_index (patches, pindex);
3756                 
3757                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3758                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
3759                         patch_info->type = MONO_PATCH_INFO_NONE;
3760                         /* Nothing to do */
3761                         continue;
3762                 }
3763
3764                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3765                         /* Stored in a GOT slot initialized at module load time */
3766                         patch_info->type = MONO_PATCH_INFO_NONE;
3767                         continue;
3768                 }
3769
3770                 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3771                         /* Stored in a GOT slot initialized at module load time */
3772                         patch_info->type = MONO_PATCH_INFO_NONE;
3773                         continue;
3774                 }
3775
3776                 if (is_plt_patch (patch_info)) {
3777                         /* Calls are made through the PLT */
3778                         patch_info->type = MONO_PATCH_INFO_NONE;
3779                         continue;
3780                 }
3781
3782                 n_patches ++;
3783         }
3784
3785         if (n_patches)
3786                 g_assert (cfg->has_got_slots);
3787
3788         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3789
3790         acfg->stats.info_size += p - buf;
3791
3792         g_assert (p - buf < buf_size);
3793
3794         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3795         g_free (buf);
3796 }
3797
3798 static guint32
3799 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3800 {
3801         guint32 cache_index;
3802         guint32 offset;
3803
3804         /* Reuse the unwind module to canonize and store unwind info entries */
3805         cache_index = mono_cache_unwind_info (encoded, encoded_len);
3806
3807         /* Use +/- 1 to distinguish 0s from missing entries */
3808         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3809         if (offset)
3810                 return offset - 1;
3811         else {
3812                 guint8 buf [16];
3813                 guint8 *p;
3814
3815                 /* 
3816                  * It would be easier to use assembler symbols, but the caller needs an
3817                  * offset now.
3818                  */
3819                 offset = acfg->unwind_info_offset;
3820                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3821                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3822
3823                 p = buf;
3824                 encode_value (encoded_len, p, &p);
3825
3826                 acfg->unwind_info_offset += encoded_len + (p - buf);
3827                 return offset;
3828         }
3829 }
3830
3831 static void
3832 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3833 {
3834         MonoMethod *method;
3835         int i, k, buf_size, method_index;
3836         guint32 debug_info_size;
3837         guint8 *code;
3838         MonoMethodHeader *header;
3839         guint8 *p, *buf, *debug_info;
3840         MonoJitInfo *jinfo = cfg->jit_info;
3841         guint32 flags;
3842         gboolean use_unwind_ops = FALSE;
3843         MonoSeqPointInfo *seq_points;
3844
3845         method = cfg->orig_method;
3846         code = cfg->native_code;
3847         header = cfg->header;
3848
3849         method_index = get_method_index (acfg, method);
3850
3851         if (!acfg->aot_opts.nodebug) {
3852                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3853         } else {
3854                 debug_info = NULL;
3855                 debug_info_size = 0;
3856         }
3857
3858         seq_points = cfg->seq_point_info;
3859
3860         buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3861         p = buf = g_malloc (buf_size);
3862
3863 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3864         use_unwind_ops = cfg->unwind_ops != NULL;
3865 #endif
3866
3867         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);
3868
3869         encode_value (flags, p, &p);
3870
3871         if (use_unwind_ops) {
3872                 guint32 encoded_len;
3873                 guint8 *encoded;
3874
3875                 /* 
3876                  * This is a duplicate of the data in the .debug_frame section, but that
3877                  * section cannot be accessed using the dl interface.
3878                  */
3879                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3880                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3881                 g_free (encoded);
3882         } else {
3883                 encode_value (jinfo->used_regs, p, &p);
3884         }
3885
3886         /*Encode the number of holes before the number of clauses to make decoding easier*/
3887         if (jinfo->has_try_block_holes) {
3888                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3889                 encode_value (table->num_holes, p, &p);
3890         }
3891
3892         /* Exception table */
3893         if (cfg->compile_llvm) {
3894                 /*
3895                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3896                  * since the information is only available to llc. Instead, we let llc save the data
3897                  * into the LSDA, and read it from there at runtime.
3898                  */
3899                 /* The assembly might be CIL stripped so emit the data ourselves */
3900                 if (header->num_clauses)
3901                         encode_value (header->num_clauses, p, &p);
3902
3903                 for (k = 0; k < header->num_clauses; ++k) {
3904                         MonoExceptionClause *clause;
3905
3906                         clause = &header->clauses [k];
3907
3908                         encode_value (clause->flags, p, &p);
3909                         if (clause->data.catch_class) {
3910                                 encode_value (1, p, &p);
3911                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3912                         } else {
3913                                 encode_value (0, p, &p);
3914                         }
3915
3916                         /* Emit a list of nesting clauses */
3917                         for (i = 0; i < header->num_clauses; ++i) {
3918                                 gint32 cindex1 = k;
3919                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3920                                 gint32 cindex2 = i;
3921                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3922
3923                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3924                                         encode_value (i, p, &p);
3925                         }
3926                         encode_value (-1, p, &p);
3927                 }
3928         } else {
3929                 if (jinfo->num_clauses)
3930                         encode_value (jinfo->num_clauses, p, &p);
3931
3932                 for (k = 0; k < jinfo->num_clauses; ++k) {
3933                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3934
3935                         encode_value (ei->flags, p, &p);
3936                         encode_value (ei->exvar_offset, p, &p);
3937
3938                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3939                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3940                         else {
3941                                 if (ei->data.catch_class) {
3942                                         encode_value (1, p, &p);
3943                                         encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3944                                 } else {
3945                                         encode_value (0, p, &p);
3946                                 }
3947                         }
3948
3949                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3950                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3951                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3952                 }
3953         }
3954
3955         if (jinfo->has_generic_jit_info) {
3956                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3957
3958                 if (!cfg->compile_llvm) {
3959                         encode_value (gi->has_this ? 1 : 0, p, &p);
3960                         encode_value (gi->this_reg, p, &p);
3961                         encode_value (gi->this_offset, p, &p);
3962                 }
3963
3964                 /* 
3965                  * Need to encode jinfo->method too, since it is not equal to 'method'
3966                  * when using generic sharing.
3967                  */
3968                 encode_method_ref (acfg, jinfo->method, p, &p);
3969         }
3970
3971         if (jinfo->has_try_block_holes) {
3972                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3973                 for (i = 0; i < table->num_holes; ++i) {
3974                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3975                         encode_value (hole->clause, p, &p);
3976                         encode_value (hole->length, p, &p);
3977                         encode_value (hole->offset, p, &p);
3978                 }
3979         }
3980
3981         if (seq_points) {
3982                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3983
3984                 encode_value (seq_points->len, p, &p);
3985                 last_il_offset = last_native_offset = 0;
3986                 for (i = 0; i < seq_points->len; ++i) {
3987                         SeqPoint *sp = &seq_points->seq_points [i];
3988                         il_offset = sp->il_offset;
3989                         native_offset = sp->native_offset;
3990                         encode_value (il_offset - last_il_offset, p, &p);
3991                         encode_value (native_offset - last_native_offset, p, &p);
3992                         last_il_offset = il_offset;
3993                         last_native_offset = native_offset;
3994
3995                         encode_value (sp->next_len, p, &p);
3996                         for (j = 0; j < sp->next_len; ++j)
3997                                 encode_value (sp->next [j], p, &p);
3998                 }
3999         }
4000                 
4001         g_assert (debug_info_size < buf_size);
4002
4003         encode_value (debug_info_size, p, &p);
4004         if (debug_info_size) {
4005                 memcpy (p, debug_info, debug_info_size);
4006                 p += debug_info_size;
4007                 g_free (debug_info);
4008         }
4009
4010         /* GC Map */
4011         if (cfg->gc_map) {
4012                 encode_value (cfg->gc_map_size, p, &p);
4013                 /* The GC map requires 4 bytes of alignment */
4014                 while ((gsize)p % 4)
4015                         p ++;
4016                 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4017                 p += cfg->gc_map_size;
4018         }
4019
4020         acfg->stats.ex_info_size += p - buf;
4021
4022         g_assert (p - buf < buf_size);
4023
4024         /* Emit info */
4025         /* The GC Map requires 4 byte alignment */
4026         cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4027         g_free (buf);
4028 }
4029
4030 static guint32
4031 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4032 {
4033         MonoClass *klass = mono_class_get (acfg->image, token);
4034         guint8 *p, *buf;
4035         int i, buf_size, res;
4036         gboolean no_special_static, cant_encode;
4037         gpointer iter = NULL;
4038
4039         if (!klass) {
4040                 buf_size = 16;
4041
4042                 p = buf = g_malloc (buf_size);
4043
4044                 /* Mark as unusable */
4045                 encode_value (-1, p, &p);
4046
4047                 res = add_to_blob (acfg, buf, p - buf);
4048                 g_free (buf);
4049
4050                 return res;
4051         }
4052                 
4053         buf_size = 10240 + (klass->vtable_size * 16);
4054         p = buf = g_malloc (buf_size);
4055
4056         g_assert (klass);
4057
4058         mono_class_init (klass);
4059
4060         mono_class_get_nested_types (klass, &iter);
4061         g_assert (klass->nested_classes_inited);
4062
4063         mono_class_setup_vtable (klass);
4064
4065         /* 
4066          * Emit all the information which is required for creating vtables so
4067          * the runtime does not need to create the MonoMethod structures which
4068          * take up a lot of space.
4069          */
4070
4071         no_special_static = !mono_class_has_special_static_fields (klass);
4072
4073         /* Check whenever we have enough info to encode the vtable */
4074         cant_encode = FALSE;
4075         for (i = 0; i < klass->vtable_size; ++i) {
4076                 MonoMethod *cm = klass->vtable [i];
4077
4078                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4079                         cant_encode = TRUE;
4080         }
4081
4082         if (klass->generic_container || cant_encode) {
4083                 encode_value (-1, p, &p);
4084         } else {
4085                 encode_value (klass->vtable_size, p, &p);
4086                 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);
4087                 if (klass->has_cctor)
4088                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4089                 if (klass->has_finalize)
4090                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4091  
4092                 encode_value (klass->instance_size, p, &p);
4093                 encode_value (mono_class_data_size (klass), p, &p);
4094                 encode_value (klass->packing_size, p, &p);
4095                 encode_value (klass->min_align, p, &p);
4096
4097                 for (i = 0; i < klass->vtable_size; ++i) {
4098                         MonoMethod *cm = klass->vtable [i];
4099
4100                         if (cm)
4101                                 encode_method_ref (acfg, cm, p, &p);
4102                         else
4103                                 encode_value (0, p, &p);
4104                 }
4105         }
4106
4107         acfg->stats.class_info_size += p - buf;
4108
4109         g_assert (p - buf < buf_size);
4110         res = add_to_blob (acfg, buf, p - buf);
4111         g_free (buf);
4112
4113         return res;
4114 }
4115
4116 static char*
4117 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4118 {
4119         char *debug_sym = NULL;
4120
4121         switch (ji->type) {
4122         case MONO_PATCH_INFO_METHOD:
4123                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4124                 break;
4125         case MONO_PATCH_INFO_INTERNAL_METHOD:
4126                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4127                 break;
4128         case MONO_PATCH_INFO_CLASS_INIT:
4129                 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4130                 sanitize_symbol (debug_sym);
4131                 break;
4132         case MONO_PATCH_INFO_RGCTX_FETCH:
4133                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4134                 break;
4135         case MONO_PATCH_INFO_ICALL_ADDR: {
4136                 char *s = get_debug_sym (ji->data.method, "", cache);
4137                 
4138                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4139                 g_free (s);
4140                 break;
4141         }
4142         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4143                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4144                 break;
4145         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4146                 debug_sym = g_strdup_printf ("plt__generic_class_init");
4147                 break;
4148         default:
4149                 break;
4150         }
4151
4152         return debug_sym;
4153 }
4154
4155 /*
4156  * Calls made from AOTed code are routed through a table of jumps similar to the
4157  * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4158  * control to the AOT runtime through a trampoline.
4159  */
4160 static void
4161 emit_plt (MonoAotCompile *acfg)
4162 {
4163         char symbol [128];
4164         int i;
4165         GHashTable *cache;
4166
4167         cache = g_hash_table_new (g_str_hash, g_str_equal);
4168
4169         emit_line (acfg);
4170         sprintf (symbol, "plt");
4171
4172         emit_section_change (acfg, ".text", 0);
4173         emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4174         emit_label (acfg, symbol);
4175         emit_label (acfg, acfg->plt_symbol);
4176
4177         for (i = 0; i < acfg->plt_offset; ++i) {
4178                 char *debug_sym = NULL;
4179                 MonoPltEntry *plt_entry = NULL;
4180                 MonoJumpInfo *ji;
4181
4182                 if (i == 0)
4183                         /* 
4184                          * The first plt entry is unused.
4185                          */
4186                         continue;
4187
4188                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4189                 ji = plt_entry->ji;
4190
4191                 if (acfg->llvm) {
4192                         /*
4193                          * If the target is directly callable, alias the plt symbol to point to
4194                          * the method code.
4195                          * FIXME: Use this to simplify emit_and_reloc_code ().
4196                          * FIXME: Avoid the got slot.
4197                          * FIXME: Add support to the binary writer.
4198                          */
4199                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4200                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4201
4202                                 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4203                                         /* LLVM calls the PLT entries using bl, so emit a stub */
4204                                         fprintf (acfg->fp, "\n.thumb_func\n");
4205                                         emit_label (acfg, plt_entry->llvm_symbol);
4206                                         fprintf (acfg->fp, "bx pc\n");
4207                                         fprintf (acfg->fp, "nop\n");
4208                                         fprintf (acfg->fp, ".arm\n");
4209                                         fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4210                                 } else {
4211                                         fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4212                                 }
4213                                 continue;
4214                         }
4215                 }
4216
4217                 if (acfg->aot_opts.write_symbols)
4218                         plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4219                 debug_sym = plt_entry->debug_sym;
4220
4221                 if (acfg->thumb_mixed && !plt_entry->jit_used)
4222                         /* Emit only a thumb version */
4223                         continue;
4224
4225                 if (!acfg->thumb_mixed)
4226                         emit_label (acfg, plt_entry->llvm_symbol);
4227
4228                 if (debug_sym) {
4229                         if (acfg->need_no_dead_strip)
4230                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4231                         emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4232                         emit_label (acfg, debug_sym);
4233                 }
4234
4235                 emit_label (acfg, plt_entry->symbol);
4236
4237                 arch_emit_plt_entry (acfg, i);
4238
4239                 if (debug_sym)
4240                         emit_symbol_size (acfg, debug_sym, ".");
4241         }
4242
4243         if (acfg->thumb_mixed) {
4244                 /* Make sure the ARM symbols don't alias the thumb ones */
4245                 emit_zero_bytes (acfg, 16);
4246
4247                 /* 
4248                  * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4249                  * code.
4250                  */
4251                 for (i = 0; i < acfg->plt_offset; ++i) {
4252                         char *debug_sym = NULL;
4253                         MonoPltEntry *plt_entry = NULL;
4254                         MonoJumpInfo *ji;
4255
4256                         if (i == 0)
4257                                 continue;
4258
4259                         plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4260                         ji = plt_entry->ji;
4261
4262                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4263                                 continue;
4264
4265                         /* Skip plt entries not actually called by LLVM code */
4266                         if (!plt_entry->llvm_used)
4267                                 continue;
4268
4269                         if (acfg->aot_opts.write_symbols) {
4270                                 if (plt_entry->debug_sym)
4271                                         debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4272                         }
4273
4274                         if (debug_sym) {
4275 #if defined(__APPLE__)
4276                                 fprintf (acfg->fp, "    .thumb_func %s\n", debug_sym);
4277                                 fprintf (acfg->fp, "    .no_dead_strip %s\n", debug_sym);
4278 #endif
4279                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4280                                 emit_label (acfg, debug_sym);
4281                         }
4282                         fprintf (acfg->fp, "\n.thumb_func\n");
4283
4284                         emit_label (acfg, plt_entry->llvm_symbol);
4285
4286                         arch_emit_llvm_plt_entry (acfg, i);
4287
4288                         if (debug_sym) {
4289                                 emit_symbol_size (acfg, debug_sym, ".");
4290                                 g_free (debug_sym);
4291                         }
4292                 }
4293         }
4294
4295         emit_symbol_size (acfg, acfg->plt_symbol, ".");
4296
4297         sprintf (symbol, "plt_end");
4298         emit_label (acfg, symbol);
4299
4300         g_hash_table_destroy (cache);
4301 }
4302
4303 static G_GNUC_UNUSED void
4304 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4305 {
4306         char start_symbol [256];
4307         char symbol [256];
4308         guint32 buf_size, info_offset;
4309         MonoJumpInfo *patch_info;
4310         guint8 *buf, *p;
4311         GPtrArray *patches;
4312         char *name;
4313         guint8 *code;
4314         guint32 code_size;
4315         MonoJumpInfo *ji;
4316         GSList *unwind_ops;
4317
4318         name = info->name;
4319         code = info->code;
4320         code_size = info->code_size;
4321         ji = info->ji;
4322         unwind_ops = info->unwind_ops;
4323
4324 #ifdef __native_client_codegen__
4325         mono_nacl_fix_patches (code, ji);
4326 #endif
4327
4328         /* Emit code */
4329
4330         sprintf (start_symbol, "%s", name);
4331
4332         emit_section_change (acfg, ".text", 0);
4333         emit_global (acfg, start_symbol, TRUE);
4334         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4335         emit_label (acfg, start_symbol);
4336
4337         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4338         emit_label (acfg, symbol);
4339
4340         /* 
4341          * The code should access everything through the GOT, so we pass
4342          * TRUE here.
4343          */
4344         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4345
4346         emit_symbol_size (acfg, start_symbol, ".");
4347
4348         /* Emit info */
4349
4350         /* Sort relocations */
4351         patches = g_ptr_array_new ();
4352         for (patch_info = ji; patch_info; patch_info = patch_info->next)
4353                 if (patch_info->type != MONO_PATCH_INFO_NONE)
4354                         g_ptr_array_add (patches, patch_info);
4355         g_ptr_array_sort (patches, compare_patches);
4356
4357         buf_size = patches->len * 128 + 128;
4358         buf = g_malloc (buf_size);
4359         p = buf;
4360
4361         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4362         g_assert (p - buf < buf_size);
4363
4364         sprintf (symbol, "%s_p", name);
4365
4366         info_offset = add_to_blob (acfg, buf, p - buf);
4367
4368         emit_section_change (acfg, RODATA_SECT, 0);
4369         emit_global (acfg, symbol, FALSE);
4370         emit_label (acfg, symbol);
4371
4372         emit_int32 (acfg, info_offset);
4373
4374         /* Emit debug info */
4375         if (unwind_ops) {
4376                 char symbol2 [256];
4377
4378                 sprintf (symbol, "%s", name);
4379                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4380
4381                 if (acfg->dwarf)
4382                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4383         }
4384 }
4385
4386 static void
4387 emit_trampolines (MonoAotCompile *acfg)
4388 {
4389         char symbol [256];
4390         int i, tramp_got_offset;
4391         MonoAotTrampoline ntype;
4392 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4393         int tramp_type;
4394         guint8 *code;
4395 #endif
4396
4397         if (!acfg->aot_opts.full_aot)
4398                 return;
4399         
4400         g_assert (acfg->image->assembly);
4401
4402         /* Currently, we emit most trampolines into the mscorlib AOT image. */
4403         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4404 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4405                 MonoTrampInfo *info;
4406
4407                 /*
4408                  * Emit the generic trampolines.
4409                  *
4410                  * We could save some code by treating the generic trampolines as a wrapper
4411                  * method, but that approach has its own complexities, so we choose the simpler
4412                  * method.
4413                  */
4414                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4415                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4416                         emit_trampoline (acfg, acfg->got_offset, info);
4417                 }
4418
4419                 mono_arch_get_nullified_class_init_trampoline (&info);
4420                 emit_trampoline (acfg, acfg->got_offset, info);
4421 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4422                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4423                 emit_trampoline (acfg, acfg->got_offset, info);
4424                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4425                 emit_trampoline (acfg, acfg->got_offset, info);
4426 #endif
4427
4428                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4429                 emit_trampoline (acfg, acfg->got_offset, info);
4430
4431                 /* Emit the exception related code pieces */
4432                 code = mono_arch_get_restore_context (&info, TRUE);
4433                 emit_trampoline (acfg, acfg->got_offset, info);
4434                 code = mono_arch_get_call_filter (&info, TRUE);
4435                 emit_trampoline (acfg, acfg->got_offset, info);
4436                 code = mono_arch_get_throw_exception (&info, TRUE);
4437                 emit_trampoline (acfg, acfg->got_offset, info);
4438                 code = mono_arch_get_rethrow_exception (&info, TRUE);
4439                 emit_trampoline (acfg, acfg->got_offset, info);
4440                 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4441                 emit_trampoline (acfg, acfg->got_offset, info);
4442
4443 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4444                 {
4445                         GSList *l = mono_arch_get_trampolines (TRUE);
4446
4447                         while (l) {
4448                                 MonoTrampInfo *info = l->data;
4449
4450                                 emit_trampoline (acfg, acfg->got_offset, info);
4451                                 l = l->next;
4452                         }
4453                 }
4454 #endif
4455
4456                 for (i = 0; i < 128; ++i) {
4457                         int offset;
4458
4459                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4460                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4461                         emit_trampoline (acfg, acfg->got_offset, info);
4462
4463                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4464                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4465                         emit_trampoline (acfg, acfg->got_offset, info);
4466                 }
4467
4468                 {
4469                         GSList *l;
4470
4471                         /* delegate_invoke_impl trampolines */
4472                         l = mono_arch_get_delegate_invoke_impls ();
4473                         while (l) {
4474                                 MonoTrampInfo *info = l->data;
4475
4476                                 emit_trampoline (acfg, acfg->got_offset, info);
4477                                 l = l->next;
4478                         }
4479                 }
4480
4481 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4482
4483                 /* Emit trampolines which are numerous */
4484
4485                 /*
4486                  * These include the following:
4487                  * - specific trampolines
4488                  * - static rgctx invoke trampolines
4489                  * - imt thunks
4490                  * These trampolines have the same code, they are parameterized by GOT 
4491                  * slots. 
4492                  * They are defined in this file, in the arch_... routines instead of
4493                  * in tramp-<ARCH>.c, since it is easier to do it this way.
4494                  */
4495
4496                 /*
4497                  * When running in aot-only mode, we can't create specific trampolines at 
4498                  * runtime, so we create a few, and save them in the AOT file. 
4499                  * Normal trampolines embed their argument as a literal inside the 
4500                  * trampoline code, we can't do that here, so instead we embed an offset
4501                  * which needs to be added to the trampoline address to get the address of
4502                  * the GOT slot which contains the argument value.
4503                  * The generated trampolines jump to the generic trampolines using another
4504                  * GOT slot, which will be setup by the AOT loader to point to the 
4505                  * generic trampoline code of the given type.
4506                  */
4507
4508                 /*
4509                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4510                  * each class).
4511                  */
4512
4513                 emit_section_change (acfg, ".text", 0);
4514
4515                 tramp_got_offset = acfg->got_offset;
4516
4517                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4518                         switch (ntype) {
4519                         case MONO_AOT_TRAMP_SPECIFIC:
4520                                 sprintf (symbol, "specific_trampolines");
4521                                 break;
4522                         case MONO_AOT_TRAMP_STATIC_RGCTX:
4523                                 sprintf (symbol, "static_rgctx_trampolines");
4524                                 break;
4525                         case MONO_AOT_TRAMP_IMT_THUNK:
4526                                 sprintf (symbol, "imt_thunks");
4527                                 break;
4528                         default:
4529                                 g_assert_not_reached ();
4530                         }
4531
4532                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4533                         emit_label (acfg, symbol);
4534
4535                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4536
4537                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4538                                 int tramp_size = 0;
4539
4540                                 switch (ntype) {
4541                                 case MONO_AOT_TRAMP_SPECIFIC:
4542                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4543                                         tramp_got_offset += 2;
4544                                 break;
4545                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
4546                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
4547                                         tramp_got_offset += 2;
4548                                         break;
4549                                 case MONO_AOT_TRAMP_IMT_THUNK:
4550                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4551                                         tramp_got_offset += 1;
4552                                         break;
4553                                 default:
4554                                         g_assert_not_reached ();
4555                                 }
4556 #ifdef __native_client_codegen__
4557                                 /* align to avoid 32-byte boundary crossings */
4558                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4559 #endif
4560
4561                                 if (!acfg->trampoline_size [ntype]) {
4562                                         g_assert (tramp_size);
4563                                         acfg->trampoline_size [ntype] = tramp_size;
4564                                 }
4565                         }
4566                 }
4567
4568                 /* Reserve some entries at the end of the GOT for our use */
4569                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4570         }
4571
4572         acfg->got_offset += acfg->num_trampoline_got_entries;
4573 }
4574
4575 static gboolean
4576 str_begins_with (const char *str1, const char *str2)
4577 {
4578         int len = strlen (str2);
4579         return strncmp (str1, str2, len) == 0;
4580 }
4581
4582 static void
4583 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4584 {
4585         gchar **args, **ptr;
4586
4587         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4588         for (ptr = args; ptr && *ptr; ptr ++) {
4589                 const char *arg = *ptr;
4590
4591                 if (str_begins_with (arg, "outfile=")) {
4592                         opts->outfile = g_strdup (arg + strlen ("outfile="));
4593                 } else if (str_begins_with (arg, "save-temps")) {
4594                         opts->save_temps = TRUE;
4595                 } else if (str_begins_with (arg, "keep-temps")) {
4596                         opts->save_temps = TRUE;
4597                 } else if (str_begins_with (arg, "write-symbols")) {
4598                         opts->write_symbols = TRUE;
4599                 } else if (str_begins_with (arg, "no-write-symbols")) {
4600                         opts->write_symbols = FALSE;
4601                 } else if (str_begins_with (arg, "metadata-only")) {
4602                         opts->metadata_only = TRUE;
4603                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4604                         opts->bind_to_runtime_version = TRUE;
4605                 } else if (str_begins_with (arg, "full")) {
4606                         opts->full_aot = TRUE;
4607                 } else if (str_begins_with (arg, "threads=")) {
4608                         opts->nthreads = atoi (arg + strlen ("threads="));
4609                 } else if (str_begins_with (arg, "static")) {
4610                         opts->static_link = TRUE;
4611                         opts->no_dlsym = TRUE;
4612                 } else if (str_begins_with (arg, "asmonly")) {
4613                         opts->asm_only = TRUE;
4614                 } else if (str_begins_with (arg, "asmwriter")) {
4615                         opts->asm_writer = TRUE;
4616                 } else if (str_begins_with (arg, "nodebug")) {
4617                         opts->nodebug = TRUE;
4618                 } else if (str_begins_with (arg, "ntrampolines=")) {
4619                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4620                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4621                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4622                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4623                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4624                 } else if (str_begins_with (arg, "autoreg")) {
4625                         opts->autoreg = TRUE;
4626                 } else if (str_begins_with (arg, "tool-prefix=")) {
4627                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4628                 } else if (str_begins_with (arg, "soft-debug")) {
4629                         opts->soft_debug = TRUE;
4630                 } else if (str_begins_with (arg, "print-skipped")) {
4631                         opts->print_skipped_methods = TRUE;
4632                 } else if (str_begins_with (arg, "stats")) {
4633                         opts->stats = TRUE;
4634                 } else if (str_begins_with (arg, "mtriple=")) {
4635                         opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4636                 } else if (str_begins_with (arg, "llvm-path=")) {
4637                         opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4638                 } else if (str_begins_with (arg, "info")) {
4639                         printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
4640                         exit (0);
4641                 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
4642                         printf ("Supported options for --aot:\n");
4643                         printf ("    outfile=\n");
4644                         printf ("    save-temps\n");
4645                         printf ("    keep-temps\n");
4646                         printf ("    write-symbols\n");
4647                         printf ("    metadata-only\n");
4648                         printf ("    bind-to-runtime-version\n");
4649                         printf ("    full\n");
4650                         printf ("    threads=\n");
4651                         printf ("    static\n");
4652                         printf ("    asmonly\n");
4653                         printf ("    asmwriter\n");
4654                         printf ("    nodebug\n");
4655                         printf ("    ntrampolines=\n");
4656                         printf ("    nrgctx-trampolines=\n");
4657                         printf ("    nimt-trampolines=\n");
4658                         printf ("    autoreg\n");
4659                         printf ("    tool-prefix=\n");
4660                         printf ("    soft-debug\n");
4661                         printf ("    print-skipped\n");
4662                         printf ("    stats\n");
4663                         printf ("    info\n");
4664                         printf ("    help/?\n");
4665                         exit (0);
4666                 } else {
4667                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4668                         exit (1);
4669                 }
4670         }
4671
4672         g_strfreev (args);
4673 }
4674
4675 static void
4676 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4677 {
4678         MonoMethod *method = (MonoMethod*)key;
4679         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4680         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4681         MonoAotCompile *acfg = user_data;
4682
4683         new_ji->image = ji->image;
4684         new_ji->token = ji->token;
4685         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4686 }
4687
4688 static gboolean
4689 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4690 {
4691         if (klass->type_token)
4692                 return TRUE;
4693         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4694                 return TRUE;
4695         if (klass->rank)
4696                 return can_encode_class (acfg, klass->element_class);
4697         return FALSE;
4698 }
4699
4700 static gboolean
4701 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4702 {
4703         switch (patch_info->type) {
4704         case MONO_PATCH_INFO_METHOD:
4705         case MONO_PATCH_INFO_METHODCONST: {
4706                 MonoMethod *method = patch_info->data.method;
4707
4708                 if (method->wrapper_type) {
4709                         switch (method->wrapper_type) {
4710                         case MONO_WRAPPER_NONE:
4711                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4712                         case MONO_WRAPPER_XDOMAIN_INVOKE:
4713                         case MONO_WRAPPER_STFLD:
4714                         case MONO_WRAPPER_LDFLD:
4715                         case MONO_WRAPPER_LDFLDA:
4716                         case MONO_WRAPPER_LDFLD_REMOTE:
4717                         case MONO_WRAPPER_STFLD_REMOTE:
4718                         case MONO_WRAPPER_STELEMREF:
4719                         case MONO_WRAPPER_ISINST:
4720                         case MONO_WRAPPER_PROXY_ISINST:
4721                         case MONO_WRAPPER_ALLOC:
4722                         case MONO_WRAPPER_REMOTING_INVOKE:
4723                         case MONO_WRAPPER_UNKNOWN:
4724                         case MONO_WRAPPER_WRITE_BARRIER:
4725                                 break;
4726                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
4727                                 if (!strcmp (method->name, "ElementAddr"))
4728                                         return TRUE;
4729                                 else
4730                                         return FALSE;
4731                         case MONO_WRAPPER_CASTCLASS:
4732                                 if (!strcmp (method->name, "__castclass_with_cache"))
4733                                         return TRUE;
4734                                 else
4735                                         return FALSE;
4736                         default:
4737                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4738                                 return FALSE;
4739                         }
4740                 } else {
4741                         if (!method->token) {
4742                                 /* The method is part of a constructed type like Int[,].Set (). */
4743                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4744                                         if (method->klass->rank)
4745                                                 return TRUE;
4746                                         return FALSE;
4747                                 }
4748                         }
4749                 }
4750                 break;
4751         }
4752         case MONO_PATCH_INFO_VTABLE:
4753         case MONO_PATCH_INFO_CLASS_INIT:
4754         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4755         case MONO_PATCH_INFO_CLASS:
4756         case MONO_PATCH_INFO_IID:
4757         case MONO_PATCH_INFO_ADJUSTED_IID:
4758                 if (!can_encode_class (acfg, patch_info->data.klass)) {
4759                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4760                         return FALSE;
4761                 }
4762                 break;
4763         case MONO_PATCH_INFO_RGCTX_FETCH: {
4764                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4765
4766                 if (!can_encode_patch (acfg, entry->data))
4767                         return FALSE;
4768                 break;
4769         }
4770         default:
4771                 break;
4772         }
4773
4774         return TRUE;
4775 }
4776
4777 /*
4778  * compile_method:
4779  *
4780  *   AOT compile a given method.
4781  * This function might be called by multiple threads, so it must be thread-safe.
4782  */
4783 static void
4784 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4785 {
4786         MonoCompile *cfg;
4787         MonoJumpInfo *patch_info;
4788         gboolean skip;
4789         int index, depth;
4790         MonoMethod *wrapped;
4791
4792         if (acfg->aot_opts.metadata_only)
4793                 return;
4794
4795         mono_acfg_lock (acfg);
4796         index = get_method_index (acfg, method);
4797         mono_acfg_unlock (acfg);
4798
4799         /* fixme: maybe we can also precompile wrapper methods */
4800         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4801                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4802                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4803                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4804                 return;
4805         }
4806
4807         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4808                 return;
4809
4810         wrapped = mono_marshal_method_from_wrapper (method);
4811         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4812                 // FIXME: The wrapper should be generic too, but it is not
4813                 return;
4814
4815         InterlockedIncrement (&acfg->stats.mcount);
4816
4817 #if 0
4818         if (method->is_generic || method->klass->generic_container) {
4819                 InterlockedIncrement (&acfg->stats.genericcount);
4820                 return;
4821         }
4822 #endif
4823
4824         //acfg->aot_opts.print_skipped_methods = TRUE;
4825
4826         /*
4827          * Since these methods are the only ones which are compiled with
4828          * AOT support, and they are not used by runtime startup/shutdown code,
4829          * the runtime will not see AOT methods during AOT compilation,so it
4830          * does not need to support them by creating a fake GOT etc.
4831          */
4832         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4833         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4834                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4835                 InterlockedIncrement (&acfg->stats.genericcount);
4836                 return;
4837         }
4838         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4839                 /* Let the exception happen at runtime */
4840                 return;
4841         }
4842
4843         if (cfg->disable_aot) {
4844                 if (acfg->aot_opts.print_skipped_methods)
4845                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4846                 InterlockedIncrement (&acfg->stats.ocount);
4847                 mono_destroy_compile (cfg);
4848                 return;
4849         }
4850
4851         /* Nullify patches which need no aot processing */
4852         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4853                 switch (patch_info->type) {
4854                 case MONO_PATCH_INFO_LABEL:
4855                 case MONO_PATCH_INFO_BB:
4856                         patch_info->type = MONO_PATCH_INFO_NONE;
4857                         break;
4858                 default:
4859                         break;
4860                 }
4861         }
4862
4863         /* Collect method->token associations from the cfg */
4864         mono_acfg_lock (acfg);
4865         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4866         mono_acfg_unlock (acfg);
4867
4868         /*
4869          * Check for absolute addresses.
4870          */
4871         skip = FALSE;
4872         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4873                 switch (patch_info->type) {
4874                 case MONO_PATCH_INFO_ABS:
4875                         /* unable to handle this */
4876                         skip = TRUE;    
4877                         break;
4878                 default:
4879                         break;
4880                 }
4881         }
4882
4883         if (skip) {
4884                 if (acfg->aot_opts.print_skipped_methods)
4885                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4886                 InterlockedIncrement (&acfg->stats.abscount);
4887                 mono_destroy_compile (cfg);
4888                 return;
4889         }
4890
4891         /* Lock for the rest of the code */
4892         mono_acfg_lock (acfg);
4893
4894         /*
4895          * Check for methods/klasses we can't encode.
4896          */
4897         skip = FALSE;
4898         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4899                 if (!can_encode_patch (acfg, patch_info))
4900                         skip = TRUE;
4901         }
4902
4903         if (skip) {
4904                 if (acfg->aot_opts.print_skipped_methods)
4905                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4906                 acfg->stats.ocount++;
4907                 mono_destroy_compile (cfg);
4908                 mono_acfg_unlock (acfg);
4909                 return;
4910         }
4911
4912         /* Adds generic instances referenced by this method */
4913         /* 
4914          * The depth is used to avoid infinite loops when generic virtual recursion is 
4915          * encountered.
4916          */
4917         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4918         if (depth < 32) {
4919                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4920                         switch (patch_info->type) {
4921                         case MONO_PATCH_INFO_METHOD: {
4922                                 MonoMethod *m = patch_info->data.method;
4923                                 if (m->is_inflated) {
4924                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
4925                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
4926                                                 !method_has_type_vars (m)) {
4927                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4928                                                         if (acfg->aot_opts.full_aot)
4929                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4930                                                 } else {
4931                                                         add_extra_method_with_depth (acfg, m, depth + 1);
4932                                                 }
4933                                         }
4934                                         add_generic_class_with_depth (acfg, m->klass, depth + 5);
4935                                 }
4936                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4937                                         add_extra_method_with_depth (acfg, m, depth + 1);
4938                                 break;
4939                         }
4940                         case MONO_PATCH_INFO_VTABLE: {
4941                                 MonoClass *klass = patch_info->data.klass;
4942
4943                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4944                                         add_generic_class_with_depth (acfg, klass, depth + 5);
4945                                 break;
4946                         }
4947                         default:
4948                                 break;
4949                         }
4950                 }
4951         }
4952
4953         /* Determine whenever the method has GOT slots */
4954         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4955                 switch (patch_info->type) {
4956                 case MONO_PATCH_INFO_GOT_OFFSET:
4957                 case MONO_PATCH_INFO_NONE:
4958                 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4959                         break;
4960                 case MONO_PATCH_INFO_IMAGE:
4961                         /* The assembly is stored in GOT slot 0 */
4962                         if (patch_info->data.image != acfg->image)
4963                                 cfg->has_got_slots = TRUE;
4964                         break;
4965                 default:
4966                         if (!is_plt_patch (patch_info))
4967                                 cfg->has_got_slots = TRUE;
4968                         break;
4969                 }
4970         }
4971
4972         if (!cfg->has_got_slots)
4973                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4974
4975         /* 
4976          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4977          */
4978         /* Make a copy of the patch info which is in the mempool */
4979         {
4980                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4981
4982                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4983                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4984
4985                         if (!patches)
4986                                 patches = new_patch_info;
4987                         else
4988                                 patches_end->next = new_patch_info;
4989                         patches_end = new_patch_info;
4990                 }
4991                 cfg->patch_info = patches;
4992         }
4993         /* Make a copy of the unwind info */
4994         {
4995                 GSList *l, *unwind_ops;
4996                 MonoUnwindOp *op;
4997
4998                 unwind_ops = NULL;
4999                 for (l = cfg->unwind_ops; l; l = l->next) {
5000                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5001                         memcpy (op, l->data, sizeof (MonoUnwindOp));
5002                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5003                 }
5004                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5005         }
5006         /* Make a copy of the argument/local info */
5007         {
5008                 MonoInst **args, **locals;
5009                 MonoMethodSignature *sig;
5010                 MonoMethodHeader *header;
5011                 int i;
5012                 
5013                 sig = mono_method_signature (method);
5014                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5015                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5016                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5017                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5018                 }
5019                 cfg->args = args;
5020
5021                 header = mono_method_get_header (method);
5022                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5023                 for (i = 0; i < header->num_locals; ++i) {
5024                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5025                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5026                 }
5027                 cfg->locals = locals;
5028         }
5029
5030         /* Free some fields used by cfg to conserve memory */
5031         mono_mempool_destroy (cfg->mempool);
5032         cfg->mempool = NULL;
5033         g_free (cfg->varinfo);
5034         cfg->varinfo = NULL;
5035         g_free (cfg->vars);
5036         cfg->vars = NULL;
5037         if (cfg->rs) {
5038                 mono_regstate_free (cfg->rs);
5039                 cfg->rs = NULL;
5040         }
5041
5042         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
5043
5044         while (index >= acfg->cfgs_size) {
5045                 MonoCompile **new_cfgs;
5046                 int new_size;
5047
5048                 new_size = acfg->cfgs_size * 2;
5049                 new_cfgs = g_new0 (MonoCompile*, new_size);
5050                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5051                 g_free (acfg->cfgs);
5052                 acfg->cfgs = new_cfgs;
5053                 acfg->cfgs_size = new_size;
5054         }
5055         acfg->cfgs [index] = cfg;
5056
5057         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5058
5059         /*
5060         if (cfg->orig_method->wrapper_type)
5061                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5062         */
5063
5064         mono_acfg_unlock (acfg);
5065
5066         InterlockedIncrement (&acfg->stats.ccount);
5067 }
5068  
5069 static void
5070 compile_thread_main (gpointer *user_data)
5071 {
5072         MonoDomain *domain = user_data [0];
5073         MonoAotCompile *acfg = user_data [1];
5074         GPtrArray *methods = user_data [2];
5075         int i;
5076
5077         mono_thread_attach (domain);
5078
5079         for (i = 0; i < methods->len; ++i)
5080                 compile_method (acfg, g_ptr_array_index (methods, i));
5081 }
5082
5083 static void
5084 load_profile_files (MonoAotCompile *acfg)
5085 {
5086         FILE *infile;
5087         char *tmp;
5088         int file_index, res, method_index, i;
5089         char ver [256];
5090         guint32 token;
5091         GList *unordered;
5092
5093         file_index = 0;
5094         while (TRUE) {
5095                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5096
5097                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5098                         g_free (tmp);
5099                         break;
5100                 }
5101
5102                 infile = fopen (tmp, "r");
5103                 g_assert (infile);
5104
5105                 printf ("Using profile data file '%s'\n", tmp);
5106                 g_free (tmp);
5107
5108                 file_index ++;
5109
5110                 res = fscanf (infile, "%32s\n", ver);
5111                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5112                         printf ("Profile file has wrong version or invalid.\n");
5113                         fclose (infile);
5114                         continue;
5115                 }
5116
5117                 while (TRUE) {
5118                         char name [1024];
5119                         MonoMethodDesc *desc;
5120                         MonoMethod *method;
5121
5122                         if (fgets (name, 1023, infile) == NULL)
5123                                 break;
5124
5125                         /* Kill the newline */
5126                         if (strlen (name) > 0)
5127                                 name [strlen (name) - 1] = '\0';
5128
5129                         desc = mono_method_desc_new (name, TRUE);
5130
5131                         method = mono_method_desc_search_in_image (desc, acfg->image);
5132
5133                         if (method && mono_method_get_token (method)) {
5134                                 token = mono_method_get_token (method);
5135                                 method_index = mono_metadata_token_index (token) - 1;
5136
5137                                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
5138                                         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
5139                                 }
5140                         } else {
5141                                 //printf ("No method found matching '%s'.\n", name);
5142                         }
5143                 }
5144                 fclose (infile);
5145         }
5146
5147         /* Add missing methods */
5148         unordered = NULL;
5149         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
5150                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
5151                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
5152         }
5153         unordered = g_list_reverse (unordered);
5154         if (acfg->method_order)
5155                 g_list_last (acfg->method_order)->next = unordered;
5156         else
5157                 acfg->method_order = unordered;
5158 }
5159  
5160 /* Used by the LLVM backend */
5161 guint32
5162 mono_aot_get_got_offset (MonoJumpInfo *ji)
5163 {
5164         return get_got_offset (llvm_acfg, ji);
5165 }
5166
5167 char*
5168 mono_aot_get_method_name (MonoCompile *cfg)
5169 {
5170         if (llvm_acfg->aot_opts.static_link)
5171                 /* Include the assembly name too to avoid duplicate symbol errors */
5172                 return g_strdup_printf ("%s_%s", llvm_acfg->image->assembly->aname.name, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5173         else
5174                 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5175 }
5176
5177 char*
5178 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5179 {
5180         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5181         MonoPltEntry *plt_entry;
5182
5183         ji->type = type;
5184         ji->data.target = data;
5185
5186         if (!can_encode_patch (llvm_acfg, ji))
5187                 return NULL;
5188
5189         plt_entry = get_plt_entry (llvm_acfg, ji);
5190         plt_entry->llvm_used = TRUE;
5191
5192 #if defined(__APPLE__)
5193         return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5194 #else
5195         return g_strdup_printf (plt_entry->llvm_symbol);
5196 #endif
5197 }
5198
5199 MonoJumpInfo*
5200 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5201 {
5202         MonoJumpInfo *res;
5203
5204         mono_acfg_lock (llvm_acfg);
5205         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5206         mono_acfg_unlock (llvm_acfg);
5207
5208         return res;
5209 }
5210
5211 #ifdef ENABLE_LLVM
5212
5213 /*
5214  * emit_llvm_file:
5215  *
5216  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5217  * tools.
5218  */
5219 static void
5220 emit_llvm_file (MonoAotCompile *acfg)
5221 {
5222         char *command, *opts;
5223         int i;
5224         MonoJumpInfo *patch_info;
5225
5226         /*
5227          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5228          * to it.
5229          */
5230
5231         /* Compute the final size of the got */
5232         for (i = 0; i < acfg->nmethods; ++i) {
5233                 if (acfg->cfgs [i]) {
5234                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5235                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5236                                         if (!is_plt_patch (patch_info))
5237                                                 get_got_offset (acfg, patch_info);
5238                                         else
5239                                                 get_plt_entry (acfg, patch_info);
5240                                 }
5241                         }
5242                 }
5243         }
5244
5245         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5246
5247         if (acfg->aot_opts.full_aot) {
5248                 int ntype;
5249
5250                 /* 
5251                  * Need to add the got entries used by the trampolines.
5252                  * This is only a conservative approximation.
5253                  */
5254                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5255                         /* For the generic + rgctx trampolines */
5256                         acfg->final_got_size += 200;
5257                         /* For the specific trampolines */
5258                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5259                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5260                 }
5261         }
5262
5263
5264         mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5265
5266         /*
5267          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5268          * a lot of time, and doesn't seem to save much space.
5269          * The following optimizations cannot be enabled:
5270          * - 'tailcallelim'
5271          * - 'jump-threading' changes our blockaddress references to int constants.
5272          * The opt list below was produced by taking the output of:
5273          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5274          * then removing tailcallelim + the global opts, and adding a second gvn.
5275          */
5276         opts = g_strdup ("-instcombine -simplifycfg");
5277         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 -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5278 #if 1
5279         command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5280         printf ("Executing opt: %s\n", command);
5281         if (system (command) != 0) {
5282                 exit (1);
5283         }
5284 #endif
5285         g_free (opts);
5286
5287         if (!acfg->llc_args)
5288                 acfg->llc_args = g_string_new ("");
5289
5290         /* Verbose asm slows down llc greatly */
5291         g_string_append (acfg->llc_args, " -asm-verbose=false");
5292
5293         if (acfg->aot_opts.mtriple)
5294                 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5295
5296         if (llvm_acfg->aot_opts.static_link)
5297                 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5298         else
5299                 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5300         unlink (acfg->tmpfname);
5301
5302         command = g_strdup_printf ("%sllc %s -unwind-tables -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5303
5304         printf ("Executing llc: %s\n", command);
5305
5306         if (system (command) != 0) {
5307                 exit (1);
5308         }
5309 }
5310 #endif
5311
5312 static void
5313 emit_code (MonoAotCompile *acfg)
5314 {
5315         int i;
5316         char symbol [256];
5317         char end_symbol [256];
5318         GList *l;
5319
5320 #if defined(TARGET_POWERPC64)
5321         sprintf (symbol, ".Lgot_addr");
5322         emit_section_change (acfg, ".text", 0);
5323         emit_alignment (acfg, 8);
5324         emit_label (acfg, symbol);
5325         emit_pointer (acfg, acfg->got_symbol);
5326 #endif
5327
5328         /* 
5329          * This global symbol is used to compute the address of each method using the
5330          * code_offsets array. It is also used to compute the memory ranges occupied by
5331          * AOT code, so it must be equal to the address of the first emitted method.
5332          */
5333         sprintf (symbol, "methods");
5334         emit_section_change (acfg, ".text", 0);
5335         emit_alignment (acfg, 8);
5336         if (acfg->llvm) {
5337                 for (i = 0; i < acfg->nmethods; ++i) {
5338                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5339                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5340                                 break;
5341                         }
5342                 }
5343                 if (i == acfg->nmethods)
5344                         /* No LLVM compiled methods */
5345                         emit_label (acfg, symbol);
5346         } else {
5347                 emit_label (acfg, symbol);
5348         }
5349
5350         /* 
5351          * Emit some padding so the local symbol for the first method doesn't have the
5352          * same address as 'methods'.
5353          */
5354 #if defined(__default_codegen__)
5355         emit_zero_bytes (acfg, 16);
5356 #elif defined(__native_client_codegen__)
5357         {
5358                 const int kPaddingSize = 16;
5359                 guint8 pad_buffer[kPaddingSize];
5360                 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5361                 emit_bytes (acfg, pad_buffer, kPaddingSize);
5362         }
5363 #endif
5364         
5365
5366         for (l = acfg->method_order; l != NULL; l = l->next) {
5367                 MonoCompile *cfg;
5368                 MonoMethod *method;
5369
5370                 i = GPOINTER_TO_UINT (l->data);
5371
5372                 cfg = acfg->cfgs [i];
5373
5374                 if (!cfg)
5375                         continue;
5376
5377                 method = cfg->orig_method;
5378
5379                 /* Emit unbox trampoline */
5380                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5381                         char call_target [256];
5382
5383                         if (!method->wrapper_type && !method->is_inflated) {
5384                                 g_assert (method->token);
5385                                 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5386                         } else {
5387                                 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5388                         }
5389
5390                         emit_section_change (acfg, ".text", 0);
5391 #ifdef __native_client_codegen__
5392                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5393 #endif
5394                         emit_global (acfg, symbol, TRUE);
5395
5396                         if (acfg->thumb_mixed && cfg->compile_llvm)
5397                                 fprintf (acfg->fp, "\n.thumb_func\n");
5398
5399                         emit_label (acfg, symbol);
5400
5401                         sprintf (call_target, "%s", cfg->asm_symbol);
5402
5403                         arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, call_target);
5404                 }
5405
5406                 if (cfg->compile_llvm)
5407                         acfg->stats.llvm_count ++;
5408                 else
5409                         emit_method_code (acfg, cfg);
5410         }
5411
5412         sprintf (symbol, "methods_end");
5413         emit_section_change (acfg, ".text", 0);
5414         emit_alignment (acfg, 8);
5415         emit_label (acfg, symbol);
5416
5417         /* 
5418          * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5419          * from optimizing them away, since it doesn't see that code_offsets references them.
5420          * JITted methods don't need this since they are referenced using assembler local
5421          * symbols.
5422          * FIXME: This is why write-symbols doesn't work on OSX ?
5423          */
5424         if (acfg->llvm && acfg->need_no_dead_strip) {
5425                 fprintf (acfg->fp, "\n");
5426                 for (i = 0; i < acfg->nmethods; ++i) {
5427                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5428                                 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5429                 }
5430         }
5431
5432         sprintf (symbol, "code_offsets");
5433         emit_section_change (acfg, RODATA_SECT, 1);
5434         emit_alignment (acfg, 8);
5435         emit_label (acfg, symbol);
5436
5437         acfg->stats.offsets_size += acfg->nmethods * 4;
5438
5439         sprintf (end_symbol, "methods");
5440         for (i = 0; i < acfg->nmethods; ++i) {
5441                 if (acfg->cfgs [i]) {
5442                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5443                 } else {
5444                         emit_int32 (acfg, 0xffffffff);
5445                 }
5446         }
5447         emit_line (acfg);
5448 }
5449
5450 static void
5451 emit_info (MonoAotCompile *acfg)
5452 {
5453         int i;
5454         char symbol [256];
5455         GList *l;
5456         gint32 *offsets;
5457
5458         offsets = g_new0 (gint32, acfg->nmethods);
5459
5460         for (l = acfg->method_order; l != NULL; l = l->next) {
5461                 i = GPOINTER_TO_UINT (l->data);
5462
5463                 if (acfg->cfgs [i]) {
5464                         emit_method_info (acfg, acfg->cfgs [i]);
5465                         offsets [i] = acfg->cfgs [i]->method_info_offset;
5466                 } else {
5467                         offsets [i] = 0;
5468                 }
5469         }
5470
5471         sprintf (symbol, "method_info_offsets");
5472         emit_section_change (acfg, RODATA_SECT, 1);
5473         emit_alignment (acfg, 8);
5474         emit_label (acfg, symbol);
5475
5476         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5477
5478         g_free (offsets);
5479 }
5480
5481 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5482
5483 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5484 #define mix(a,b,c) { \
5485         a -= c;  a ^= rot(c, 4);  c += b; \
5486         b -= a;  b ^= rot(a, 6);  a += c; \
5487         c -= b;  c ^= rot(b, 8);  b += a; \
5488         a -= c;  a ^= rot(c,16);  c += b; \
5489         b -= a;  b ^= rot(a,19);  a += c; \
5490         c -= b;  c ^= rot(b, 4);  b += a; \
5491 }
5492 #define final(a,b,c) { \
5493         c ^= b; c -= rot(b,14); \
5494         a ^= c; a -= rot(c,11); \
5495         b ^= a; b -= rot(a,25); \
5496         c ^= b; c -= rot(b,16); \
5497         a ^= c; a -= rot(c,4);  \
5498         b ^= a; b -= rot(a,14); \
5499         c ^= b; c -= rot(b,24); \
5500 }
5501
5502 static guint
5503 mono_aot_type_hash (MonoType *t1)
5504 {
5505         guint hash = t1->type;
5506
5507         hash |= t1->byref << 6; /* do not collide with t1->type values */
5508         switch (t1->type) {
5509         case MONO_TYPE_VALUETYPE:
5510         case MONO_TYPE_CLASS:
5511         case MONO_TYPE_SZARRAY:
5512                 /* check if the distribution is good enough */
5513                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5514         case MONO_TYPE_PTR:
5515                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5516         case MONO_TYPE_ARRAY:
5517                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5518         case MONO_TYPE_GENERICINST:
5519                 return ((hash << 5) - hash) ^ 0;
5520         }
5521         return hash;
5522 }
5523
5524 /*
5525  * mono_aot_method_hash:
5526  *
5527  *   Return a hash code for methods which only depends on metadata.
5528  */
5529 guint32
5530 mono_aot_method_hash (MonoMethod *method)
5531 {
5532         MonoMethodSignature *sig;
5533         MonoClass *klass;
5534         int i, hindex;
5535         int hashes_count;
5536         guint32 *hashes_start, *hashes;
5537         guint32 a, b, c;
5538         MonoGenericInst *ginst = NULL;
5539
5540         /* Similar to the hash in mono_method_get_imt_slot () */
5541
5542         sig = mono_method_signature (method);
5543
5544         if (method->is_inflated)
5545                 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5546
5547         hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5548         hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5549         hashes = hashes_start;
5550
5551         /* Some wrappers are assigned to random classes */
5552         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5553                 klass = method->klass;
5554         else
5555                 klass = mono_defaults.object_class;
5556
5557         if (!method->wrapper_type) {
5558                 char *full_name = mono_type_full_name (&klass->byval_arg);
5559
5560                 hashes [0] = mono_metadata_str_hash (full_name);
5561                 hashes [1] = 0;
5562                 g_free (full_name);
5563         } else {
5564                 hashes [0] = mono_metadata_str_hash (klass->name);
5565                 hashes [1] = mono_metadata_str_hash (klass->name_space);
5566         }
5567         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5568                 /* The method name includes a stringified pointer */
5569                 hashes [2] = 0;
5570         else
5571                 hashes [2] = mono_metadata_str_hash (method->name);
5572         hashes [3] = method->wrapper_type;
5573         hashes [4] = mono_aot_type_hash (sig->ret);
5574         hindex = 5;
5575         for (i = 0; i < sig->param_count; i++) {
5576                 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5577         }
5578         if (ginst) {
5579                 for (i = 0; i < ginst->type_argc; ++i)
5580                         hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5581         }               
5582         g_assert (hindex == hashes_count);
5583
5584         /* Setup internal state */
5585         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5586
5587         /* Handle most of the hashes */
5588         while (hashes_count > 3) {
5589                 a += hashes [0];
5590                 b += hashes [1];
5591                 c += hashes [2];
5592                 mix (a,b,c);
5593                 hashes_count -= 3;
5594                 hashes += 3;
5595         }
5596
5597         /* Handle the last 3 hashes (all the case statements fall through) */
5598         switch (hashes_count) { 
5599         case 3 : c += hashes [2];
5600         case 2 : b += hashes [1];
5601         case 1 : a += hashes [0];
5602                 final (a,b,c);
5603         case 0: /* nothing left to add */
5604                 break;
5605         }
5606         
5607         free (hashes_start);
5608         
5609         return c;
5610 }
5611 #undef rot
5612 #undef mix
5613 #undef final
5614
5615 /*
5616  * mono_aot_wrapper_name:
5617  *
5618  *   Return a string which uniqely identifies the given wrapper method.
5619  */
5620 char*
5621 mono_aot_wrapper_name (MonoMethod *method)
5622 {
5623         char *name, *tmpsig, *klass_desc;
5624
5625         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5626
5627         switch (method->wrapper_type) {
5628         case MONO_WRAPPER_RUNTIME_INVOKE:
5629                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5630                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5631                 else
5632                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5633                 break;
5634         default:
5635                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5636                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5637                 g_free (klass_desc);
5638                 break;
5639         }
5640
5641         g_free (tmpsig);
5642
5643         return name;
5644 }
5645
5646 /*
5647  * mono_aot_get_array_helper_from_wrapper;
5648  *
5649  * Get the helper method in Array called by an array wrapper method.
5650  */
5651 MonoMethod*
5652 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5653 {
5654         MonoMethod *m;
5655         const char *prefix;
5656         MonoGenericContext ctx;
5657         MonoType *args [16];
5658         char *mname, *iname, *s, *s2, *helper_name = NULL;
5659
5660         prefix = "System.Collections.Generic";
5661         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5662         s2 = strstr (s, "`1.");
5663         g_assert (s2);
5664         s2 [0] = '\0';
5665         iname = s;
5666         mname = s2 + 3;
5667
5668         //printf ("X: %s %s\n", iname, mname);
5669
5670         if (!strcmp (iname, "IList"))
5671                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5672         else
5673                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5674         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5675         g_assert (m);
5676         g_free (helper_name);
5677         g_free (s);
5678
5679         if (m->is_generic) {
5680                 memset (&ctx, 0, sizeof (ctx));
5681                 args [0] = &method->klass->element_class->byval_arg;
5682                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5683                 m = mono_class_inflate_generic_method (m, &ctx);
5684         }
5685
5686         return m;
5687 }
5688
5689 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5690
5691 typedef struct HashEntry {
5692     guint32 key, value, index;
5693         struct HashEntry *next;
5694 } HashEntry;
5695
5696 /*
5697  * emit_extra_methods:
5698  *
5699  * Emit methods which are not in the METHOD table, like wrappers.
5700  */
5701 static void
5702 emit_extra_methods (MonoAotCompile *acfg)
5703 {
5704         int i, table_size, buf_size;
5705         char symbol [256];
5706         guint8 *p, *buf;
5707         guint32 *info_offsets;
5708         guint32 hash;
5709         GPtrArray *table;
5710         HashEntry *entry, *new_entry;
5711         int nmethods, max_chain_length;
5712         int *chain_lengths;
5713
5714         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5715
5716         /* Emit method info */
5717         nmethods = 0;
5718         for (i = 0; i < acfg->extra_methods->len; ++i) {
5719                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5720                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5721                 char *name;
5722
5723                 if (!cfg)
5724                         continue;
5725
5726                 buf_size = 10240;
5727                 p = buf = g_malloc (buf_size);
5728
5729                 nmethods ++;
5730
5731                 method = cfg->method_to_register;
5732
5733                 name = NULL;
5734                 if (method->wrapper_type) {
5735                         gboolean encode_ref = FALSE;
5736
5737                         /* 
5738                          * We encode some wrappers using their name, since encoding them
5739                          * directly would be difficult. This works because at runtime, we only need to
5740                          * check whenever a method ref matches an existing MonoMethod. The downside is
5741                          * that the method names are large, so we use the binary encoding if possible.
5742                          */
5743                         switch (method->wrapper_type) {
5744                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5745                         case MONO_WRAPPER_SYNCHRONIZED:
5746                                 encode_ref = TRUE;
5747                                 break;
5748                         case MONO_WRAPPER_MANAGED_TO_NATIVE:
5749                                 /* Skip JIT icall wrappers */
5750                                 if (!strstr (method->name, "__icall_wrapper"))
5751                                         encode_ref = TRUE;
5752                                 break;
5753                         case MONO_WRAPPER_UNKNOWN:
5754                                 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5755                                         encode_ref = TRUE;
5756                                 break;
5757                         case MONO_WRAPPER_RUNTIME_INVOKE:
5758                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5759                                         /* Direct wrapper, encode normally */
5760                                         encode_ref = TRUE;
5761                                 break;
5762                         default:
5763                                 break;
5764                         }
5765
5766                         if (!encode_ref)
5767                                 name = mono_aot_wrapper_name (method);
5768                 }
5769
5770                 if (name) {
5771                         encode_value (1, p, &p);
5772                         encode_value (method->wrapper_type, p, &p);
5773                         strcpy ((char*)p, name);
5774                         p += strlen (name ) + 1;
5775                         g_free (name);
5776                 } else {
5777                         encode_value (0, p, &p);
5778                         encode_method_ref (acfg, method, p, &p);
5779                 }
5780
5781                 g_assert ((p - buf) < buf_size);
5782
5783                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5784                 g_free (buf);
5785         }
5786
5787         /*
5788          * Construct a chained hash table for mapping indexes in extra_method_info to
5789          * method indexes.
5790          */
5791         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5792         table = g_ptr_array_sized_new (table_size);
5793         for (i = 0; i < table_size; ++i)
5794                 g_ptr_array_add (table, NULL);
5795         chain_lengths = g_new0 (int, table_size);
5796         max_chain_length = 0;
5797         for (i = 0; i < acfg->extra_methods->len; ++i) {
5798                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5799                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5800                 guint32 key, value;
5801
5802                 if (!cfg)
5803                         continue;
5804
5805                 key = info_offsets [i];
5806                 value = get_method_index (acfg, method);
5807
5808                 hash = mono_aot_method_hash (method) % table_size;
5809
5810                 chain_lengths [hash] ++;
5811                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5812
5813                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5814                 new_entry->key = key;
5815                 new_entry->value = value;
5816
5817                 entry = g_ptr_array_index (table, hash);
5818                 if (entry == NULL) {
5819                         new_entry->index = hash;
5820                         g_ptr_array_index (table, hash) = new_entry;
5821                 } else {
5822                         while (entry->next)
5823                                 entry = entry->next;
5824                         
5825                         entry->next = new_entry;
5826                         new_entry->index = table->len;
5827                         g_ptr_array_add (table, new_entry);
5828                 }
5829         }
5830
5831         //printf ("MAX: %d\n", max_chain_length);
5832
5833         /* Emit the table */
5834         sprintf (symbol, "extra_method_table");
5835         emit_section_change (acfg, RODATA_SECT, 0);
5836         emit_alignment (acfg, 8);
5837         emit_label (acfg, symbol);
5838
5839         emit_int32 (acfg, table_size);
5840         for (i = 0; i < table->len; ++i) {
5841                 HashEntry *entry = g_ptr_array_index (table, i);
5842
5843                 if (entry == NULL) {
5844                         emit_int32 (acfg, 0);
5845                         emit_int32 (acfg, 0);
5846                         emit_int32 (acfg, 0);
5847                 } else {
5848                         //g_assert (entry->key > 0);
5849                         emit_int32 (acfg, entry->key);
5850                         emit_int32 (acfg, entry->value);
5851                         if (entry->next)
5852                                 emit_int32 (acfg, entry->next->index);
5853                         else
5854                                 emit_int32 (acfg, 0);
5855                 }
5856         }
5857
5858         /* 
5859          * Emit a table reverse mapping method indexes to their index in extra_method_info.
5860          * This is used by mono_aot_find_jit_info ().
5861          */
5862         sprintf (symbol, "extra_method_info_offsets");
5863         emit_section_change (acfg, RODATA_SECT, 0);
5864         emit_alignment (acfg, 8);
5865         emit_label (acfg, symbol);
5866
5867         emit_int32 (acfg, acfg->extra_methods->len);
5868         for (i = 0; i < acfg->extra_methods->len; ++i) {
5869                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5870
5871                 emit_int32 (acfg, get_method_index (acfg, method));
5872                 emit_int32 (acfg, info_offsets [i]);
5873         }
5874 }       
5875
5876 static void
5877 emit_exception_info (MonoAotCompile *acfg)
5878 {
5879         int i;
5880         char symbol [256];
5881         gint32 *offsets;
5882
5883         offsets = g_new0 (gint32, acfg->nmethods);
5884         for (i = 0; i < acfg->nmethods; ++i) {
5885                 if (acfg->cfgs [i]) {
5886                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
5887                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
5888                 } else {
5889                         offsets [i] = 0;
5890                 }
5891         }
5892
5893         sprintf (symbol, "ex_info_offsets");
5894         emit_section_change (acfg, RODATA_SECT, 1);
5895         emit_alignment (acfg, 8);
5896         emit_label (acfg, symbol);
5897
5898         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5899         g_free (offsets);
5900 }
5901
5902 static void
5903 emit_unwind_info (MonoAotCompile *acfg)
5904 {
5905         int i;
5906         char symbol [128];
5907
5908         /* 
5909          * The unwind info contains a lot of duplicates so we emit each unique
5910          * entry once, and only store the offset from the start of the table in the
5911          * exception info.
5912          */
5913
5914         sprintf (symbol, "unwind_info");
5915         emit_section_change (acfg, RODATA_SECT, 1);
5916         emit_alignment (acfg, 8);
5917         emit_label (acfg, symbol);
5918
5919         for (i = 0; i < acfg->unwind_ops->len; ++i) {
5920                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5921                 guint8 *unwind_info;
5922                 guint32 unwind_info_len;
5923                 guint8 buf [16];
5924                 guint8 *p;
5925
5926                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5927
5928                 p = buf;
5929                 encode_value (unwind_info_len, p, &p);
5930                 emit_bytes (acfg, buf, p - buf);
5931                 emit_bytes (acfg, unwind_info, unwind_info_len);
5932
5933                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5934         }
5935 }
5936
5937 static void
5938 emit_class_info (MonoAotCompile *acfg)
5939 {
5940         int i;
5941         char symbol [256];
5942         gint32 *offsets;
5943
5944         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5945         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5946                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5947
5948         sprintf (symbol, "class_info_offsets");
5949         emit_section_change (acfg, RODATA_SECT, 1);
5950         emit_alignment (acfg, 8);
5951         emit_label (acfg, symbol);
5952
5953         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5954         g_free (offsets);
5955 }
5956
5957 typedef struct ClassNameTableEntry {
5958         guint32 token, index;
5959         struct ClassNameTableEntry *next;
5960 } ClassNameTableEntry;
5961
5962 static void
5963 emit_class_name_table (MonoAotCompile *acfg)
5964 {
5965         int i, table_size;
5966         guint32 token, hash;
5967         MonoClass *klass;
5968         GPtrArray *table;
5969         char *full_name;
5970         char symbol [256];
5971         ClassNameTableEntry *entry, *new_entry;
5972
5973         /*
5974          * Construct a chained hash table for mapping class names to typedef tokens.
5975          */
5976         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5977         table = g_ptr_array_sized_new (table_size);
5978         for (i = 0; i < table_size; ++i)
5979                 g_ptr_array_add (table, NULL);
5980         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5981                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5982                 klass = mono_class_get (acfg->image, token);
5983                 if (!klass)
5984                         continue;
5985                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5986                 hash = mono_metadata_str_hash (full_name) % table_size;
5987                 g_free (full_name);
5988
5989                 /* FIXME: Allocate from the mempool */
5990                 new_entry = g_new0 (ClassNameTableEntry, 1);
5991                 new_entry->token = token;
5992
5993                 entry = g_ptr_array_index (table, hash);
5994                 if (entry == NULL) {
5995                         new_entry->index = hash;
5996                         g_ptr_array_index (table, hash) = new_entry;
5997                 } else {
5998                         while (entry->next)
5999                                 entry = entry->next;
6000                         
6001                         entry->next = new_entry;
6002                         new_entry->index = table->len;
6003                         g_ptr_array_add (table, new_entry);
6004                 }
6005         }
6006
6007         /* Emit the table */
6008         sprintf (symbol, "class_name_table");
6009         emit_section_change (acfg, RODATA_SECT, 0);
6010         emit_alignment (acfg, 8);
6011         emit_label (acfg, symbol);
6012
6013         /* FIXME: Optimize memory usage */
6014         g_assert (table_size < 65000);
6015         emit_int16 (acfg, table_size);
6016         g_assert (table->len < 65000);
6017         for (i = 0; i < table->len; ++i) {
6018                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6019
6020                 if (entry == NULL) {
6021                         emit_int16 (acfg, 0);
6022                         emit_int16 (acfg, 0);
6023                 } else {
6024                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
6025                         if (entry->next)
6026                                 emit_int16 (acfg, entry->next->index);
6027                         else
6028                                 emit_int16 (acfg, 0);
6029                 }
6030         }
6031 }
6032
6033 static void
6034 emit_image_table (MonoAotCompile *acfg)
6035 {
6036         int i;
6037         char symbol [256];
6038
6039         /*
6040          * The image table is small but referenced in a lot of places.
6041          * So we emit it at once, and reference its elements by an index.
6042          */
6043
6044         sprintf (symbol, "image_table");
6045         emit_section_change (acfg, RODATA_SECT, 1);
6046         emit_alignment (acfg, 8);
6047         emit_label (acfg, symbol);
6048
6049         emit_int32 (acfg, acfg->image_table->len);
6050         for (i = 0; i < acfg->image_table->len; i++) {
6051                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6052                 MonoAssemblyName *aname = &image->assembly->aname;
6053
6054                 /* FIXME: Support multi-module assemblies */
6055                 g_assert (image->assembly->image == image);
6056
6057                 emit_string (acfg, image->assembly_name);
6058                 emit_string (acfg, image->guid);
6059                 emit_string (acfg, aname->culture ? aname->culture : "");
6060                 emit_string (acfg, (const char*)aname->public_key_token);
6061
6062                 emit_alignment (acfg, 8);
6063                 emit_int32 (acfg, aname->flags);
6064                 emit_int32 (acfg, aname->major);
6065                 emit_int32 (acfg, aname->minor);
6066                 emit_int32 (acfg, aname->build);
6067                 emit_int32 (acfg, aname->revision);
6068         }
6069 }
6070
6071 static void
6072 emit_got_info (MonoAotCompile *acfg)
6073 {
6074         char symbol [256];
6075         int i, first_plt_got_patch, buf_size;
6076         guint8 *p, *buf;
6077         guint32 *got_info_offsets;
6078
6079         /* Add the patches needed by the PLT to the GOT */
6080         acfg->plt_got_offset_base = acfg->got_offset;
6081         first_plt_got_patch = acfg->got_patches->len;
6082         for (i = 1; i < acfg->plt_offset; ++i) {
6083                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6084
6085                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6086         }
6087
6088         acfg->got_offset += acfg->plt_offset;
6089
6090         /**
6091          * FIXME: 
6092          * - optimize offsets table.
6093          * - reduce number of exported symbols.
6094          * - emit info for a klass only once.
6095          * - determine when a method uses a GOT slot which is guaranteed to be already 
6096          *   initialized.
6097          * - clean up and document the code.
6098          * - use String.Empty in class libs.
6099          */
6100
6101         /* Encode info required to decode shared GOT entries */
6102         buf_size = acfg->got_patches->len * 128;
6103         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6104         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6105         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6106         /* Unused */
6107         if (acfg->plt_offset)
6108                 acfg->plt_got_info_offsets [0] = 0;
6109         for (i = 0; i < acfg->got_patches->len; ++i) {
6110                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6111
6112                 p = buf;
6113
6114                 encode_value (ji->type, p, &p);
6115                 encode_patch (acfg, ji, p, &p);
6116
6117                 g_assert (p - buf <= buf_size);
6118                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6119
6120                 if (i >= first_plt_got_patch)
6121                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6122                 acfg->stats.got_info_size += p - buf;
6123         }
6124
6125         /* Emit got_info_offsets table */
6126         sprintf (symbol, "got_info_offsets");
6127         emit_section_change (acfg, RODATA_SECT, 1);
6128         emit_alignment (acfg, 8);
6129         emit_label (acfg, symbol);
6130
6131         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6132         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6133 }
6134
6135 static void
6136 emit_got (MonoAotCompile *acfg)
6137 {
6138         char symbol [256];
6139
6140         if (!acfg->llvm) {
6141                 /* Don't make GOT global so accesses to it don't need relocations */
6142                 sprintf (symbol, "%s", acfg->got_symbol);
6143                 emit_section_change (acfg, ".bss", 0);
6144                 emit_alignment (acfg, 8);
6145                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6146                 emit_label (acfg, symbol);
6147                 if (acfg->got_offset > 0)
6148                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6149
6150                 sprintf (symbol, "got_end");
6151                 emit_label (acfg, symbol);
6152         }
6153 }
6154
6155 typedef struct GlobalsTableEntry {
6156         guint32 value, index;
6157         struct GlobalsTableEntry *next;
6158 } GlobalsTableEntry;
6159
6160 static void
6161 emit_globals (MonoAotCompile *acfg)
6162 {
6163         int i, table_size;
6164         guint32 hash;
6165         GPtrArray *table;
6166         char symbol [256];
6167         GlobalsTableEntry *entry, *new_entry;
6168
6169         if (!acfg->aot_opts.static_link)
6170                 return;
6171
6172         /* 
6173          * When static linking, we emit a table containing our globals.
6174          */
6175
6176         /*
6177          * Construct a chained hash table for mapping global names to their index in
6178          * the globals table.
6179          */
6180         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6181         table = g_ptr_array_sized_new (table_size);
6182         for (i = 0; i < table_size; ++i)
6183                 g_ptr_array_add (table, NULL);
6184         for (i = 0; i < acfg->globals->len; ++i) {
6185                 char *name = g_ptr_array_index (acfg->globals, i);
6186
6187                 hash = mono_metadata_str_hash (name) % table_size;
6188
6189                 /* FIXME: Allocate from the mempool */
6190                 new_entry = g_new0 (GlobalsTableEntry, 1);
6191                 new_entry->value = i;
6192
6193                 entry = g_ptr_array_index (table, hash);
6194                 if (entry == NULL) {
6195                         new_entry->index = hash;
6196                         g_ptr_array_index (table, hash) = new_entry;
6197                 } else {
6198                         while (entry->next)
6199                                 entry = entry->next;
6200                         
6201                         entry->next = new_entry;
6202                         new_entry->index = table->len;
6203                         g_ptr_array_add (table, new_entry);
6204                 }
6205         }
6206
6207         /* Emit the table */
6208         sprintf (symbol, ".Lglobals_hash");
6209         emit_section_change (acfg, RODATA_SECT, 0);
6210         emit_alignment (acfg, 8);
6211         emit_label (acfg, symbol);
6212
6213         /* FIXME: Optimize memory usage */
6214         g_assert (table_size < 65000);
6215         emit_int16 (acfg, table_size);
6216         for (i = 0; i < table->len; ++i) {
6217                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6218
6219                 if (entry == NULL) {
6220                         emit_int16 (acfg, 0);
6221                         emit_int16 (acfg, 0);
6222                 } else {
6223                         emit_int16 (acfg, entry->value + 1);
6224                         if (entry->next)
6225                                 emit_int16 (acfg, entry->next->index);
6226                         else
6227                                 emit_int16 (acfg, 0);
6228                 }
6229         }
6230
6231         /* Emit the names */
6232         for (i = 0; i < acfg->globals->len; ++i) {
6233                 char *name = g_ptr_array_index (acfg->globals, i);
6234
6235                 sprintf (symbol, "name_%d", i);
6236                 emit_section_change (acfg, RODATA_SECT, 1);
6237 #ifdef __APPLE__
6238                 emit_alignment (acfg, 4);
6239 #endif
6240                 emit_label (acfg, symbol);
6241                 emit_string (acfg, name);
6242         }
6243
6244         /* Emit the globals table */
6245         sprintf (symbol, "globals");
6246         emit_section_change (acfg, ".data", 0);
6247         /* This is not a global, since it is accessed by the init function */
6248         emit_alignment (acfg, 8);
6249         emit_label (acfg, symbol);
6250
6251         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6252         emit_pointer (acfg, symbol);
6253
6254         for (i = 0; i < acfg->globals->len; ++i) {
6255                 char *name = g_ptr_array_index (acfg->globals, i);
6256
6257                 sprintf (symbol, "name_%d", i);
6258                 emit_pointer (acfg, symbol);
6259
6260                 sprintf (symbol, "%s", name);
6261                 emit_pointer (acfg, symbol);
6262         }
6263         /* Null terminate the table */
6264         emit_int32 (acfg, 0);
6265         emit_int32 (acfg, 0);
6266 }
6267
6268 static void
6269 emit_autoreg (MonoAotCompile *acfg)
6270 {
6271         char *symbol;
6272
6273         /*
6274          * Emit a function into the .ctor section which will be called by the ELF
6275          * loader to register this module with the runtime.
6276          */
6277         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6278                 return;
6279
6280         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6281
6282         arch_emit_autoreg (acfg, symbol);
6283
6284         g_free (symbol);
6285 }       
6286
6287 static void
6288 emit_mem_end (MonoAotCompile *acfg)
6289 {
6290         char symbol [128];
6291
6292         sprintf (symbol, "mem_end");
6293         emit_section_change (acfg, ".text", 1);
6294         emit_alignment (acfg, 8);
6295         emit_label (acfg, symbol);
6296 }
6297
6298 /*
6299  * Emit a structure containing all the information not stored elsewhere.
6300  */
6301 static void
6302 emit_file_info (MonoAotCompile *acfg)
6303 {
6304         char symbol [256];
6305         int i;
6306         int gc_name_offset;
6307         const char *gc_name;
6308         char *build_info;
6309
6310         emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6311
6312         if (acfg->aot_opts.bind_to_runtime_version) {
6313                 build_info = mono_get_runtime_build_info ();
6314                 emit_string_symbol (acfg, "runtime_version", build_info);
6315                 g_free (build_info);
6316         } else {
6317                 emit_string_symbol (acfg, "runtime_version", "");
6318         }
6319
6320         /* Emit a string holding the assembly name */
6321         emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6322
6323         /*
6324          * The managed allocators are GC specific, so can't use an AOT image created by one GC
6325          * in another.
6326          */
6327         gc_name = mono_gc_get_gc_name ();
6328         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6329
6330         sprintf (symbol, "mono_aot_file_info");
6331         emit_section_change (acfg, ".data", 0);
6332         emit_alignment (acfg, 8);
6333         emit_label (acfg, symbol);
6334         if (!acfg->aot_opts.static_link)
6335                 emit_global (acfg, symbol, FALSE);
6336
6337         /* The data emitted here must match MonoAotFileInfo. */
6338
6339         emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6340         emit_int32 (acfg, 0);
6341
6342         /* 
6343          * We emit pointers to our data structures instead of emitting global symbols which
6344          * point to them, to reduce the number of globals, and because using globals leads to
6345          * various problems (i.e. arm/thumb).
6346          */
6347         emit_pointer (acfg, acfg->got_symbol);
6348         emit_pointer (acfg, "methods");
6349         if (acfg->llvm) {
6350                 /*
6351                  * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6352                  */
6353                 emit_pointer (acfg, "mono_eh_frame");
6354         } else {
6355                 emit_pointer (acfg, NULL);
6356         }
6357         emit_pointer (acfg, "blob");
6358         emit_pointer (acfg, "class_name_table");
6359         emit_pointer (acfg, "class_info_offsets");
6360         emit_pointer (acfg, "method_info_offsets");
6361         emit_pointer (acfg, "ex_info_offsets");
6362         emit_pointer (acfg, "code_offsets");
6363         emit_pointer (acfg, "extra_method_info_offsets");
6364         emit_pointer (acfg, "extra_method_table");
6365         emit_pointer (acfg, "got_info_offsets");
6366         emit_pointer (acfg, "methods_end");
6367         emit_pointer (acfg, "unwind_info");
6368         emit_pointer (acfg, "mem_end");
6369         emit_pointer (acfg, "image_table");
6370         emit_pointer (acfg, "plt");
6371         emit_pointer (acfg, "plt_end");
6372         emit_pointer (acfg, "assembly_guid");
6373         emit_pointer (acfg, "runtime_version");
6374         if (acfg->num_trampoline_got_entries) {
6375                 emit_pointer (acfg, "specific_trampolines");
6376                 emit_pointer (acfg, "static_rgctx_trampolines");
6377                 emit_pointer (acfg, "imt_thunks");
6378         } else {
6379                 emit_pointer (acfg, NULL);
6380                 emit_pointer (acfg, NULL);
6381                 emit_pointer (acfg, NULL);
6382         }
6383         if (acfg->thumb_mixed) {
6384                 emit_pointer (acfg, "thumb_end");
6385         } else {
6386                 emit_pointer (acfg, NULL);
6387         }
6388         if (acfg->aot_opts.static_link) {
6389                 emit_pointer (acfg, "globals");
6390         } else {
6391                 emit_pointer (acfg, NULL);
6392         }
6393         emit_pointer (acfg, "assembly_name");
6394
6395         emit_int32 (acfg, acfg->plt_got_offset_base);
6396         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6397         emit_int32 (acfg, acfg->plt_offset);
6398         emit_int32 (acfg, acfg->nmethods);
6399         emit_int32 (acfg, acfg->flags);
6400         emit_int32 (acfg, acfg->opts);
6401         emit_int32 (acfg, gc_name_offset);
6402
6403         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6404                 emit_int32 (acfg, acfg->num_trampolines [i]);
6405         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6406                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6407         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6408                 emit_int32 (acfg, acfg->trampoline_size [i]);
6409
6410 #if defined (TARGET_ARM) && defined (__APPLE__)
6411        {
6412                MonoType t;
6413                int align = 0;
6414
6415                t.type = MONO_TYPE_R8;
6416                mono_type_size (&t, &align);
6417
6418                emit_int32 (acfg, align);
6419
6420                t.type = MONO_TYPE_I8;
6421                mono_type_size (&t, &align);
6422
6423                emit_int32 (acfg, align);
6424        }
6425 #else
6426         emit_int32 (acfg, __alignof__ (double));
6427         emit_int32 (acfg, __alignof__ (gint64));
6428 #endif
6429
6430         if (acfg->aot_opts.static_link) {
6431                 char *p;
6432
6433                 /* 
6434                  * Emit a global symbol which can be passed by an embedding app to
6435                  * mono_aot_register_module (). The symbol points to a pointer to the the file info
6436                  * structure.
6437                  */
6438 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6439                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6440 #else
6441                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6442 #endif
6443
6444                 /* Get rid of characters which cannot occur in symbols */
6445                 p = symbol;
6446                 for (p = symbol; *p; ++p) {
6447                         if (!(isalnum (*p) || *p == '_'))
6448                                 *p = '_';
6449                 }
6450                 acfg->static_linking_symbol = g_strdup (symbol);
6451                 emit_global_inner (acfg, symbol, FALSE);
6452                 emit_label (acfg, symbol);
6453                 emit_pointer (acfg, "mono_aot_file_info");
6454         }
6455 }
6456
6457 static void
6458 emit_blob (MonoAotCompile *acfg)
6459 {
6460         char symbol [128];
6461
6462         sprintf (symbol, "blob");
6463         emit_section_change (acfg, RODATA_SECT, 1);
6464         emit_alignment (acfg, 8);
6465         emit_label (acfg, symbol);
6466
6467         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6468 }
6469
6470 static void
6471 emit_dwarf_info (MonoAotCompile *acfg)
6472 {
6473 #ifdef EMIT_DWARF_INFO
6474         int i;
6475         char symbol [128], symbol2 [128];
6476
6477         /* DIEs for methods */
6478         for (i = 0; i < acfg->nmethods; ++i) {
6479                 MonoCompile *cfg = acfg->cfgs [i];
6480
6481                 if (!cfg)
6482                         continue;
6483
6484                 // FIXME: LLVM doesn't define .Lme_...
6485                 if (cfg->compile_llvm)
6486                         continue;
6487
6488                 sprintf (symbol, "%s", cfg->asm_symbol);
6489                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6490
6491                 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 ()));
6492         }
6493 #endif
6494 }
6495
6496 static void
6497 collect_methods (MonoAotCompile *acfg)
6498 {
6499         int i;
6500         MonoImage *image = acfg->image;
6501
6502         /* Collect methods */
6503         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6504                 MonoMethod *method;
6505                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6506
6507                 method = mono_get_method (acfg->image, token, NULL);
6508
6509                 if (!method) {
6510                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6511                         exit (1);
6512                 }
6513                         
6514                 /* Load all methods eagerly to skip the slower lazy loading code */
6515                 mono_class_setup_methods (method->klass);
6516
6517                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6518                         /* Compile the wrapper instead */
6519                         /* We do this here instead of add_wrappers () because it is easy to do it here */
6520                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6521                         method = wrapper;
6522                 }
6523
6524                 /* FIXME: Some mscorlib methods don't have debug info */
6525                 /*
6526                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6527                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6528                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6529                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6530                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6531                                 if (!mono_debug_lookup_method (method)) {
6532                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6533                                         exit (1);
6534                                 }
6535                         }
6536                 }
6537                 */
6538
6539                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6540                 add_method_with_index (acfg, method, i, FALSE);
6541                 acfg->method_index ++;
6542         }
6543
6544         add_generic_instances (acfg);
6545
6546         if (acfg->aot_opts.full_aot)
6547                 add_wrappers (acfg);
6548 }
6549
6550 static void
6551 compile_methods (MonoAotCompile *acfg)
6552 {
6553         int i, methods_len;
6554
6555         if (acfg->aot_opts.nthreads > 0) {
6556                 GPtrArray *frag;
6557                 int len, j;
6558                 GPtrArray *threads;
6559                 HANDLE handle;
6560                 gpointer *user_data;
6561                 MonoMethod **methods;
6562
6563                 methods_len = acfg->methods->len;
6564
6565                 len = acfg->methods->len / acfg->aot_opts.nthreads;
6566                 g_assert (len > 0);
6567                 /* 
6568                  * Partition the list of methods into fragments, and hand it to threads to
6569                  * process.
6570                  */
6571                 threads = g_ptr_array_new ();
6572                 /* Make a copy since acfg->methods is modified by compile_method () */
6573                 methods = g_new0 (MonoMethod*, methods_len);
6574                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6575                 for (i = 0; i < methods_len; ++i)
6576                         methods [i] = g_ptr_array_index (acfg->methods, i);
6577                 i = 0;
6578                 while (i < methods_len) {
6579                         frag = g_ptr_array_new ();
6580                         for (j = 0; j < len; ++j) {
6581                                 if (i < methods_len) {
6582                                         g_ptr_array_add (frag, methods [i]);
6583                                         i ++;
6584                                 }
6585                         }
6586
6587                         user_data = g_new0 (gpointer, 3);
6588                         user_data [0] = mono_domain_get ();
6589                         user_data [1] = acfg;
6590                         user_data [2] = frag;
6591                         
6592                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6593                         g_ptr_array_add (threads, handle);
6594                 }
6595                 g_free (methods);
6596
6597                 for (i = 0; i < threads->len; ++i) {
6598                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6599                 }
6600         } else {
6601                 methods_len = 0;
6602         }
6603
6604         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6605         for (i = methods_len; i < acfg->methods->len; ++i) {
6606                 /* This can new methods to acfg->methods */
6607                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6608         }
6609 }
6610
6611 static int
6612 compile_asm (MonoAotCompile *acfg)
6613 {
6614         char *command, *objfile;
6615         char *outfile_name, *tmp_outfile_name;
6616         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6617
6618 #if defined(TARGET_AMD64)
6619 #define AS_OPTIONS "--64"
6620 #elif defined(TARGET_POWERPC64)
6621 #define AS_OPTIONS "-a64 -mppc64"
6622 #define LD_OPTIONS "-m elf64ppc"
6623 #elif defined(sparc) && SIZEOF_VOID_P == 8
6624 #define AS_OPTIONS "-xarch=v9"
6625 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6626 #define AS_OPTIONS "-arch i386 -W"
6627 #else
6628 #define AS_OPTIONS ""
6629 #endif
6630
6631 #ifdef __native_client_codegen__
6632 #if defined(TARGET_AMD64)
6633 #define AS_NAME "nacl64-as"
6634 #else
6635 #define AS_NAME "nacl-as"
6636 #endif
6637 #else
6638 #define AS_NAME "as"
6639 #endif
6640
6641 #ifndef LD_OPTIONS
6642 #define LD_OPTIONS ""
6643 #endif
6644
6645 #define EH_LD_OPTIONS ""
6646
6647         if (acfg->aot_opts.asm_only) {
6648                 printf ("Output file: '%s'.\n", acfg->tmpfname);
6649                 if (acfg->aot_opts.static_link)
6650                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6651                 return 0;
6652         }
6653
6654         if (acfg->aot_opts.static_link) {
6655                 if (acfg->aot_opts.outfile)
6656                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6657                 else
6658                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
6659         } else {
6660                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6661         }
6662         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);
6663         printf ("Executing the native assembler: %s\n", command);
6664         if (system (command) != 0) {
6665                 g_free (command);
6666                 g_free (objfile);
6667                 return 1;
6668         }
6669
6670         g_free (command);
6671
6672         if (acfg->aot_opts.static_link) {
6673                 printf ("Output file: '%s'.\n", objfile);
6674                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6675                 g_free (objfile);
6676                 return 0;
6677         }
6678
6679         if (acfg->aot_opts.outfile)
6680                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6681         else
6682                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6683
6684         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6685
6686 #if defined(sparc)
6687         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6688 #elif defined(__ppc__) && defined(__APPLE__)
6689         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6690 #elif defined(HOST_WIN32)
6691         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6692 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6693         command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6694 #else
6695         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6696 #endif
6697         printf ("Executing the native linker: %s\n", command);
6698         if (system (command) != 0) {
6699                 g_free (tmp_outfile_name);
6700                 g_free (outfile_name);
6701                 g_free (command);
6702                 g_free (objfile);
6703                 return 1;
6704         }
6705
6706         g_free (command);
6707         unlink (objfile);
6708         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6709         printf ("Stripping the binary: %s\n", com);
6710         system (com);
6711         g_free (com);*/
6712
6713 #if defined(TARGET_ARM) && !defined(__APPLE__)
6714         /* 
6715          * gas generates 'mapping symbols' each time code and data is mixed, which 
6716          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6717          */
6718         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6719         printf ("Stripping the binary: %s\n", command);
6720         if (system (command) != 0) {
6721                 g_free (tmp_outfile_name);
6722                 g_free (outfile_name);
6723                 g_free (command);
6724                 g_free (objfile);
6725                 return 1;
6726         }
6727 #endif
6728
6729         rename (tmp_outfile_name, outfile_name);
6730
6731         g_free (tmp_outfile_name);
6732         g_free (outfile_name);
6733         g_free (objfile);
6734
6735         if (acfg->aot_opts.save_temps)
6736                 printf ("Retained input file.\n");
6737         else
6738                 unlink (acfg->tmpfname);
6739
6740         return 0;
6741 }
6742
6743 static MonoAotCompile*
6744 acfg_create (MonoAssembly *ass, guint32 opts)
6745 {
6746         MonoImage *image = ass->image;
6747         MonoAotCompile *acfg;
6748         int i;
6749
6750         acfg = g_new0 (MonoAotCompile, 1);
6751         acfg->methods = g_ptr_array_new ();
6752         acfg->method_indexes = g_hash_table_new (NULL, NULL);
6753         acfg->method_depth = g_hash_table_new (NULL, NULL);
6754         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6755         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6756         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6757         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6758         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6759                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6760         acfg->got_patches = g_ptr_array_new ();
6761         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6762         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6763         acfg->image_hash = g_hash_table_new (NULL, NULL);
6764         acfg->image_table = g_ptr_array_new ();
6765         acfg->globals = g_ptr_array_new ();
6766         acfg->image = image;
6767         acfg->opts = opts;
6768         acfg->mempool = mono_mempool_new ();
6769         acfg->extra_methods = g_ptr_array_new ();
6770         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6771         acfg->unwind_ops = g_ptr_array_new ();
6772         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6773         InitializeCriticalSection (&acfg->mutex);
6774
6775         return acfg;
6776 }
6777
6778 static void
6779 acfg_free (MonoAotCompile *acfg)
6780 {
6781         int i;
6782
6783         img_writer_destroy (acfg->w);
6784         for (i = 0; i < acfg->nmethods; ++i)
6785                 if (acfg->cfgs [i])
6786                         g_free (acfg->cfgs [i]);
6787         g_free (acfg->cfgs);
6788         g_free (acfg->static_linking_symbol);
6789         g_free (acfg->got_symbol);
6790         g_free (acfg->plt_symbol);
6791         g_ptr_array_free (acfg->methods, TRUE);
6792         g_ptr_array_free (acfg->got_patches, TRUE);
6793         g_ptr_array_free (acfg->image_table, TRUE);
6794         g_ptr_array_free (acfg->globals, TRUE);
6795         g_ptr_array_free (acfg->unwind_ops, TRUE);
6796         g_hash_table_destroy (acfg->method_indexes);
6797         g_hash_table_destroy (acfg->method_depth);
6798         g_hash_table_destroy (acfg->plt_offset_to_entry);
6799         g_hash_table_destroy (acfg->patch_to_plt_entry);
6800         g_hash_table_destroy (acfg->patch_to_got_offset);
6801         g_hash_table_destroy (acfg->method_to_cfg);
6802         g_hash_table_destroy (acfg->token_info_hash);
6803         g_hash_table_destroy (acfg->image_hash);
6804         g_hash_table_destroy (acfg->unwind_info_offsets);
6805         g_hash_table_destroy (acfg->method_label_hash);
6806         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6807                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6808         g_free (acfg->patch_to_got_offset_by_type);
6809         mono_mempool_destroy (acfg->mempool);
6810         g_free (acfg);
6811 }
6812
6813 int
6814 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6815 {
6816         MonoImage *image = ass->image;
6817         int i, res;
6818         MonoAotCompile *acfg;
6819         char *outfile_name, *tmp_outfile_name, *p;
6820         TV_DECLARE (atv);
6821         TV_DECLARE (btv);
6822
6823         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6824
6825         acfg = acfg_create (ass, opts);
6826
6827         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6828         acfg->aot_opts.write_symbols = TRUE;
6829         acfg->aot_opts.ntrampolines = 1024;
6830         acfg->aot_opts.nrgctx_trampolines = 1024;
6831         acfg->aot_opts.nimt_trampolines = 128;
6832         acfg->aot_opts.llvm_path = g_strdup ("");
6833
6834         mono_aot_parse_options (aot_options, &acfg->aot_opts);
6835
6836         if (acfg->aot_opts.static_link)
6837                 acfg->aot_opts.autoreg = TRUE;
6838
6839         //acfg->aot_opts.print_skipped_methods = TRUE;
6840
6841 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6842         if (acfg->aot_opts.full_aot) {
6843                 printf ("--aot=full is not supported on this platform.\n");
6844                 return 1;
6845         }
6846 #endif
6847
6848         if (acfg->aot_opts.static_link)
6849                 acfg->aot_opts.asm_writer = TRUE;
6850
6851         if (acfg->aot_opts.soft_debug) {
6852                 MonoDebugOptions *opt = mini_get_debug_options ();
6853
6854                 opt->mdb_optimizations = TRUE;
6855                 opt->gen_seq_points = TRUE;
6856
6857                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6858                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6859                         return 1;
6860                 }
6861                 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6862         }
6863
6864         if (mono_use_llvm) {
6865                 acfg->llvm = TRUE;
6866                 acfg->aot_opts.asm_writer = TRUE;
6867                 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6868
6869                 if (acfg->aot_opts.soft_debug) {
6870                         fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6871                         exit (1);
6872                 }
6873         }
6874
6875         if (acfg->aot_opts.full_aot)
6876                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6877
6878         load_profile_files (acfg);
6879
6880         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6881 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6882         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6883 #endif
6884         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6885
6886         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6887
6888         arch_init (acfg);
6889
6890         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6891         acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6892
6893         /* Get rid of characters which cannot occur in symbols */
6894         for (p = acfg->got_symbol_base; *p; ++p) {
6895                 if (!(isalnum (*p) || *p == '_'))
6896                         *p = '_';
6897         }
6898         for (p = acfg->plt_symbol; *p; ++p) {
6899                 if (!(isalnum (*p) || *p == '_'))
6900                         *p = '_';
6901         }
6902
6903         acfg->method_index = 1;
6904
6905         collect_methods (acfg);
6906
6907         acfg->cfgs_size = acfg->methods->len + 32;
6908         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6909
6910         /* PLT offset 0 is reserved for the PLT trampoline */
6911         acfg->plt_offset = 1;
6912
6913 #ifdef ENABLE_LLVM
6914         if (acfg->llvm) {
6915                 llvm_acfg = acfg;
6916                 mono_llvm_create_aot_module (acfg->got_symbol_base);
6917         }
6918 #endif
6919
6920         /* GOT offset 0 is reserved for the address of the current assembly */
6921         {
6922                 MonoJumpInfo *ji;
6923
6924                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6925                 ji->type = MONO_PATCH_INFO_IMAGE;
6926                 ji->data.image = acfg->image;
6927
6928                 get_got_offset (acfg, ji);
6929
6930                 /* Slot 1 is reserved for the mscorlib got addr */
6931                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6932                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6933                 get_got_offset (acfg, ji);
6934
6935                 /* This is very common */
6936                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6937                 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6938                 get_got_offset (acfg, ji);
6939         }
6940
6941         TV_GETTIME (atv);
6942
6943         compile_methods (acfg);
6944
6945         TV_GETTIME (btv);
6946
6947         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6948
6949         TV_GETTIME (atv);
6950
6951 #ifdef ENABLE_LLVM
6952         if (acfg->llvm) {
6953                 if (acfg->aot_opts.asm_only) {
6954                         if (acfg->aot_opts.outfile)
6955                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6956                         else
6957                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6958                 } else {
6959                         acfg->tmpfname = g_strdup ("temp.s");
6960                 }
6961
6962                 emit_llvm_file (acfg);
6963         }
6964 #endif
6965
6966         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6967                 if (acfg->aot_opts.outfile)
6968                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6969                 else
6970                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6971
6972                 /* 
6973                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
6974                  * it might be in another file system so the rename () won't work.
6975                  */
6976                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6977
6978                 acfg->fp = fopen (tmp_outfile_name, "w");
6979                 if (!acfg->fp) {
6980                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6981                         return 1;
6982                 }
6983
6984                 acfg->w = img_writer_create (acfg->fp, TRUE);
6985                 acfg->use_bin_writer = TRUE;
6986         } else {
6987                 if (acfg->llvm) {
6988                         /* Append to the .s file created by llvm */
6989                         /* FIXME: Use multiple files instead */
6990                         acfg->fp = fopen (acfg->tmpfname, "a+");
6991                 } else {
6992                         if (acfg->aot_opts.asm_only) {
6993                                 if (acfg->aot_opts.outfile)
6994                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6995                                 else
6996                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6997                                 acfg->fp = fopen (acfg->tmpfname, "w+");
6998                         } else {
6999                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7000                                 acfg->fp = fdopen (i, "w+");
7001                         }
7002                         g_assert (acfg->fp);
7003                 }
7004                 acfg->w = img_writer_create (acfg->fp, FALSE);
7005                 
7006                 tmp_outfile_name = NULL;
7007                 outfile_name = NULL;
7008         }
7009
7010         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7011
7012         /* Compute symbols for methods */
7013         for (i = 0; i < acfg->nmethods; ++i) {
7014                 if (acfg->cfgs [i]) {
7015                         MonoCompile *cfg = acfg->cfgs [i];
7016                         int method_index = get_method_index (acfg, cfg->orig_method);
7017
7018                         if (COMPILE_LLVM (cfg))
7019                                 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7020                         else
7021                                 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7022                 }
7023         }
7024
7025         if (!acfg->aot_opts.nodebug)
7026                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7027
7028         img_writer_emit_start (acfg->w);
7029
7030         if (acfg->dwarf)
7031                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7032
7033         if (acfg->thumb_mixed) {
7034                 char symbol [256];
7035                 /*
7036                  * This global symbol marks the end of THUMB code, and the beginning of ARM
7037                  * code generated by our JIT.
7038                  */
7039                 sprintf (symbol, "thumb_end");
7040                 emit_section_change (acfg, ".text", 0);
7041                 emit_label (acfg, symbol);
7042                 emit_zero_bytes (acfg, 16);
7043
7044                 fprintf (acfg->fp, ".arm\n");
7045         }
7046
7047         emit_code (acfg);
7048
7049         emit_info (acfg);
7050
7051         emit_extra_methods (acfg);
7052
7053         emit_trampolines (acfg);
7054
7055         emit_class_name_table (acfg);
7056
7057         emit_got_info (acfg);
7058
7059         emit_exception_info (acfg);
7060
7061         emit_unwind_info (acfg);
7062
7063         emit_class_info (acfg);
7064
7065         emit_plt (acfg);
7066
7067         emit_image_table (acfg);
7068
7069         emit_got (acfg);
7070
7071         emit_file_info (acfg);
7072
7073         emit_blob (acfg);
7074
7075         emit_globals (acfg);
7076
7077         emit_autoreg (acfg);
7078
7079         if (acfg->dwarf) {
7080                 emit_dwarf_info (acfg);
7081                 mono_dwarf_writer_close (acfg->dwarf);
7082         }
7083
7084         emit_mem_end (acfg);
7085
7086         if (acfg->need_pt_gnu_stack) {
7087                 /* This is required so the .so doesn't have an executable stack */
7088                 /* The bin writer already emits this */
7089                 if (!acfg->use_bin_writer)
7090                         fprintf (acfg->fp, "\n.section  .note.GNU-stack,\"\",@progbits\n");
7091         }
7092
7093         TV_GETTIME (btv);
7094
7095         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7096
7097         if (acfg->llvm)
7098                 g_assert (acfg->got_offset <= acfg->final_got_size);
7099
7100         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);
7101
7102         TV_GETTIME (atv);
7103         res = img_writer_emit_writeout (acfg->w);
7104         if (res != 0) {
7105                 acfg_free (acfg);
7106                 return res;
7107         }
7108         if (acfg->use_bin_writer) {
7109                 int err = rename (tmp_outfile_name, outfile_name);
7110
7111                 if (err) {
7112                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7113                         return 1;
7114                 }
7115         } else {
7116                 res = compile_asm (acfg);
7117                 if (res != 0) {
7118                         acfg_free (acfg);
7119                         return res;
7120                 }
7121         }
7122         TV_GETTIME (btv);
7123         acfg->stats.link_time = TV_ELAPSED (atv, btv);
7124
7125         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);
7126         if (acfg->stats.genericcount)
7127                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7128         if (acfg->stats.abscount)
7129                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7130         if (acfg->stats.lmfcount)
7131                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7132         if (acfg->stats.ocount)
7133                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7134         if (acfg->llvm)
7135                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7136         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);
7137         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7138
7139         if (acfg->aot_opts.stats) {
7140                 int i;
7141
7142                 printf ("GOT slot distribution:\n");
7143                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7144                         if (acfg->stats.got_slot_types [i])
7145                                 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7146         }
7147
7148         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);
7149
7150         acfg_free (acfg);
7151         
7152         return 0;
7153 }
7154
7155 #else
7156
7157 /* AOT disabled */
7158
7159 int
7160 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7161 {
7162         return 0;
7163 }
7164
7165 #endif