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