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