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