Add support to the x86 backend for generating code compatible with Google
[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                 break;
3197         case MONO_PATCH_INFO_METHOD_REL:
3198                 encode_value ((gint)patch_info->data.offset, p, &p);
3199                 break;
3200         case MONO_PATCH_INFO_SWITCH: {
3201                 gpointer *table = (gpointer *)patch_info->data.table->table;
3202                 int k;
3203
3204                 encode_value (patch_info->data.table->table_size, p, &p);
3205                 for (k = 0; k < patch_info->data.table->table_size; k++)
3206                         encode_value ((int)(gssize)table [k], p, &p);
3207                 break;
3208         }
3209         case MONO_PATCH_INFO_METHODCONST:
3210         case MONO_PATCH_INFO_METHOD:
3211         case MONO_PATCH_INFO_METHOD_JUMP:
3212         case MONO_PATCH_INFO_ICALL_ADDR:
3213         case MONO_PATCH_INFO_METHOD_RGCTX:
3214                 encode_method_ref (acfg, patch_info->data.method, p, &p);
3215                 break;
3216         case MONO_PATCH_INFO_INTERNAL_METHOD:
3217         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3218                 guint32 len = strlen (patch_info->data.name);
3219
3220                 encode_value (len, p, &p);
3221
3222                 memcpy (p, patch_info->data.name, len);
3223                 p += len;
3224                 *p++ = '\0';
3225                 break;
3226         }
3227         case MONO_PATCH_INFO_LDSTR: {
3228                 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3229                 guint32 token = patch_info->data.token->token;
3230                 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3231                 encode_value (image_index, p, &p);
3232                 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3233                 break;
3234         }
3235         case MONO_PATCH_INFO_RVA:
3236         case MONO_PATCH_INFO_DECLSEC:
3237         case MONO_PATCH_INFO_LDTOKEN:
3238         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3239                 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3240                 encode_value (patch_info->data.token->token, p, &p);
3241                 encode_value (patch_info->data.token->has_context, p, &p);
3242                 if (patch_info->data.token->has_context)
3243                         encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3244                 break;
3245         case MONO_PATCH_INFO_EXC_NAME: {
3246                 MonoClass *ex_class;
3247
3248                 ex_class =
3249                         mono_class_from_name (mono_defaults.exception_class->image,
3250                                                                   "System", patch_info->data.target);
3251                 g_assert (ex_class);
3252                 encode_klass_ref (acfg, ex_class, p, &p);
3253                 break;
3254         }
3255         case MONO_PATCH_INFO_R4:
3256                 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3257                 break;
3258         case MONO_PATCH_INFO_R8:
3259                 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3260                 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3261                 break;
3262         case MONO_PATCH_INFO_VTABLE:
3263         case MONO_PATCH_INFO_CLASS:
3264         case MONO_PATCH_INFO_IID:
3265         case MONO_PATCH_INFO_ADJUSTED_IID:
3266                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3267                 break;
3268         case MONO_PATCH_INFO_CLASS_INIT:
3269         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3270                 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3271                 break;
3272         case MONO_PATCH_INFO_FIELD:
3273         case MONO_PATCH_INFO_SFLDA:
3274                 encode_field_info (acfg, patch_info->data.field, p, &p);
3275                 break;
3276         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3277                 break;
3278         case MONO_PATCH_INFO_RGCTX_FETCH: {
3279                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3280
3281                 encode_method_ref (acfg, entry->method, p, &p);
3282                 encode_value (entry->in_mrgctx, p, &p);
3283                 encode_value (entry->info_type, p, &p);
3284                 encode_value (entry->data->type, p, &p);
3285                 encode_patch (acfg, entry->data, p, &p);
3286                 break;
3287         }
3288         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3289         case MONO_PATCH_INFO_MONITOR_ENTER:
3290         case MONO_PATCH_INFO_MONITOR_EXIT:
3291         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3292                 break;
3293         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3294                 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3295                 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3296                 break;
3297         default:
3298                 g_warning ("unable to handle jump info %d", patch_info->type);
3299                 g_assert_not_reached ();
3300         }
3301
3302         *endbuf = p;
3303 }
3304
3305 static void
3306 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3307 {
3308         guint8 *p = buf;
3309         guint32 pindex, offset;
3310         MonoJumpInfo *patch_info;
3311
3312         encode_value (n_patches, p, &p);
3313
3314         for (pindex = 0; pindex < patches->len; ++pindex) {
3315                 patch_info = g_ptr_array_index (patches, pindex);
3316
3317                 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3318                         /* Nothing to do */
3319                         continue;
3320
3321                 offset = get_got_offset (acfg, patch_info);
3322                 encode_value (offset, p, &p);
3323         }
3324
3325         *endbuf = p;
3326 }
3327
3328 static void
3329 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3330 {
3331         MonoMethod *method;
3332         GList *l;
3333         int pindex, buf_size, n_patches;
3334         guint8 *code;
3335         GPtrArray *patches;
3336         MonoJumpInfo *patch_info;
3337         MonoMethodHeader *header;
3338         guint32 method_index;
3339         guint8 *p, *buf;
3340         guint32 first_got_offset;
3341
3342         method = cfg->orig_method;
3343         code = cfg->native_code;
3344         header = mono_method_get_header (method);
3345
3346         method_index = get_method_index (acfg, method);
3347
3348         /* Sort relocations */
3349         patches = g_ptr_array_new ();
3350         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3351                 g_ptr_array_add (patches, patch_info);
3352         g_ptr_array_sort (patches, compare_patches);
3353
3354         first_got_offset = acfg->cfgs [method_index]->got_offset;
3355
3356         /**********************/
3357         /* Encode method info */
3358         /**********************/
3359
3360         buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3361         p = buf = g_malloc (buf_size);
3362
3363         if (mono_class_get_cctor (method->klass))
3364                 encode_klass_ref (acfg, method->klass, p, &p);
3365         else
3366                 /* Not needed when loading the method */
3367                 encode_value (0, p, &p);
3368
3369         /* String table */
3370         if (cfg->opt & MONO_OPT_SHARED) {
3371                 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3372                 for (l = cfg->ldstr_list; l; l = l->next) {
3373                         encode_value ((long)l->data, p, &p);
3374                 }
3375         }
3376         else
3377                 /* Used only in shared mode */
3378                 g_assert (!cfg->ldstr_list);
3379
3380         n_patches = 0;
3381         for (pindex = 0; pindex < patches->len; ++pindex) {
3382                 patch_info = g_ptr_array_index (patches, pindex);
3383                 
3384                 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3385                         (patch_info->type == MONO_PATCH_INFO_NONE)) {
3386                         patch_info->type = MONO_PATCH_INFO_NONE;
3387                         /* Nothing to do */
3388                         continue;
3389                 }
3390
3391                 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3392                         /* Stored in a GOT slot initialized at module load time */
3393                         patch_info->type = MONO_PATCH_INFO_NONE;
3394                         continue;
3395                 }
3396
3397                 if (is_plt_patch (patch_info)) {
3398                         /* Calls are made through the PLT */
3399                         patch_info->type = MONO_PATCH_INFO_NONE;
3400                         continue;
3401                 }
3402
3403                 n_patches ++;
3404         }
3405
3406         if (n_patches)
3407                 g_assert (cfg->has_got_slots);
3408
3409         encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3410
3411         acfg->stats.info_size += p - buf;
3412
3413         g_assert (p - buf < buf_size);
3414
3415         cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3416         g_free (buf);
3417 }
3418
3419 static guint32
3420 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3421 {
3422         guint32 cache_index;
3423         guint32 offset;
3424
3425         /* Reuse the unwind module to canonize and store unwind info entries */
3426         cache_index = mono_cache_unwind_info (encoded, encoded_len);
3427
3428         /* Use +/- 1 to distinguish 0s from missing entries */
3429         offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3430         if (offset)
3431                 return offset - 1;
3432         else {
3433                 guint8 buf [16];
3434                 guint8 *p;
3435
3436                 /* 
3437                  * It would be easier to use assembler symbols, but the caller needs an
3438                  * offset now.
3439                  */
3440                 offset = acfg->unwind_info_offset;
3441                 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3442                 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3443
3444                 p = buf;
3445                 encode_value (encoded_len, p, &p);
3446
3447                 acfg->unwind_info_offset += encoded_len + (p - buf);
3448                 return offset;
3449         }
3450 }
3451
3452 static void
3453 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3454 {
3455         MonoMethod *method;
3456         int i, k, buf_size, method_index;
3457         guint32 debug_info_size;
3458         guint8 *code;
3459         MonoMethodHeader *header;
3460         guint8 *p, *buf, *debug_info;
3461         MonoJitInfo *jinfo = cfg->jit_info;
3462         guint32 flags;
3463         gboolean use_unwind_ops = FALSE;
3464         MonoSeqPointInfo *seq_points;
3465
3466         method = cfg->orig_method;
3467         code = cfg->native_code;
3468         header = cfg->header;
3469
3470         method_index = get_method_index (acfg, method);
3471
3472         if (!acfg->aot_opts.nodebug) {
3473                 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3474         } else {
3475                 debug_info = NULL;
3476                 debug_info_size = 0;
3477         }
3478
3479         seq_points = cfg->seq_point_info;
3480
3481         buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3482         p = buf = g_malloc (buf_size);
3483
3484 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3485         use_unwind_ops = cfg->unwind_ops != NULL;
3486 #endif
3487
3488         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);
3489
3490         encode_value (flags, p, &p);
3491
3492         if (use_unwind_ops) {
3493                 guint32 encoded_len;
3494                 guint8 *encoded;
3495
3496                 /* 
3497                  * This is a duplicate of the data in the .debug_frame section, but that
3498                  * section cannot be accessed using the dl interface.
3499                  */
3500                 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3501                 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3502                 g_free (encoded);
3503         } else {
3504                 encode_value (jinfo->used_regs, p, &p);
3505         }
3506
3507         /*Encode the number of holes before the number of clauses to make decoding easier*/
3508         if (jinfo->has_try_block_holes) {
3509                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3510                 encode_value (table->num_holes, p, &p);
3511         }
3512
3513         /* Exception table */
3514         if (cfg->compile_llvm) {
3515                 /*
3516                  * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3517                  * since the information is only available to llc. Instead, we let llc save the data
3518                  * into the LSDA, and read it from there at runtime.
3519                  */
3520                 /* The assembly might be CIL stripped so emit the data ourselves */
3521                 if (header->num_clauses)
3522                         encode_value (header->num_clauses, p, &p);
3523
3524                 for (k = 0; k < header->num_clauses; ++k) {
3525                         MonoExceptionClause *clause;
3526
3527                         clause = &header->clauses [k];
3528
3529                         encode_value (clause->flags, p, &p);
3530                         if (clause->data.catch_class) {
3531                                 encode_value (1, p, &p);
3532                                 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3533                         } else {
3534                                 encode_value (0, p, &p);
3535                         }
3536
3537                         /* Emit a list of nesting clauses */
3538                         for (i = 0; i < header->num_clauses; ++i) {
3539                                 gint32 cindex1 = k;
3540                                 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3541                                 gint32 cindex2 = i;
3542                                 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3543
3544                                 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3545                                         encode_value (i, p, &p);
3546                         }
3547                         encode_value (-1, p, &p);
3548                 }
3549         } else {
3550                 if (jinfo->num_clauses)
3551                         encode_value (jinfo->num_clauses, p, &p);
3552
3553                 for (k = 0; k < jinfo->num_clauses; ++k) {
3554                         MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3555
3556                         encode_value (ei->flags, p, &p);
3557                         encode_value (ei->exvar_offset, p, &p);
3558
3559                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3560                                 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3561                         else {
3562                                 if (ei->data.catch_class) {
3563                                         encode_value (1, p, &p);
3564                                         encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3565                                 } else {
3566                                         encode_value (0, p, &p);
3567                                 }
3568                         }
3569
3570                         encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3571                         encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3572                         encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3573                 }
3574         }
3575
3576         if (jinfo->has_generic_jit_info) {
3577                 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3578
3579                 if (!cfg->compile_llvm) {
3580                         encode_value (gi->has_this ? 1 : 0, p, &p);
3581                         encode_value (gi->this_reg, p, &p);
3582                         encode_value (gi->this_offset, p, &p);
3583                 }
3584
3585                 /* 
3586                  * Need to encode jinfo->method too, since it is not equal to 'method'
3587                  * when using generic sharing.
3588                  */
3589                 encode_method_ref (acfg, jinfo->method, p, &p);
3590         }
3591
3592         if (jinfo->has_try_block_holes) {
3593                 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3594                 for (i = 0; i < table->num_holes; ++i) {
3595                         MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3596                         encode_value (hole->clause, p, &p);
3597                         encode_value (hole->length, p, &p);
3598                         encode_value (hole->offset, p, &p);
3599                 }
3600         }
3601
3602         if (seq_points) {
3603                 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3604
3605                 encode_value (seq_points->len, p, &p);
3606                 last_il_offset = last_native_offset = 0;
3607                 for (i = 0; i < seq_points->len; ++i) {
3608                         SeqPoint *sp = &seq_points->seq_points [i];
3609                         il_offset = sp->il_offset;
3610                         native_offset = sp->native_offset;
3611                         encode_value (il_offset - last_il_offset, p, &p);
3612                         encode_value (native_offset - last_native_offset, p, &p);
3613                         last_il_offset = il_offset;
3614                         last_native_offset = native_offset;
3615
3616                         encode_value (sp->next_len, p, &p);
3617                         for (j = 0; j < sp->next_len; ++j)
3618                                 encode_value (sp->next [j], p, &p);
3619                 }
3620         }
3621                 
3622
3623         g_assert (debug_info_size < buf_size);
3624
3625         encode_value (debug_info_size, p, &p);
3626         if (debug_info_size) {
3627                 memcpy (p, debug_info, debug_info_size);
3628                 p += debug_info_size;
3629                 g_free (debug_info);
3630         }
3631
3632         acfg->stats.ex_info_size += p - buf;
3633
3634         g_assert (p - buf < buf_size);
3635
3636         /* Emit info */
3637         cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3638         g_free (buf);
3639 }
3640
3641 static guint32
3642 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3643 {
3644         MonoClass *klass = mono_class_get (acfg->image, token);
3645         guint8 *p, *buf;
3646         int i, buf_size, res;
3647         gboolean no_special_static, cant_encode;
3648         gpointer iter = NULL;
3649
3650         if (!klass) {
3651                 buf_size = 16;
3652
3653                 p = buf = g_malloc (buf_size);
3654
3655                 /* Mark as unusable */
3656                 encode_value (-1, p, &p);
3657
3658                 res = add_to_blob (acfg, buf, p - buf);
3659                 g_free (buf);
3660
3661                 return res;
3662         }
3663                 
3664         buf_size = 10240 + (klass->vtable_size * 16);
3665         p = buf = g_malloc (buf_size);
3666
3667         g_assert (klass);
3668
3669         mono_class_init (klass);
3670
3671         mono_class_get_nested_types (klass, &iter);
3672         g_assert (klass->nested_classes_inited);
3673
3674         mono_class_setup_vtable (klass);
3675
3676         /* 
3677          * Emit all the information which is required for creating vtables so
3678          * the runtime does not need to create the MonoMethod structures which
3679          * take up a lot of space.
3680          */
3681
3682         no_special_static = !mono_class_has_special_static_fields (klass);
3683
3684         /* Check whenever we have enough info to encode the vtable */
3685         cant_encode = FALSE;
3686         for (i = 0; i < klass->vtable_size; ++i) {
3687                 MonoMethod *cm = klass->vtable [i];
3688
3689                 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3690                         cant_encode = TRUE;
3691         }
3692
3693         if (klass->generic_container || cant_encode) {
3694                 encode_value (-1, p, &p);
3695         } else {
3696                 encode_value (klass->vtable_size, p, &p);
3697                 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);
3698                 if (klass->has_cctor)
3699                         encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3700                 if (klass->has_finalize)
3701                         encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3702  
3703                 encode_value (klass->instance_size, p, &p);
3704                 encode_value (mono_class_data_size (klass), p, &p);
3705                 encode_value (klass->packing_size, p, &p);
3706                 encode_value (klass->min_align, p, &p);
3707
3708                 for (i = 0; i < klass->vtable_size; ++i) {
3709                         MonoMethod *cm = klass->vtable [i];
3710
3711                         if (cm)
3712                                 encode_method_ref (acfg, cm, p, &p);
3713                         else
3714                                 encode_value (0, p, &p);
3715                 }
3716         }
3717
3718         acfg->stats.class_info_size += p - buf;
3719
3720         g_assert (p - buf < buf_size);
3721         res = add_to_blob (acfg, buf, p - buf);
3722         g_free (buf);
3723
3724         return res;
3725 }
3726
3727 /*
3728  * Calls made from AOTed code are routed through a table of jumps similar to the
3729  * ELF PLT (Program Linkage Table). The differences are the following:
3730  * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3731  *   GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3732  *   jumps. This means the jumps need to be patched when the address of the callee is
3733  *   known. Initially the PLT entries jump to code which transfers control to the
3734  *   AOT runtime through the first PLT entry.
3735  */
3736 static void
3737 emit_plt (MonoAotCompile *acfg)
3738 {
3739         char symbol [128];
3740         int i;
3741         GHashTable *cache;
3742
3743         cache = g_hash_table_new (g_str_hash, g_str_equal);
3744
3745         emit_line (acfg);
3746         sprintf (symbol, "plt");
3747
3748         emit_section_change (acfg, ".text", 0);
3749         emit_global (acfg, symbol, TRUE);
3750         emit_alignment (acfg, 16);
3751         emit_label (acfg, symbol);
3752         emit_label (acfg, acfg->plt_symbol);
3753
3754         for (i = 0; i < acfg->plt_offset; ++i) {
3755                 char label [128];
3756                 char *debug_sym = NULL;
3757                 MonoPltEntry *plt_entry = NULL;
3758                 MonoJumpInfo *ji;
3759
3760                 if (i == 0) {
3761                         /* 
3762                          * The first plt entry is used to transfer code to the AOT loader. 
3763                          */
3764                         arch_emit_plt_entry (acfg, i);
3765                         continue;
3766                 }
3767
3768                 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3769                 ji = plt_entry->ji;
3770                 sprintf (label, "%s", plt_entry->symbol);
3771
3772                 if (acfg->llvm) {
3773                         /*
3774                          * If the target is directly callable, alias the plt symbol to point to
3775                          * the method code.
3776                          * FIXME: Use this to simplify emit_and_reloc_code ().
3777                          * FIXME: Avoid the got slot.
3778                          * FIXME: Add support to the binary writer.
3779                          */
3780                         if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3781                                 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3782                                 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3783                                 continue;
3784                         }
3785                 }
3786
3787                 emit_label (acfg, label);
3788
3789                 if (acfg->aot_opts.write_symbols) {
3790                         switch (ji->type) {
3791                         case MONO_PATCH_INFO_METHOD:
3792                                 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3793                                 break;
3794                         case MONO_PATCH_INFO_INTERNAL_METHOD:
3795                                 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3796                                 break;
3797                         case MONO_PATCH_INFO_CLASS_INIT:
3798                                 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3799                                 sanitize_symbol (debug_sym);
3800                                 break;
3801                         case MONO_PATCH_INFO_RGCTX_FETCH:
3802                                 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3803                                 break;
3804                         case MONO_PATCH_INFO_ICALL_ADDR: {
3805                                 char *s = get_debug_sym (ji->data.method, "", cache);
3806                                         
3807                                 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3808                                 g_free (s);
3809                                 break;
3810                         }
3811                         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3812                                 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3813                                 break;
3814                         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3815                                 debug_sym = g_strdup_printf ("plt__generic_class_init");
3816                                 break;
3817                         default:
3818                                 break;
3819                         }
3820
3821                         if (debug_sym) {
3822                                 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3823                                 emit_label (acfg, debug_sym);
3824                         }
3825                 }
3826
3827                 arch_emit_plt_entry (acfg, i);
3828
3829                 if (debug_sym) {
3830                         emit_symbol_size (acfg, debug_sym, ".");
3831                         g_free (debug_sym);
3832                 }
3833         }
3834
3835         emit_symbol_size (acfg, acfg->plt_symbol, ".");
3836
3837         sprintf (symbol, "plt_end");
3838         emit_global (acfg, symbol, TRUE);
3839         emit_label (acfg, symbol);
3840
3841         g_hash_table_destroy (cache);
3842 }
3843
3844 static G_GNUC_UNUSED void
3845 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3846 {
3847         char start_symbol [256];
3848         char symbol [256];
3849         guint32 buf_size, info_offset;
3850         MonoJumpInfo *patch_info;
3851         guint8 *buf, *p;
3852         GPtrArray *patches;
3853         char *name;
3854         guint8 *code;
3855         guint32 code_size;
3856         MonoJumpInfo *ji;
3857         GSList *unwind_ops;
3858
3859         name = info->name;
3860         code = info->code;
3861         code_size = info->code_size;
3862         ji = info->ji;
3863         unwind_ops = info->unwind_ops;
3864
3865 #ifdef __native_client_codegen__
3866         mono_nacl_fix_patches (code, ji);
3867 #endif
3868
3869         /* Emit code */
3870
3871         sprintf (start_symbol, "%s", name);
3872
3873         emit_section_change (acfg, ".text", 0);
3874         emit_global (acfg, start_symbol, TRUE);
3875         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
3876         emit_label (acfg, start_symbol);
3877
3878         sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3879         emit_label (acfg, symbol);
3880
3881         /* 
3882          * The code should access everything through the GOT, so we pass
3883          * TRUE here.
3884          */
3885         emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3886
3887         emit_symbol_size (acfg, start_symbol, ".");
3888
3889         /* Emit info */
3890
3891         /* Sort relocations */
3892         patches = g_ptr_array_new ();
3893         for (patch_info = ji; patch_info; patch_info = patch_info->next)
3894                 if (patch_info->type != MONO_PATCH_INFO_NONE)
3895                         g_ptr_array_add (patches, patch_info);
3896         g_ptr_array_sort (patches, compare_patches);
3897
3898         buf_size = patches->len * 128 + 128;
3899         buf = g_malloc (buf_size);
3900         p = buf;
3901
3902         encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3903         g_assert (p - buf < buf_size);
3904
3905         sprintf (symbol, "%s_p", name);
3906
3907         info_offset = add_to_blob (acfg, buf, p - buf);
3908
3909         emit_section_change (acfg, RODATA_SECT, 0);
3910         emit_global (acfg, symbol, FALSE);
3911         emit_label (acfg, symbol);
3912
3913         emit_int32 (acfg, info_offset);
3914
3915         /* Emit debug info */
3916         if (unwind_ops) {
3917                 char symbol2 [256];
3918
3919                 sprintf (symbol, "%s", name);
3920                 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3921
3922                 if (acfg->dwarf)
3923                         mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3924         }
3925 }
3926
3927 static void
3928 emit_trampolines (MonoAotCompile *acfg)
3929 {
3930         char symbol [256];
3931         int i, tramp_got_offset;
3932         MonoAotTrampoline ntype;
3933 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3934         int tramp_type;
3935         guint8 *code;
3936 #endif
3937
3938         if (!acfg->aot_opts.full_aot)
3939                 return;
3940         
3941         g_assert (acfg->image->assembly);
3942
3943         /* Currently, we emit most trampolines into the mscorlib AOT image. */
3944         if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3945 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3946                 MonoTrampInfo *info;
3947
3948                 /*
3949                  * Emit the generic trampolines.
3950                  *
3951                  * We could save some code by treating the generic trampolines as a wrapper
3952                  * method, but that approach has its own complexities, so we choose the simpler
3953                  * method.
3954                  */
3955                 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3956                         mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
3957                         emit_trampoline (acfg, acfg->got_offset, info);
3958                 }
3959
3960                 mono_arch_get_nullified_class_init_trampoline (&info);
3961                 emit_trampoline (acfg, acfg->got_offset, info);
3962 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
3963                 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
3964                 emit_trampoline (acfg, acfg->got_offset, info);
3965                 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
3966                 emit_trampoline (acfg, acfg->got_offset, info);
3967 #endif
3968
3969                 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
3970                 emit_trampoline (acfg, acfg->got_offset, info);
3971
3972                 /* Emit the exception related code pieces */
3973                 code = mono_arch_get_restore_context (&info, TRUE);
3974                 emit_trampoline (acfg, acfg->got_offset, info);
3975                 code = mono_arch_get_call_filter (&info, TRUE);
3976                 emit_trampoline (acfg, acfg->got_offset, info);
3977                 code = mono_arch_get_throw_exception (&info, TRUE);
3978                 emit_trampoline (acfg, acfg->got_offset, info);
3979                 code = mono_arch_get_rethrow_exception (&info, TRUE);
3980                 emit_trampoline (acfg, acfg->got_offset, info);
3981                 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
3982                 emit_trampoline (acfg, acfg->got_offset, info);
3983
3984 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
3985                 {
3986                         GSList *l = mono_arch_get_trampolines (TRUE);
3987
3988                         while (l) {
3989                                 MonoTrampInfo *info = l->data;
3990
3991                                 emit_trampoline (acfg, acfg->got_offset, info);
3992                                 l = l->next;
3993                         }
3994                 }
3995 #endif
3996
3997                 for (i = 0; i < 128; ++i) {
3998                         int offset;
3999
4000                         offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4001                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4002                         emit_trampoline (acfg, acfg->got_offset, info);
4003
4004                         offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4005                         code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4006                         emit_trampoline (acfg, acfg->got_offset, info);
4007                 }
4008
4009                 {
4010                         GSList *l;
4011
4012                         /* delegate_invoke_impl trampolines */
4013                         l = mono_arch_get_delegate_invoke_impls ();
4014                         while (l) {
4015                                 MonoTrampInfo *info = l->data;
4016
4017                                 emit_trampoline (acfg, acfg->got_offset, info);
4018                                 l = l->next;
4019                         }
4020                 }
4021
4022 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4023
4024                 /* Emit trampolines which are numerous */
4025
4026                 /*
4027                  * These include the following:
4028                  * - specific trampolines
4029                  * - static rgctx invoke trampolines
4030                  * - imt thunks
4031                  * These trampolines have the same code, they are parameterized by GOT 
4032                  * slots. 
4033                  * They are defined in this file, in the arch_... routines instead of
4034                  * in tramp-<ARCH>.c, since it is easier to do it this way.
4035                  */
4036
4037                 /*
4038                  * When running in aot-only mode, we can't create specific trampolines at 
4039                  * runtime, so we create a few, and save them in the AOT file. 
4040                  * Normal trampolines embed their argument as a literal inside the 
4041                  * trampoline code, we can't do that here, so instead we embed an offset
4042                  * which needs to be added to the trampoline address to get the address of
4043                  * the GOT slot which contains the argument value.
4044                  * The generated trampolines jump to the generic trampolines using another
4045                  * GOT slot, which will be setup by the AOT loader to point to the 
4046                  * generic trampoline code of the given type.
4047                  */
4048
4049                 /*
4050                  * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4051                  * each class).
4052                  */
4053
4054                 emit_section_change (acfg, ".text", 0);
4055
4056                 tramp_got_offset = acfg->got_offset;
4057
4058                 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4059                         switch (ntype) {
4060                         case MONO_AOT_TRAMP_SPECIFIC:
4061                                 sprintf (symbol, "specific_trampolines");
4062                                 break;
4063                         case MONO_AOT_TRAMP_STATIC_RGCTX:
4064                                 sprintf (symbol, "static_rgctx_trampolines");
4065                                 break;
4066                         case MONO_AOT_TRAMP_IMT_THUNK:
4067                                 sprintf (symbol, "imt_thunks");
4068                                 break;
4069                         default:
4070                                 g_assert_not_reached ();
4071                         }
4072
4073                         emit_global (acfg, symbol, TRUE);
4074                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4075                         emit_label (acfg, symbol);
4076
4077                         acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4078
4079                         for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4080                                 int tramp_size = 0;
4081
4082                                 switch (ntype) {
4083                                 case MONO_AOT_TRAMP_SPECIFIC:
4084                                         arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4085                                         tramp_got_offset += 2;
4086                                 break;
4087                                 case MONO_AOT_TRAMP_STATIC_RGCTX:
4088                                         arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);                                
4089                                         tramp_got_offset += 2;
4090                                         break;
4091                                 case MONO_AOT_TRAMP_IMT_THUNK:
4092                                         arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4093                                         tramp_got_offset += 1;
4094                                         break;
4095                                 default:
4096                                         g_assert_not_reached ();
4097                                 }
4098 #ifdef __native_client_codegen__
4099                                 /* align to avoid 32-byte boundary crossings */
4100                                 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4101 #endif
4102
4103                                 if (!acfg->trampoline_size [ntype]) {
4104                                         g_assert (tramp_size);
4105                                         acfg->trampoline_size [ntype] = tramp_size;
4106                                 }
4107                         }
4108                 }
4109
4110                 /* Reserve some entries at the end of the GOT for our use */
4111                 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4112         }
4113
4114         acfg->got_offset += acfg->num_trampoline_got_entries;
4115 }
4116
4117 static gboolean
4118 str_begins_with (const char *str1, const char *str2)
4119 {
4120         int len = strlen (str2);
4121         return strncmp (str1, str2, len) == 0;
4122 }
4123
4124 static void
4125 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4126 {
4127         gchar **args, **ptr;
4128
4129         args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4130         for (ptr = args; ptr && *ptr; ptr ++) {
4131                 const char *arg = *ptr;
4132
4133                 if (str_begins_with (arg, "outfile=")) {
4134                         opts->outfile = g_strdup (arg + strlen ("outfile="));
4135                 } else if (str_begins_with (arg, "save-temps")) {
4136                         opts->save_temps = TRUE;
4137                 } else if (str_begins_with (arg, "keep-temps")) {
4138                         opts->save_temps = TRUE;
4139                 } else if (str_begins_with (arg, "write-symbols")) {
4140                         opts->write_symbols = TRUE;
4141                 } else if (str_begins_with (arg, "metadata-only")) {
4142                         opts->metadata_only = TRUE;
4143                 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4144                         opts->bind_to_runtime_version = TRUE;
4145                 } else if (str_begins_with (arg, "full")) {
4146                         opts->full_aot = TRUE;
4147                 } else if (str_begins_with (arg, "threads=")) {
4148                         opts->nthreads = atoi (arg + strlen ("threads="));
4149                 } else if (str_begins_with (arg, "static")) {
4150                         opts->static_link = TRUE;
4151                         opts->no_dlsym = TRUE;
4152                 } else if (str_begins_with (arg, "asmonly")) {
4153                         opts->asm_only = TRUE;
4154                 } else if (str_begins_with (arg, "asmwriter")) {
4155                         opts->asm_writer = TRUE;
4156                 } else if (str_begins_with (arg, "nodebug")) {
4157                         opts->nodebug = TRUE;
4158                 } else if (str_begins_with (arg, "ntrampolines=")) {
4159                         opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4160                 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4161                         opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4162                 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4163                         opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4164                 } else if (str_begins_with (arg, "autoreg")) {
4165                         opts->autoreg = TRUE;
4166                 } else if (str_begins_with (arg, "tool-prefix=")) {
4167                         opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4168                 } else if (str_begins_with (arg, "soft-debug")) {
4169                         opts->soft_debug = TRUE;
4170                 } else if (str_begins_with (arg, "print-skipped")) {
4171                         opts->print_skipped_methods = TRUE;
4172                 } else if (str_begins_with (arg, "stats")) {
4173                         opts->stats = TRUE;
4174                 } else {
4175                         fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4176                         exit (1);
4177                 }
4178         }
4179
4180         g_strfreev (args);
4181 }
4182
4183 static void
4184 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4185 {
4186         MonoMethod *method = (MonoMethod*)key;
4187         MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4188         MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4189         MonoAotCompile *acfg = user_data;
4190
4191         new_ji->image = ji->image;
4192         new_ji->token = ji->token;
4193         g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4194 }
4195
4196 static gboolean
4197 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4198 {
4199         if (klass->type_token)
4200                 return TRUE;
4201         if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4202                 return TRUE;
4203         if (klass->rank)
4204                 return can_encode_class (acfg, klass->element_class);
4205         return FALSE;
4206 }
4207
4208 static gboolean
4209 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4210 {
4211         switch (patch_info->type) {
4212         case MONO_PATCH_INFO_METHOD:
4213         case MONO_PATCH_INFO_METHODCONST: {
4214                 MonoMethod *method = patch_info->data.method;
4215
4216                 if (method->wrapper_type) {
4217                         switch (method->wrapper_type) {
4218                         case MONO_WRAPPER_NONE:
4219                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4220                         case MONO_WRAPPER_XDOMAIN_INVOKE:
4221                         case MONO_WRAPPER_STFLD:
4222                         case MONO_WRAPPER_LDFLD:
4223                         case MONO_WRAPPER_LDFLDA:
4224                         case MONO_WRAPPER_LDFLD_REMOTE:
4225                         case MONO_WRAPPER_STFLD_REMOTE:
4226                         case MONO_WRAPPER_STELEMREF:
4227                         case MONO_WRAPPER_ISINST:
4228                         case MONO_WRAPPER_PROXY_ISINST:
4229                         case MONO_WRAPPER_ALLOC:
4230                         case MONO_WRAPPER_REMOTING_INVOKE:
4231                         case MONO_WRAPPER_UNKNOWN:
4232                         case MONO_WRAPPER_WRITE_BARRIER:
4233                                 break;
4234                         case MONO_WRAPPER_MANAGED_TO_MANAGED:
4235                                 if (!strcmp (method->name, "ElementAddr"))
4236                                         return TRUE;
4237                                 else
4238                                         return FALSE;
4239                         default:
4240                                 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4241                                 return FALSE;
4242                         }
4243                 } else {
4244                         if (!method->token) {
4245                                 /* The method is part of a constructed type like Int[,].Set (). */
4246                                 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4247                                         if (method->klass->rank)
4248                                                 return TRUE;
4249                                         return FALSE;
4250                                 }
4251                         }
4252                 }
4253                 break;
4254         }
4255         case MONO_PATCH_INFO_VTABLE:
4256         case MONO_PATCH_INFO_CLASS_INIT:
4257         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4258         case MONO_PATCH_INFO_CLASS:
4259         case MONO_PATCH_INFO_IID:
4260         case MONO_PATCH_INFO_ADJUSTED_IID:
4261                 if (!can_encode_class (acfg, patch_info->data.klass)) {
4262                         //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4263                         return FALSE;
4264                 }
4265                 break;
4266         case MONO_PATCH_INFO_RGCTX_FETCH: {
4267                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4268
4269                 if (!can_encode_patch (acfg, entry->data))
4270                         return FALSE;
4271                 break;
4272         }
4273         default:
4274                 break;
4275         }
4276
4277         return TRUE;
4278 }
4279
4280 static void
4281 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4282
4283 /*
4284  * compile_method:
4285  *
4286  *   AOT compile a given method.
4287  * This function might be called by multiple threads, so it must be thread-safe.
4288  */
4289 static void
4290 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4291 {
4292         MonoCompile *cfg;
4293         MonoJumpInfo *patch_info;
4294         gboolean skip;
4295         int index, depth;
4296         MonoMethod *wrapped;
4297
4298         if (acfg->aot_opts.metadata_only)
4299                 return;
4300
4301         mono_acfg_lock (acfg);
4302         index = get_method_index (acfg, method);
4303         mono_acfg_unlock (acfg);
4304
4305         /* fixme: maybe we can also precompile wrapper methods */
4306         if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4307                 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4308                 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4309                 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4310                 return;
4311         }
4312
4313         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4314                 return;
4315
4316         wrapped = mono_marshal_method_from_wrapper (method);
4317         if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4318                 // FIXME: The wrapper should be generic too, but it is not
4319                 return;
4320
4321         InterlockedIncrement (&acfg->stats.mcount);
4322
4323 #if 0
4324         if (method->is_generic || method->klass->generic_container) {
4325                 InterlockedIncrement (&acfg->stats.genericcount);
4326                 return;
4327         }
4328 #endif
4329
4330         //acfg->aot_opts.print_skipped_methods = TRUE;
4331
4332         /*
4333          * Since these methods are the only ones which are compiled with
4334          * AOT support, and they are not used by runtime startup/shutdown code,
4335          * the runtime will not see AOT methods during AOT compilation,so it
4336          * does not need to support them by creating a fake GOT etc.
4337          */
4338         cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4339         if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4340                 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4341                 InterlockedIncrement (&acfg->stats.genericcount);
4342                 return;
4343         }
4344         if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4345                 /* Let the exception happen at runtime */
4346                 return;
4347         }
4348
4349         if (cfg->disable_aot) {
4350                 if (acfg->aot_opts.print_skipped_methods)
4351                         printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4352                 InterlockedIncrement (&acfg->stats.ocount);
4353                 mono_destroy_compile (cfg);
4354                 return;
4355         }
4356
4357         /* Nullify patches which need no aot processing */
4358         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4359                 switch (patch_info->type) {
4360                 case MONO_PATCH_INFO_LABEL:
4361                 case MONO_PATCH_INFO_BB:
4362                         patch_info->type = MONO_PATCH_INFO_NONE;
4363                         break;
4364                 default:
4365                         break;
4366                 }
4367         }
4368
4369         /* Collect method->token associations from the cfg */
4370         mono_acfg_lock (acfg);
4371         g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4372         mono_acfg_unlock (acfg);
4373
4374         /*
4375          * Check for absolute addresses.
4376          */
4377         skip = FALSE;
4378         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4379                 switch (patch_info->type) {
4380                 case MONO_PATCH_INFO_ABS:
4381                         /* unable to handle this */
4382                         skip = TRUE;    
4383                         break;
4384                 default:
4385                         break;
4386                 }
4387         }
4388
4389         if (skip) {
4390                 if (acfg->aot_opts.print_skipped_methods)
4391                         printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4392                 InterlockedIncrement (&acfg->stats.abscount);
4393                 mono_destroy_compile (cfg);
4394                 return;
4395         }
4396
4397         /* Lock for the rest of the code */
4398         mono_acfg_lock (acfg);
4399
4400         /*
4401          * Check for methods/klasses we can't encode.
4402          */
4403         skip = FALSE;
4404         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4405                 if (!can_encode_patch (acfg, patch_info))
4406                         skip = TRUE;
4407         }
4408
4409         if (skip) {
4410                 if (acfg->aot_opts.print_skipped_methods)
4411                         printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4412                 acfg->stats.ocount++;
4413                 mono_destroy_compile (cfg);
4414                 mono_acfg_unlock (acfg);
4415                 return;
4416         }
4417
4418         /* Adds generic instances referenced by this method */
4419         /* 
4420          * The depth is used to avoid infinite loops when generic virtual recursion is 
4421          * encountered.
4422          */
4423         depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4424         if (depth < 32) {
4425                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4426                         switch (patch_info->type) {
4427                         case MONO_PATCH_INFO_METHOD: {
4428                                 MonoMethod *m = patch_info->data.method;
4429                                 if (m->is_inflated) {
4430                                         if (!(mono_class_generic_sharing_enabled (m->klass) &&
4431                                                   mono_method_is_generic_sharable_impl (m, FALSE)) &&
4432                                                 !method_has_type_vars (m)) {
4433                                                 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4434                                                         if (acfg->aot_opts.full_aot)
4435                                                                 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4436                                                 } else {
4437                                                         add_extra_method_with_depth (acfg, m, depth + 1);
4438                                                 }
4439                                         }
4440                                         add_generic_class_with_depth (acfg, m->klass, depth + 5);
4441                                 }
4442                                 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4443                                         add_extra_method_with_depth (acfg, m, depth + 1);
4444                                 break;
4445                         }
4446                         case MONO_PATCH_INFO_VTABLE: {
4447                                 MonoClass *klass = patch_info->data.klass;
4448
4449                                 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4450                                         add_generic_class_with_depth (acfg, klass, depth + 5);
4451                                 break;
4452                         }
4453                         default:
4454                                 break;
4455                         }
4456                 }
4457         }
4458
4459         /* Determine whenever the method has GOT slots */
4460         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4461                 switch (patch_info->type) {
4462                 case MONO_PATCH_INFO_GOT_OFFSET:
4463                 case MONO_PATCH_INFO_NONE:
4464                         break;
4465                 case MONO_PATCH_INFO_IMAGE:
4466                         /* The assembly is stored in GOT slot 0 */
4467                         if (patch_info->data.image != acfg->image)
4468                                 cfg->has_got_slots = TRUE;
4469                         break;
4470                 default:
4471                         if (!is_plt_patch (patch_info))
4472                                 cfg->has_got_slots = TRUE;
4473                         break;
4474                 }
4475         }
4476
4477         if (!cfg->has_got_slots)
4478                 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4479
4480         /* 
4481          * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4482          */
4483         /* Make a copy of the patch info which is in the mempool */
4484         {
4485                 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4486
4487                 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4488                         MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4489
4490                         if (!patches)
4491                                 patches = new_patch_info;
4492                         else
4493                                 patches_end->next = new_patch_info;
4494                         patches_end = new_patch_info;
4495                 }
4496                 cfg->patch_info = patches;
4497         }
4498         /* Make a copy of the unwind info */
4499         {
4500                 GSList *l, *unwind_ops;
4501                 MonoUnwindOp *op;
4502
4503                 unwind_ops = NULL;
4504                 for (l = cfg->unwind_ops; l; l = l->next) {
4505                         op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4506                         memcpy (op, l->data, sizeof (MonoUnwindOp));
4507                         unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4508                 }
4509                 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4510         }
4511         /* Make a copy of the argument/local info */
4512         {
4513                 MonoInst **args, **locals;
4514                 MonoMethodSignature *sig;
4515                 MonoMethodHeader *header;
4516                 int i;
4517                 
4518                 sig = mono_method_signature (method);
4519                 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4520                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4521                         args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4522                         memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4523                 }
4524                 cfg->args = args;
4525
4526                 header = mono_method_get_header (method);
4527                 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4528                 for (i = 0; i < header->num_locals; ++i) {
4529                         locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4530                         memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4531                 }
4532                 cfg->locals = locals;
4533         }
4534
4535         /* Free some fields used by cfg to conserve memory */
4536         mono_mempool_destroy (cfg->mempool);
4537         cfg->mempool = NULL;
4538         g_free (cfg->varinfo);
4539         cfg->varinfo = NULL;
4540         g_free (cfg->vars);
4541         cfg->vars = NULL;
4542         if (cfg->rs) {
4543                 mono_regstate_free (cfg->rs);
4544                 cfg->rs = NULL;
4545         }
4546
4547         //printf ("Compile:           %s\n", mono_method_full_name (method, TRUE));
4548
4549         while (index >= acfg->cfgs_size) {
4550                 MonoCompile **new_cfgs;
4551                 int new_size;
4552
4553                 new_size = acfg->cfgs_size * 2;
4554                 new_cfgs = g_new0 (MonoCompile*, new_size);
4555                 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4556                 g_free (acfg->cfgs);
4557                 acfg->cfgs = new_cfgs;
4558                 acfg->cfgs_size = new_size;
4559         }
4560         acfg->cfgs [index] = cfg;
4561
4562         g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4563
4564         /*
4565         if (cfg->orig_method->wrapper_type)
4566                 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4567         */
4568
4569         mono_acfg_unlock (acfg);
4570
4571         InterlockedIncrement (&acfg->stats.ccount);
4572 }
4573  
4574 static void
4575 compile_thread_main (gpointer *user_data)
4576 {
4577         MonoDomain *domain = user_data [0];
4578         MonoAotCompile *acfg = user_data [1];
4579         GPtrArray *methods = user_data [2];
4580         int i;
4581
4582         mono_thread_attach (domain);
4583
4584         for (i = 0; i < methods->len; ++i)
4585                 compile_method (acfg, g_ptr_array_index (methods, i));
4586 }
4587
4588 static void
4589 load_profile_files (MonoAotCompile *acfg)
4590 {
4591         FILE *infile;
4592         char *tmp;
4593         int file_index, res, method_index, i;
4594         char ver [256];
4595         guint32 token;
4596         GList *unordered;
4597
4598         file_index = 0;
4599         while (TRUE) {
4600                 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4601
4602                 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4603                         g_free (tmp);
4604                         break;
4605                 }
4606
4607                 infile = fopen (tmp, "r");
4608                 g_assert (infile);
4609
4610                 printf ("Using profile data file '%s'\n", tmp);
4611                 g_free (tmp);
4612
4613                 file_index ++;
4614
4615                 res = fscanf (infile, "%32s\n", ver);
4616                 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4617                         printf ("Profile file has wrong version or invalid.\n");
4618                         fclose (infile);
4619                         continue;
4620                 }
4621
4622                 while (TRUE) {
4623                         char name [1024];
4624                         MonoMethodDesc *desc;
4625                         MonoMethod *method;
4626
4627                         if (fgets (name, 1023, infile) == NULL)
4628                                 break;
4629
4630                         /* Kill the newline */
4631                         if (strlen (name) > 0)
4632                                 name [strlen (name) - 1] = '\0';
4633
4634                         desc = mono_method_desc_new (name, TRUE);
4635
4636                         method = mono_method_desc_search_in_image (desc, acfg->image);
4637
4638                         if (method && mono_method_get_token (method)) {
4639                                 token = mono_method_get_token (method);
4640                                 method_index = mono_metadata_token_index (token) - 1;
4641
4642                                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4643                                         acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4644                                 }
4645                         } else {
4646                                 //printf ("No method found matching '%s'.\n", name);
4647                         }
4648                 }
4649                 fclose (infile);
4650         }
4651
4652         /* Add missing methods */
4653         unordered = NULL;
4654         for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4655                 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4656                         unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4657         }
4658         unordered = g_list_reverse (unordered);
4659         if (acfg->method_order)
4660                 g_list_last (acfg->method_order)->next = unordered;
4661         else
4662                 acfg->method_order = unordered;
4663 }
4664  
4665 /* Used by the LLVM backend */
4666 guint32
4667 mono_aot_get_got_offset (MonoJumpInfo *ji)
4668 {
4669         return get_got_offset (llvm_acfg, ji);
4670 }
4671
4672 char*
4673 mono_aot_get_method_name (MonoCompile *cfg)
4674 {
4675         guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4676
4677         return g_strdup_printf ("m_%x", method_index);
4678 }
4679
4680 char*
4681 mono_aot_get_method_debug_name (MonoCompile *cfg)
4682 {
4683         return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4684 }
4685
4686 char*
4687 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4688 {
4689         MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4690         MonoPltEntry *plt_entry;
4691
4692         ji->type = type;
4693         ji->data.target = data;
4694
4695         if (!can_encode_patch (llvm_acfg, ji))
4696                 return NULL;
4697
4698         plt_entry = get_plt_entry (llvm_acfg, ji);
4699
4700         return g_strdup_printf (plt_entry->symbol);
4701 }
4702
4703 MonoJumpInfo*
4704 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4705 {
4706         MonoJumpInfo *res;
4707
4708         mono_acfg_lock (llvm_acfg);
4709         res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4710         mono_acfg_unlock (llvm_acfg);
4711
4712         return res;
4713 }
4714
4715 #ifdef ENABLE_LLVM
4716
4717 /*
4718  * emit_llvm_file:
4719  *
4720  *   Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4721  * tools.
4722  */
4723 static void
4724 emit_llvm_file (MonoAotCompile *acfg)
4725 {
4726         char *command, *opts;
4727         int i;
4728         MonoJumpInfo *patch_info;
4729         const char *llc_extra_args;
4730
4731         /*
4732          * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4733          * to it.
4734          */
4735
4736         /* Compute the final size of the got */
4737         for (i = 0; i < acfg->nmethods; ++i) {
4738                 if (acfg->cfgs [i]) {
4739                         for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4740                                 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4741                                         if (!is_plt_patch (patch_info))
4742                                                 get_got_offset (acfg, patch_info);
4743                                         else
4744                                                 get_plt_entry (acfg, patch_info);
4745                                 }
4746                         }
4747                 }
4748         }
4749
4750         acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4751
4752         if (acfg->aot_opts.full_aot) {
4753                 int ntype;
4754
4755                 /* 
4756                  * Need to add the got entries used by the trampolines.
4757                  * This is only a conservative approximation.
4758                  */
4759                 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4760                         /* For the generic + rgctx trampolines */
4761                         acfg->final_got_size += 200;
4762                         /* For the specific trampolines */
4763                         for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4764                                 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4765                 }
4766         }
4767
4768
4769         mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4770
4771         /*
4772          * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4773          * a lot of time, and doesn't seem to save much space.
4774          * The following optimizations cannot be enabled:
4775          * - 'tailcallelim'
4776          * - 'jump-threading' changes our blockaddress references to int constants.
4777          * The opt list below was produced by taking the output of:
4778          * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4779          * then removing tailcallelim + the global opts, and adding a second gvn.
4780          */
4781         opts = g_strdup ("-instcombine -simplifycfg");
4782         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");
4783 #if 1
4784         command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4785         printf ("Executing opt: %s\n", command);
4786         if (system (command) != 0) {
4787                 exit (1);
4788         }
4789 #endif
4790         g_free (opts);
4791
4792 #if !LLVM_CHECK_VERSION(2, 8)
4793         /* LLVM 2.8 removed the -f flag ??? */
4794         llc_extra_args = "-f";
4795 #else
4796         llc_extra_args = "";
4797 #endif
4798         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);
4799
4800         printf ("Executing llc: %s\n", command);
4801
4802         if (system (command) != 0) {
4803                 exit (1);
4804         }
4805 }
4806 #endif
4807
4808 static void
4809 emit_code (MonoAotCompile *acfg)
4810 {
4811         int i;
4812         char symbol [256];
4813         char end_symbol [256];
4814         GList *l;
4815
4816 #if defined(TARGET_POWERPC64)
4817         sprintf (symbol, ".Lgot_addr");
4818         emit_section_change (acfg, ".text", 0);
4819         emit_alignment (acfg, 8);
4820         emit_label (acfg, symbol);
4821         emit_pointer (acfg, acfg->got_symbol);
4822 #endif
4823
4824         /* 
4825          * This global symbol is used to compute the address of each method using the
4826          * code_offsets array. It is also used to compute the memory ranges occupied by
4827          * AOT code, so it must be equal to the address of the first emitted method.
4828          */
4829         sprintf (symbol, "methods");
4830         emit_section_change (acfg, ".text", 0);
4831         emit_global (acfg, symbol, TRUE);
4832         emit_alignment (acfg, 8);
4833         if (acfg->llvm) {
4834                 for (i = 0; i < acfg->nmethods; ++i) {
4835                         if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4836                                 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4837                                 break;
4838                         }
4839                 }
4840                 if (i == acfg->nmethods)
4841                         /* No LLVM compiled methods */
4842                         emit_label (acfg, symbol);
4843         } else {
4844                 emit_label (acfg, symbol);
4845         }
4846
4847         /* 
4848          * Emit some padding so the local symbol for the first method doesn't have the
4849          * same address as 'methods'.
4850          */
4851         emit_zero_bytes (acfg, 16);
4852
4853         for (l = acfg->method_order; l != NULL; l = l->next) {
4854                 MonoCompile *cfg;
4855                 MonoMethod *method;
4856
4857                 i = GPOINTER_TO_UINT (l->data);
4858
4859                 cfg = acfg->cfgs [i];
4860
4861                 if (!cfg)
4862                         continue;
4863
4864                 method = cfg->orig_method;
4865
4866                 /* Emit unbox trampoline */
4867                 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4868                         char call_target [256];
4869
4870                         if (!method->wrapper_type && !method->is_inflated) {
4871                                 g_assert (method->token);
4872                                 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4873                         } else {
4874                                 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4875                         }
4876
4877                         emit_section_change (acfg, ".text", 0);
4878 #ifdef __native_client_codegen__
4879                         emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4880 #endif
4881                         emit_global (acfg, symbol, TRUE);
4882                         emit_label (acfg, symbol);
4883
4884                         sprintf (call_target, "%s", cfg->asm_symbol);
4885
4886                         arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4887                 }
4888
4889                 if (cfg->compile_llvm)
4890                         acfg->stats.llvm_count ++;
4891                 else
4892                         emit_method_code (acfg, cfg);
4893         }
4894
4895         sprintf (symbol, "methods_end");
4896         emit_section_change (acfg, ".text", 0);
4897         emit_global (acfg, symbol, FALSE);
4898         emit_alignment (acfg, 8);
4899         emit_label (acfg, symbol);
4900
4901         sprintf (symbol, "code_offsets");
4902         emit_section_change (acfg, RODATA_SECT, 1);
4903         emit_global (acfg, symbol, FALSE);
4904         emit_alignment (acfg, 8);
4905         emit_label (acfg, symbol);
4906
4907         acfg->stats.offsets_size += acfg->nmethods * 4;
4908
4909         sprintf (end_symbol, "methods");
4910         for (i = 0; i < acfg->nmethods; ++i) {
4911                 if (acfg->cfgs [i]) {
4912                         emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4913                 } else {
4914                         emit_int32 (acfg, 0xffffffff);
4915                 }
4916         }
4917         emit_line (acfg);
4918 }
4919
4920 static void
4921 emit_info (MonoAotCompile *acfg)
4922 {
4923         int i;
4924         char symbol [256];
4925         GList *l;
4926         gint32 *offsets;
4927
4928         offsets = g_new0 (gint32, acfg->nmethods);
4929
4930         for (l = acfg->method_order; l != NULL; l = l->next) {
4931                 i = GPOINTER_TO_UINT (l->data);
4932
4933                 if (acfg->cfgs [i]) {
4934                         emit_method_info (acfg, acfg->cfgs [i]);
4935                         offsets [i] = acfg->cfgs [i]->method_info_offset;
4936                 } else {
4937                         offsets [i] = 0;
4938                 }
4939         }
4940
4941         sprintf (symbol, "method_info_offsets");
4942         emit_section_change (acfg, RODATA_SECT, 1);
4943         emit_global (acfg, symbol, FALSE);
4944         emit_alignment (acfg, 8);
4945         emit_label (acfg, symbol);
4946
4947         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4948
4949         g_free (offsets);
4950 }
4951
4952 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4953
4954 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4955 #define mix(a,b,c) { \
4956         a -= c;  a ^= rot(c, 4);  c += b; \
4957         b -= a;  b ^= rot(a, 6);  a += c; \
4958         c -= b;  c ^= rot(b, 8);  b += a; \
4959         a -= c;  a ^= rot(c,16);  c += b; \
4960         b -= a;  b ^= rot(a,19);  a += c; \
4961         c -= b;  c ^= rot(b, 4);  b += a; \
4962 }
4963 #define final(a,b,c) { \
4964         c ^= b; c -= rot(b,14); \
4965         a ^= c; a -= rot(c,11); \
4966         b ^= a; b -= rot(a,25); \
4967         c ^= b; c -= rot(b,16); \
4968         a ^= c; a -= rot(c,4);  \
4969         b ^= a; b -= rot(a,14); \
4970         c ^= b; c -= rot(b,24); \
4971 }
4972
4973 static guint
4974 mono_aot_type_hash (MonoType *t1)
4975 {
4976         guint hash = t1->type;
4977
4978         hash |= t1->byref << 6; /* do not collide with t1->type values */
4979         switch (t1->type) {
4980         case MONO_TYPE_VALUETYPE:
4981         case MONO_TYPE_CLASS:
4982         case MONO_TYPE_SZARRAY:
4983                 /* check if the distribution is good enough */
4984                 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4985         case MONO_TYPE_PTR:
4986                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4987         case MONO_TYPE_ARRAY:
4988                 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4989         case MONO_TYPE_GENERICINST:
4990                 return ((hash << 5) - hash) ^ 0;
4991         }
4992         return hash;
4993 }
4994
4995 /*
4996  * mono_aot_method_hash:
4997  *
4998  *   Return a hash code for methods which only depends on metadata.
4999  */
5000 guint32
5001 mono_aot_method_hash (MonoMethod *method)
5002 {
5003         MonoMethodSignature *sig;
5004         MonoClass *klass;
5005         int i;
5006         int hashes_count;
5007         guint32 *hashes_start, *hashes;
5008         guint32 a, b, c;
5009
5010         /* Similar to the hash in mono_method_get_imt_slot () */
5011
5012         sig = mono_method_signature (method);
5013
5014         hashes_count = sig->param_count + 5;
5015         hashes_start = malloc (hashes_count * sizeof (guint32));
5016         hashes = hashes_start;
5017
5018         /* Some wrappers are assigned to random classes */
5019         if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5020                 klass = method->klass;
5021         else
5022                 klass = mono_defaults.object_class;
5023
5024         if (!method->wrapper_type) {
5025                 char *full_name = mono_type_full_name (&klass->byval_arg);
5026
5027                 hashes [0] = mono_metadata_str_hash (full_name);
5028                 hashes [1] = 0;
5029                 g_free (full_name);
5030         } else {
5031                 hashes [0] = mono_metadata_str_hash (klass->name);
5032                 hashes [1] = mono_metadata_str_hash (klass->name_space);
5033         }
5034         if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5035                 /* The method name includes a stringified pointer */
5036                 hashes [2] = 0;
5037         else
5038                 hashes [2] = mono_metadata_str_hash (method->name);
5039         hashes [3] = method->wrapper_type;
5040         hashes [4] = mono_aot_type_hash (sig->ret);
5041         for (i = 0; i < sig->param_count; i++) {
5042                 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
5043         }
5044         
5045         /* Setup internal state */
5046         a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5047
5048         /* Handle most of the hashes */
5049         while (hashes_count > 3) {
5050                 a += hashes [0];
5051                 b += hashes [1];
5052                 c += hashes [2];
5053                 mix (a,b,c);
5054                 hashes_count -= 3;
5055                 hashes += 3;
5056         }
5057
5058         /* Handle the last 3 hashes (all the case statements fall through) */
5059         switch (hashes_count) { 
5060         case 3 : c += hashes [2];
5061         case 2 : b += hashes [1];
5062         case 1 : a += hashes [0];
5063                 final (a,b,c);
5064         case 0: /* nothing left to add */
5065                 break;
5066         }
5067         
5068         free (hashes_start);
5069         
5070         return c;
5071 }
5072 #undef rot
5073 #undef mix
5074 #undef final
5075
5076 /*
5077  * mono_aot_wrapper_name:
5078  *
5079  *   Return a string which uniqely identifies the given wrapper method.
5080  */
5081 char*
5082 mono_aot_wrapper_name (MonoMethod *method)
5083 {
5084         char *name, *tmpsig, *klass_desc;
5085
5086         tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5087
5088         switch (method->wrapper_type) {
5089         case MONO_WRAPPER_RUNTIME_INVOKE:
5090                 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5091                         name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5092                 else
5093                         name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5094                 break;
5095         default:
5096                 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5097                 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5098                 g_free (klass_desc);
5099                 break;
5100         }
5101
5102         g_free (tmpsig);
5103
5104         return name;
5105 }
5106
5107 /*
5108  * mono_aot_get_array_helper_from_wrapper;
5109  *
5110  * Get the helper method in Array called by an array wrapper method.
5111  */
5112 MonoMethod*
5113 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5114 {
5115         MonoMethod *m;
5116         const char *prefix;
5117         MonoGenericContext ctx;
5118         MonoType *args [16];
5119         char *mname, *iname, *s, *s2, *helper_name = NULL;
5120
5121         prefix = "System.Collections.Generic";
5122         s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5123         s2 = strstr (s, "`1.");
5124         g_assert (s2);
5125         s2 [0] = '\0';
5126         iname = s;
5127         mname = s2 + 3;
5128
5129         //printf ("X: %s %s\n", iname, mname);
5130
5131         if (!strcmp (iname, "IList"))
5132                 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5133         else
5134                 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5135         m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5136         g_assert (m);
5137         g_free (helper_name);
5138         g_free (s);
5139
5140         if (m->is_generic) {
5141                 memset (&ctx, 0, sizeof (ctx));
5142                 args [0] = &method->klass->element_class->byval_arg;
5143                 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5144                 m = mono_class_inflate_generic_method (m, &ctx);
5145         }
5146
5147         return m;
5148 }
5149
5150 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5151
5152 typedef struct HashEntry {
5153     guint32 key, value, index;
5154         struct HashEntry *next;
5155 } HashEntry;
5156
5157 /*
5158  * emit_extra_methods:
5159  *
5160  * Emit methods which are not in the METHOD table, like wrappers.
5161  */
5162 static void
5163 emit_extra_methods (MonoAotCompile *acfg)
5164 {
5165         int i, table_size, buf_size;
5166         char symbol [256];
5167         guint8 *p, *buf;
5168         guint32 *info_offsets;
5169         guint32 hash;
5170         GPtrArray *table;
5171         HashEntry *entry, *new_entry;
5172         int nmethods, max_chain_length;
5173         int *chain_lengths;
5174
5175         info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5176
5177         /* Emit method info */
5178         nmethods = 0;
5179         for (i = 0; i < acfg->extra_methods->len; ++i) {
5180                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5181                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5182                 char *name;
5183
5184                 if (!cfg)
5185                         continue;
5186
5187                 buf_size = 10240;
5188                 p = buf = g_malloc (buf_size);
5189
5190                 nmethods ++;
5191
5192                 method = cfg->method_to_register;
5193
5194                 name = NULL;
5195                 if (method->wrapper_type) {
5196                         /* 
5197                          * We encode some wrappers using their name, since encoding them
5198                          * directly would be difficult. This also avoids creating the wrapper
5199                          * methods at runtime, since they are not needed anyway.
5200                          */
5201                         switch (method->wrapper_type) {
5202                         case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5203                         case MONO_WRAPPER_SYNCHRONIZED:
5204                                 /* encode_method_ref () can handle these */
5205                                 break;
5206                         case MONO_WRAPPER_RUNTIME_INVOKE:
5207                                 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5208                                         /* Direct wrapper, encode normally */
5209                                         break;
5210                                 /* Fall through */
5211                         default:
5212                                 name = mono_aot_wrapper_name (method);
5213                                 break;
5214                         }
5215                 }
5216
5217                 if (name) {
5218                         encode_value (1, p, &p);
5219                         encode_value (method->wrapper_type, p, &p);
5220                         strcpy ((char*)p, name);
5221                         p += strlen (name ) + 1;
5222                         g_free (name);
5223                 } else {
5224                         encode_value (0, p, &p);
5225                         encode_method_ref (acfg, method, p, &p);
5226                 }
5227
5228                 g_assert ((p - buf) < buf_size);
5229
5230                 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5231                 g_free (buf);
5232         }
5233
5234         /*
5235          * Construct a chained hash table for mapping indexes in extra_method_info to
5236          * method indexes.
5237          */
5238         table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5239         table = g_ptr_array_sized_new (table_size);
5240         for (i = 0; i < table_size; ++i)
5241                 g_ptr_array_add (table, NULL);
5242         chain_lengths = g_new0 (int, table_size);
5243         max_chain_length = 0;
5244         for (i = 0; i < acfg->extra_methods->len; ++i) {
5245                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5246                 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5247                 guint32 key, value;
5248
5249                 if (!cfg)
5250                         continue;
5251
5252                 key = info_offsets [i];
5253                 value = get_method_index (acfg, method);
5254
5255                 hash = mono_aot_method_hash (method) % table_size;
5256
5257                 chain_lengths [hash] ++;
5258                 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5259
5260                 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5261                 new_entry->key = key;
5262                 new_entry->value = value;
5263
5264                 entry = g_ptr_array_index (table, hash);
5265                 if (entry == NULL) {
5266                         new_entry->index = hash;
5267                         g_ptr_array_index (table, hash) = new_entry;
5268                 } else {
5269                         while (entry->next)
5270                                 entry = entry->next;
5271                         
5272                         entry->next = new_entry;
5273                         new_entry->index = table->len;
5274                         g_ptr_array_add (table, new_entry);
5275                 }
5276         }
5277
5278         //printf ("MAX: %d\n", max_chain_length);
5279
5280         /* Emit the table */
5281         sprintf (symbol, "extra_method_table");
5282         emit_section_change (acfg, RODATA_SECT, 0);
5283         emit_global (acfg, symbol, FALSE);
5284         emit_alignment (acfg, 8);
5285         emit_label (acfg, symbol);
5286
5287         emit_int32 (acfg, table_size);
5288         for (i = 0; i < table->len; ++i) {
5289                 HashEntry *entry = g_ptr_array_index (table, i);
5290
5291                 if (entry == NULL) {
5292                         emit_int32 (acfg, 0);
5293                         emit_int32 (acfg, 0);
5294                         emit_int32 (acfg, 0);
5295                 } else {
5296                         //g_assert (entry->key > 0);
5297                         emit_int32 (acfg, entry->key);
5298                         emit_int32 (acfg, entry->value);
5299                         if (entry->next)
5300                                 emit_int32 (acfg, entry->next->index);
5301                         else
5302                                 emit_int32 (acfg, 0);
5303                 }
5304         }
5305
5306         /* 
5307          * Emit a table reverse mapping method indexes to their index in extra_method_info.
5308          * This is used by mono_aot_find_jit_info ().
5309          */
5310         sprintf (symbol, "extra_method_info_offsets");
5311         emit_section_change (acfg, RODATA_SECT, 0);
5312         emit_global (acfg, symbol, FALSE);
5313         emit_alignment (acfg, 8);
5314         emit_label (acfg, symbol);
5315
5316         emit_int32 (acfg, acfg->extra_methods->len);
5317         for (i = 0; i < acfg->extra_methods->len; ++i) {
5318                 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5319
5320                 emit_int32 (acfg, get_method_index (acfg, method));
5321                 emit_int32 (acfg, info_offsets [i]);
5322         }
5323 }       
5324
5325 static void
5326 emit_exception_info (MonoAotCompile *acfg)
5327 {
5328         int i;
5329         char symbol [256];
5330         gint32 *offsets;
5331
5332         offsets = g_new0 (gint32, acfg->nmethods);
5333         for (i = 0; i < acfg->nmethods; ++i) {
5334                 if (acfg->cfgs [i]) {
5335                         emit_exception_debug_info (acfg, acfg->cfgs [i]);
5336                         offsets [i] = acfg->cfgs [i]->ex_info_offset;
5337                 } else {
5338                         offsets [i] = 0;
5339                 }
5340         }
5341
5342         sprintf (symbol, "ex_info_offsets");
5343         emit_section_change (acfg, RODATA_SECT, 1);
5344         emit_global (acfg, symbol, FALSE);
5345         emit_alignment (acfg, 8);
5346         emit_label (acfg, symbol);
5347
5348         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5349         g_free (offsets);
5350 }
5351
5352 static void
5353 emit_unwind_info (MonoAotCompile *acfg)
5354 {
5355         int i;
5356         char symbol [128];
5357
5358         /* 
5359          * The unwind info contains a lot of duplicates so we emit each unique
5360          * entry once, and only store the offset from the start of the table in the
5361          * exception info.
5362          */
5363
5364         sprintf (symbol, "unwind_info");
5365         emit_section_change (acfg, RODATA_SECT, 1);
5366         emit_alignment (acfg, 8);
5367         emit_label (acfg, symbol);
5368         emit_global (acfg, symbol, FALSE);
5369
5370         for (i = 0; i < acfg->unwind_ops->len; ++i) {
5371                 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5372                 guint8 *unwind_info;
5373                 guint32 unwind_info_len;
5374                 guint8 buf [16];
5375                 guint8 *p;
5376
5377                 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5378
5379                 p = buf;
5380                 encode_value (unwind_info_len, p, &p);
5381                 emit_bytes (acfg, buf, p - buf);
5382                 emit_bytes (acfg, unwind_info, unwind_info_len);
5383
5384                 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5385         }
5386 }
5387
5388 static void
5389 emit_class_info (MonoAotCompile *acfg)
5390 {
5391         int i;
5392         char symbol [256];
5393         gint32 *offsets;
5394
5395         offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5396         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5397                 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5398
5399         sprintf (symbol, "class_info_offsets");
5400         emit_section_change (acfg, RODATA_SECT, 1);
5401         emit_global (acfg, symbol, FALSE);
5402         emit_alignment (acfg, 8);
5403         emit_label (acfg, symbol);
5404
5405         acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5406         g_free (offsets);
5407 }
5408
5409 typedef struct ClassNameTableEntry {
5410         guint32 token, index;
5411         struct ClassNameTableEntry *next;
5412 } ClassNameTableEntry;
5413
5414 static void
5415 emit_class_name_table (MonoAotCompile *acfg)
5416 {
5417         int i, table_size;
5418         guint32 token, hash;
5419         MonoClass *klass;
5420         GPtrArray *table;
5421         char *full_name;
5422         char symbol [256];
5423         ClassNameTableEntry *entry, *new_entry;
5424
5425         /*
5426          * Construct a chained hash table for mapping class names to typedef tokens.
5427          */
5428         table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5429         table = g_ptr_array_sized_new (table_size);
5430         for (i = 0; i < table_size; ++i)
5431                 g_ptr_array_add (table, NULL);
5432         for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5433                 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5434                 klass = mono_class_get (acfg->image, token);
5435                 if (!klass)
5436                         continue;
5437                 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5438                 hash = mono_metadata_str_hash (full_name) % table_size;
5439                 g_free (full_name);
5440
5441                 /* FIXME: Allocate from the mempool */
5442                 new_entry = g_new0 (ClassNameTableEntry, 1);
5443                 new_entry->token = token;
5444
5445                 entry = g_ptr_array_index (table, hash);
5446                 if (entry == NULL) {
5447                         new_entry->index = hash;
5448                         g_ptr_array_index (table, hash) = new_entry;
5449                 } else {
5450                         while (entry->next)
5451                                 entry = entry->next;
5452                         
5453                         entry->next = new_entry;
5454                         new_entry->index = table->len;
5455                         g_ptr_array_add (table, new_entry);
5456                 }
5457         }
5458
5459         /* Emit the table */
5460         sprintf (symbol, "class_name_table");
5461         emit_section_change (acfg, RODATA_SECT, 0);
5462         emit_global (acfg, symbol, FALSE);
5463         emit_alignment (acfg, 8);
5464         emit_label (acfg, symbol);
5465
5466         /* FIXME: Optimize memory usage */
5467         g_assert (table_size < 65000);
5468         emit_int16 (acfg, table_size);
5469         g_assert (table->len < 65000);
5470         for (i = 0; i < table->len; ++i) {
5471                 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5472
5473                 if (entry == NULL) {
5474                         emit_int16 (acfg, 0);
5475                         emit_int16 (acfg, 0);
5476                 } else {
5477                         emit_int16 (acfg, mono_metadata_token_index (entry->token));
5478                         if (entry->next)
5479                                 emit_int16 (acfg, entry->next->index);
5480                         else
5481                                 emit_int16 (acfg, 0);
5482                 }
5483         }
5484 }
5485
5486 static void
5487 emit_image_table (MonoAotCompile *acfg)
5488 {
5489         int i;
5490         char symbol [256];
5491
5492         /*
5493          * The image table is small but referenced in a lot of places.
5494          * So we emit it at once, and reference its elements by an index.
5495          */
5496
5497         sprintf (symbol, "mono_image_table");
5498         emit_section_change (acfg, RODATA_SECT, 1);
5499         emit_global (acfg, symbol, FALSE);
5500         emit_alignment (acfg, 8);
5501         emit_label (acfg, symbol);
5502
5503         emit_int32 (acfg, acfg->image_table->len);
5504         for (i = 0; i < acfg->image_table->len; i++) {
5505                 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5506                 MonoAssemblyName *aname = &image->assembly->aname;
5507
5508                 /* FIXME: Support multi-module assemblies */
5509                 g_assert (image->assembly->image == image);
5510
5511                 emit_string (acfg, image->assembly_name);
5512                 emit_string (acfg, image->guid);
5513                 emit_string (acfg, aname->culture ? aname->culture : "");
5514                 emit_string (acfg, (const char*)aname->public_key_token);
5515
5516                 emit_alignment (acfg, 8);
5517                 emit_int32 (acfg, aname->flags);
5518                 emit_int32 (acfg, aname->major);
5519                 emit_int32 (acfg, aname->minor);
5520                 emit_int32 (acfg, aname->build);
5521                 emit_int32 (acfg, aname->revision);
5522         }
5523 }
5524
5525 static void
5526 emit_got_info (MonoAotCompile *acfg)
5527 {
5528         char symbol [256];
5529         int i, first_plt_got_patch, buf_size;
5530         guint8 *p, *buf;
5531         guint32 *got_info_offsets;
5532
5533         /* Add the patches needed by the PLT to the GOT */
5534         acfg->plt_got_offset_base = acfg->got_offset;
5535         first_plt_got_patch = acfg->got_patches->len;
5536         for (i = 1; i < acfg->plt_offset; ++i) {
5537                 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5538
5539                 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5540         }
5541
5542         acfg->got_offset += acfg->plt_offset;
5543
5544         /**
5545          * FIXME: 
5546          * - optimize offsets table.
5547          * - reduce number of exported symbols.
5548          * - emit info for a klass only once.
5549          * - determine when a method uses a GOT slot which is guaranteed to be already 
5550          *   initialized.
5551          * - clean up and document the code.
5552          * - use String.Empty in class libs.
5553          */
5554
5555         /* Encode info required to decode shared GOT entries */
5556         buf_size = acfg->got_patches->len * 128;
5557         p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5558         got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5559         acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5560         /* Unused */
5561         if (acfg->plt_offset)
5562                 acfg->plt_got_info_offsets [0] = 0;
5563         for (i = 0; i < acfg->got_patches->len; ++i) {
5564                 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5565
5566                 p = buf;
5567
5568                 encode_value (ji->type, p, &p);
5569                 encode_patch (acfg, ji, p, &p);
5570
5571                 g_assert (p - buf <= buf_size);
5572                 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5573
5574                 if (i >= first_plt_got_patch)
5575                         acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5576                 acfg->stats.got_info_size += p - buf;
5577         }
5578
5579         /* Emit got_info_offsets table */
5580         sprintf (symbol, "got_info_offsets");
5581         emit_section_change (acfg, RODATA_SECT, 1);
5582         emit_global (acfg, symbol, FALSE);
5583         emit_alignment (acfg, 8);
5584         emit_label (acfg, symbol);
5585
5586         /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5587         acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5588 }
5589
5590 static void
5591 emit_got (MonoAotCompile *acfg)
5592 {
5593         char symbol [256];
5594
5595         if (!acfg->llvm) {
5596                 /* Don't make GOT global so accesses to it don't need relocations */
5597                 sprintf (symbol, "%s", acfg->got_symbol);
5598                 emit_section_change (acfg, ".bss", 0);
5599                 emit_alignment (acfg, 8);
5600                 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5601                 emit_label (acfg, symbol);
5602                 if (acfg->got_offset > 0)
5603                         emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5604
5605                 sprintf (symbol, "got_end");
5606                 emit_label (acfg, symbol);
5607         }
5608
5609         sprintf (symbol, "mono_aot_got_addr");
5610         emit_section_change (acfg, ".data", 0);
5611         emit_global (acfg, symbol, FALSE);
5612         emit_alignment (acfg, 8);
5613         emit_label (acfg, symbol);
5614         emit_pointer (acfg, acfg->got_symbol);
5615 }
5616
5617 typedef struct GlobalsTableEntry {
5618         guint32 value, index;
5619         struct GlobalsTableEntry *next;
5620 } GlobalsTableEntry;
5621
5622 static void
5623 emit_globals_table (MonoAotCompile *acfg)
5624 {
5625         int i, table_size;
5626         guint32 hash;
5627         GPtrArray *table;
5628         char symbol [256];
5629         GlobalsTableEntry *entry, *new_entry;
5630
5631         /*
5632          * Construct a chained hash table for mapping global names to their index in
5633          * the globals table.
5634          */
5635         table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5636         table = g_ptr_array_sized_new (table_size);
5637         for (i = 0; i < table_size; ++i)
5638                 g_ptr_array_add (table, NULL);
5639         for (i = 0; i < acfg->globals->len; ++i) {
5640                 char *name = g_ptr_array_index (acfg->globals, i);
5641
5642                 hash = mono_metadata_str_hash (name) % table_size;
5643
5644                 /* FIXME: Allocate from the mempool */
5645                 new_entry = g_new0 (GlobalsTableEntry, 1);
5646                 new_entry->value = i;
5647
5648                 entry = g_ptr_array_index (table, hash);
5649                 if (entry == NULL) {
5650                         new_entry->index = hash;
5651                         g_ptr_array_index (table, hash) = new_entry;
5652                 } else {
5653                         while (entry->next)
5654                                 entry = entry->next;
5655                         
5656                         entry->next = new_entry;
5657                         new_entry->index = table->len;
5658                         g_ptr_array_add (table, new_entry);
5659                 }
5660         }
5661
5662         /* Emit the table */
5663         sprintf (symbol, ".Lglobals_hash");
5664         emit_section_change (acfg, RODATA_SECT, 0);
5665         emit_alignment (acfg, 8);
5666         emit_label (acfg, symbol);
5667
5668         /* FIXME: Optimize memory usage */
5669         g_assert (table_size < 65000);
5670         emit_int16 (acfg, table_size);
5671         for (i = 0; i < table->len; ++i) {
5672                 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5673
5674                 if (entry == NULL) {
5675                         emit_int16 (acfg, 0);
5676                         emit_int16 (acfg, 0);
5677                 } else {
5678                         emit_int16 (acfg, entry->value + 1);
5679                         if (entry->next)
5680                                 emit_int16 (acfg, entry->next->index);
5681                         else
5682                                 emit_int16 (acfg, 0);
5683                 }
5684         }
5685
5686         /* Emit the names */
5687         for (i = 0; i < acfg->globals->len; ++i) {
5688                 char *name = g_ptr_array_index (acfg->globals, i);
5689
5690                 sprintf (symbol, "name_%d", i);
5691                 emit_section_change (acfg, RODATA_SECT, 1);
5692                 emit_label (acfg, symbol);
5693                 emit_string (acfg, name);
5694         }
5695
5696         /* Emit the globals table */
5697         sprintf (symbol, ".Lglobals");
5698         emit_section_change (acfg, ".data", 0);
5699         /* This is not a global, since it is accessed by the init function */
5700         emit_alignment (acfg, 8);
5701         emit_label (acfg, symbol);
5702
5703         sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5704         emit_pointer (acfg, symbol);
5705
5706         for (i = 0; i < acfg->globals->len; ++i) {
5707                 char *name = g_ptr_array_index (acfg->globals, i);
5708
5709                 sprintf (symbol, "name_%d", i);
5710                 emit_pointer (acfg, symbol);
5711
5712                 sprintf (symbol, "%s", name);
5713                 emit_pointer (acfg, symbol);
5714         }
5715         /* Null terminate the table */
5716         emit_int32 (acfg, 0);
5717         emit_int32 (acfg, 0);
5718 }
5719
5720 static void
5721 emit_globals (MonoAotCompile *acfg)
5722 {
5723         char *build_info;
5724
5725         emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5726
5727         emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5728
5729         if (acfg->aot_opts.bind_to_runtime_version) {
5730                 build_info = mono_get_runtime_build_info ();
5731                 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5732                 g_free (build_info);
5733         } else {
5734                 emit_string_symbol (acfg, "mono_runtime_version", "");
5735         }
5736
5737         /* 
5738          * When static linking, we emit a global which will point to the symbol table.
5739          */
5740         if (acfg->aot_opts.static_link) {
5741                 char symbol [256];
5742                 char *p;
5743
5744                 /* Emit a string holding the assembly name */
5745                 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5746
5747                 emit_globals_table (acfg);
5748
5749                 /* 
5750                  * Emit a global symbol which can be passed by an embedding app to
5751                  * mono_aot_register_module ().
5752                  */
5753 #if defined(__MACH__) && !defined(__native_client_codegen__)
5754                 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5755 #else
5756                 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5757 #endif
5758
5759                 /* Get rid of characters which cannot occur in symbols */
5760                 p = symbol;
5761                 for (p = symbol; *p; ++p) {
5762                         if (!(isalnum (*p) || *p == '_'))
5763                                 *p = '_';
5764                 }
5765                 acfg->static_linking_symbol = g_strdup (symbol);
5766                 emit_global_inner (acfg, symbol, FALSE);
5767                 emit_alignment (acfg, 8);
5768                 emit_label (acfg, symbol);
5769                 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5770                 emit_pointer (acfg, symbol);
5771         }
5772 }
5773
5774 static void
5775 emit_autoreg (MonoAotCompile *acfg)
5776 {
5777         char *symbol;
5778
5779         /*
5780          * Emit a function into the .ctor section which will be called by the ELF
5781          * loader to register this module with the runtime.
5782          */
5783         if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5784                 return;
5785
5786         symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5787
5788         arch_emit_autoreg (acfg, symbol);
5789
5790         g_free (symbol);
5791 }       
5792
5793 static void
5794 emit_mem_end (MonoAotCompile *acfg)
5795 {
5796         char symbol [128];
5797
5798         sprintf (symbol, "mem_end");
5799         emit_section_change (acfg, ".text", 1);
5800         emit_global (acfg, symbol, FALSE);
5801         emit_alignment (acfg, 8);
5802         emit_label (acfg, symbol);
5803 }
5804
5805 /*
5806  * Emit a structure containing all the information not stored elsewhere.
5807  */
5808 static void
5809 emit_file_info (MonoAotCompile *acfg)
5810 {
5811         char symbol [128];
5812         int i;
5813         int gc_name_offset;
5814         const char *gc_name;
5815
5816         /*
5817          * The managed allocators are GC specific, so can't use an AOT image created by one GC
5818          * in another.
5819          */
5820         gc_name = mono_gc_get_gc_name ();
5821         gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
5822
5823         sprintf (symbol, "mono_aot_file_info");
5824         emit_section_change (acfg, ".data", 0);
5825         emit_alignment (acfg, 8);
5826         emit_label (acfg, symbol);
5827         emit_global (acfg, symbol, FALSE);
5828
5829         /* The data emitted here must match MonoAotFileInfo. */
5830         emit_int32 (acfg, acfg->plt_got_offset_base);
5831         emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5832         emit_int32 (acfg, acfg->plt_offset);
5833         emit_int32 (acfg, acfg->nmethods);
5834         emit_int32 (acfg, acfg->flags);
5835         emit_int32 (acfg, acfg->opts);
5836         emit_int32 (acfg, gc_name_offset);
5837
5838         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5839                 emit_int32 (acfg, acfg->num_trampolines [i]);
5840         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5841                 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5842         for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5843                 emit_int32 (acfg, acfg->trampoline_size [i]);
5844 }
5845
5846 static void
5847 emit_blob (MonoAotCompile *acfg)
5848 {
5849         char symbol [128];
5850
5851         sprintf (symbol, "blob");
5852         emit_section_change (acfg, RODATA_SECT, 1);
5853         emit_global (acfg, symbol, FALSE);
5854         emit_alignment (acfg, 8);
5855         emit_label (acfg, symbol);
5856
5857         emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5858 }
5859
5860 static void
5861 emit_dwarf_info (MonoAotCompile *acfg)
5862 {
5863 #ifdef EMIT_DWARF_INFO
5864         int i;
5865         char symbol [128], symbol2 [128];
5866
5867         /* DIEs for methods */
5868         for (i = 0; i < acfg->nmethods; ++i) {
5869                 MonoCompile *cfg = acfg->cfgs [i];
5870
5871                 if (!cfg)
5872                         continue;
5873
5874                 // FIXME: LLVM doesn't define .Lme_...
5875                 if (cfg->compile_llvm)
5876                         continue;
5877
5878                 sprintf (symbol, "%s", cfg->asm_symbol);
5879                 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5880
5881                 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 ()));
5882         }
5883 #endif
5884 }
5885
5886 static void
5887 collect_methods (MonoAotCompile *acfg)
5888 {
5889         int i;
5890         MonoImage *image = acfg->image;
5891
5892         /* Collect methods */
5893         for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5894                 MonoMethod *method;
5895                 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5896
5897                 method = mono_get_method (acfg->image, token, NULL);
5898
5899                 if (!method) {
5900                         printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5901                         exit (1);
5902                 }
5903                         
5904                 /* Load all methods eagerly to skip the slower lazy loading code */
5905                 mono_class_setup_methods (method->klass);
5906
5907                 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5908                         /* Compile the wrapper instead */
5909                         /* We do this here instead of add_wrappers () because it is easy to do it here */
5910                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5911                         method = wrapper;
5912                 }
5913
5914                 /* FIXME: Some mscorlib methods don't have debug info */
5915                 /*
5916                 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5917                         if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5918                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5919                                   (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5920                                   (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5921                                 if (!mono_debug_lookup_method (method)) {
5922                                         fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5923                                         exit (1);
5924                                 }
5925                         }
5926                 }
5927                 */
5928
5929                 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5930                 add_method_with_index (acfg, method, i, FALSE);
5931                 acfg->method_index ++;
5932         }
5933
5934         add_generic_instances (acfg);
5935
5936         if (acfg->aot_opts.full_aot)
5937                 add_wrappers (acfg);
5938 }
5939
5940 static void
5941 compile_methods (MonoAotCompile *acfg)
5942 {
5943         int i, methods_len;
5944
5945         if (acfg->aot_opts.nthreads > 0) {
5946                 GPtrArray *frag;
5947                 int len, j;
5948                 GPtrArray *threads;
5949                 HANDLE handle;
5950                 gpointer *user_data;
5951                 MonoMethod **methods;
5952
5953                 methods_len = acfg->methods->len;
5954
5955                 len = acfg->methods->len / acfg->aot_opts.nthreads;
5956                 g_assert (len > 0);
5957                 /* 
5958                  * Partition the list of methods into fragments, and hand it to threads to
5959                  * process.
5960                  */
5961                 threads = g_ptr_array_new ();
5962                 /* Make a copy since acfg->methods is modified by compile_method () */
5963                 methods = g_new0 (MonoMethod*, methods_len);
5964                 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5965                 for (i = 0; i < methods_len; ++i)
5966                         methods [i] = g_ptr_array_index (acfg->methods, i);
5967                 i = 0;
5968                 while (i < methods_len) {
5969                         frag = g_ptr_array_new ();
5970                         for (j = 0; j < len; ++j) {
5971                                 if (i < methods_len) {
5972                                         g_ptr_array_add (frag, methods [i]);
5973                                         i ++;
5974                                 }
5975                         }
5976
5977                         user_data = g_new0 (gpointer, 3);
5978                         user_data [0] = mono_domain_get ();
5979                         user_data [1] = acfg;
5980                         user_data [2] = frag;
5981                         
5982                         handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5983                         g_ptr_array_add (threads, handle);
5984                 }
5985                 g_free (methods);
5986
5987                 for (i = 0; i < threads->len; ++i) {
5988                         WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5989                 }
5990         } else {
5991                 methods_len = 0;
5992         }
5993
5994         /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5995         for (i = methods_len; i < acfg->methods->len; ++i) {
5996                 /* This can new methods to acfg->methods */
5997                 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5998         }
5999 }
6000
6001 static int
6002 compile_asm (MonoAotCompile *acfg)
6003 {
6004         char *command, *objfile;
6005         char *outfile_name, *tmp_outfile_name;
6006         const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6007
6008 #if defined(TARGET_AMD64)
6009 #define AS_OPTIONS "--64"
6010 #elif defined(TARGET_POWERPC64)
6011 #define AS_OPTIONS "-a64 -mppc64"
6012 #define LD_OPTIONS "-m elf64ppc"
6013 #elif defined(sparc) && SIZEOF_VOID_P == 8
6014 #define AS_OPTIONS "-xarch=v9"
6015 #else
6016 #define AS_OPTIONS ""
6017 #endif
6018
6019 #ifdef __native_client_codegen__
6020 #define AS_NAME "nacl-as"
6021 #else
6022 #define AS_NAME "as"
6023 #endif
6024
6025 #ifndef LD_OPTIONS
6026 #define LD_OPTIONS ""
6027 #endif
6028
6029 #ifdef ENABLE_LLVM
6030 #define EH_LD_OPTIONS "--eh-frame-hdr"
6031 #else
6032 #define EH_LD_OPTIONS ""
6033 #endif
6034
6035         if (acfg->aot_opts.asm_only) {
6036                 printf ("Output file: '%s'.\n", acfg->tmpfname);
6037                 if (acfg->aot_opts.static_link)
6038                         printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6039                 return 0;
6040         }
6041
6042         if (acfg->aot_opts.static_link) {
6043                 if (acfg->aot_opts.outfile)
6044                         objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6045                 else
6046                         objfile = g_strdup_printf ("%s.o", acfg->image->name);
6047         } else {
6048                 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6049         }
6050         command = g_strdup_printf ("%s%s %s %s -o %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->tmpfname, objfile);
6051         printf ("Executing the native assembler: %s\n", command);
6052         if (system (command) != 0) {
6053                 g_free (command);
6054                 g_free (objfile);
6055                 return 1;
6056         }
6057
6058         g_free (command);
6059
6060         if (acfg->aot_opts.static_link) {
6061                 printf ("Output file: '%s'.\n", objfile);
6062                 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6063                 g_free (objfile);
6064                 return 0;
6065         }
6066
6067         if (acfg->aot_opts.outfile)
6068                 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6069         else
6070                 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6071
6072         tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6073
6074 #if defined(sparc)
6075         command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6076 #elif defined(__ppc__) && defined(__MACH__)
6077         command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6078 #elif defined(HOST_WIN32)
6079         command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6080 #else
6081         command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6082 #endif
6083         printf ("Executing the native linker: %s\n", command);
6084         if (system (command) != 0) {
6085                 g_free (tmp_outfile_name);
6086                 g_free (outfile_name);
6087                 g_free (command);
6088                 g_free (objfile);
6089                 return 1;
6090         }
6091
6092         g_free (command);
6093         unlink (objfile);
6094         /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6095         printf ("Stripping the binary: %s\n", com);
6096         system (com);
6097         g_free (com);*/
6098
6099 #if defined(TARGET_ARM) && !defined(__MACH__)
6100         /* 
6101          * gas generates 'mapping symbols' each time code and data is mixed, which 
6102          * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6103          */
6104         command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6105         printf ("Stripping the binary: %s\n", command);
6106         if (system (command) != 0) {
6107                 g_free (tmp_outfile_name);
6108                 g_free (outfile_name);
6109                 g_free (command);
6110                 g_free (objfile);
6111                 return 1;
6112         }
6113 #endif
6114
6115         rename (tmp_outfile_name, outfile_name);
6116
6117         g_free (tmp_outfile_name);
6118         g_free (outfile_name);
6119         g_free (objfile);
6120
6121         if (acfg->aot_opts.save_temps)
6122                 printf ("Retained input file.\n");
6123         else
6124                 unlink (acfg->tmpfname);
6125
6126         return 0;
6127 }
6128
6129 static MonoAotCompile*
6130 acfg_create (MonoAssembly *ass, guint32 opts)
6131 {
6132         MonoImage *image = ass->image;
6133         MonoAotCompile *acfg;
6134         int i;
6135
6136         acfg = g_new0 (MonoAotCompile, 1);
6137         acfg->methods = g_ptr_array_new ();
6138         acfg->method_indexes = g_hash_table_new (NULL, NULL);
6139         acfg->method_depth = g_hash_table_new (NULL, NULL);
6140         acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6141         acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6142         acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6143         acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6144         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6145                 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6146         acfg->got_patches = g_ptr_array_new ();
6147         acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6148         acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6149         acfg->image_hash = g_hash_table_new (NULL, NULL);
6150         acfg->image_table = g_ptr_array_new ();
6151         acfg->globals = g_ptr_array_new ();
6152         acfg->image = image;
6153         acfg->opts = opts;
6154         acfg->mempool = mono_mempool_new ();
6155         acfg->extra_methods = g_ptr_array_new ();
6156         acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6157         acfg->unwind_ops = g_ptr_array_new ();
6158         acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6159         InitializeCriticalSection (&acfg->mutex);
6160
6161         return acfg;
6162 }
6163
6164 static void
6165 acfg_free (MonoAotCompile *acfg)
6166 {
6167         int i;
6168
6169         img_writer_destroy (acfg->w);
6170         for (i = 0; i < acfg->nmethods; ++i)
6171                 if (acfg->cfgs [i])
6172                         g_free (acfg->cfgs [i]);
6173         g_free (acfg->cfgs);
6174         g_free (acfg->static_linking_symbol);
6175         g_free (acfg->got_symbol);
6176         g_free (acfg->plt_symbol);
6177         g_ptr_array_free (acfg->methods, TRUE);
6178         g_ptr_array_free (acfg->got_patches, TRUE);
6179         g_ptr_array_free (acfg->image_table, TRUE);
6180         g_ptr_array_free (acfg->globals, TRUE);
6181         g_ptr_array_free (acfg->unwind_ops, TRUE);
6182         g_hash_table_destroy (acfg->method_indexes);
6183         g_hash_table_destroy (acfg->method_depth);
6184         g_hash_table_destroy (acfg->plt_offset_to_entry);
6185         g_hash_table_destroy (acfg->patch_to_plt_entry);
6186         g_hash_table_destroy (acfg->patch_to_got_offset);
6187         g_hash_table_destroy (acfg->method_to_cfg);
6188         g_hash_table_destroy (acfg->token_info_hash);
6189         g_hash_table_destroy (acfg->image_hash);
6190         g_hash_table_destroy (acfg->unwind_info_offsets);
6191         g_hash_table_destroy (acfg->method_label_hash);
6192         for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6193                 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6194         g_free (acfg->patch_to_got_offset_by_type);
6195         mono_mempool_destroy (acfg->mempool);
6196         g_free (acfg);
6197 }
6198
6199 int
6200 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6201 {
6202         MonoImage *image = ass->image;
6203         int i, res;
6204         MonoAotCompile *acfg;
6205         char *outfile_name, *tmp_outfile_name, *p;
6206         TV_DECLARE (atv);
6207         TV_DECLARE (btv);
6208
6209         printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6210
6211         acfg = acfg_create (ass, opts);
6212
6213         memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6214         acfg->aot_opts.write_symbols = TRUE;
6215         acfg->aot_opts.ntrampolines = 1024;
6216         acfg->aot_opts.nrgctx_trampolines = 1024;
6217         acfg->aot_opts.nimt_trampolines = 128;
6218
6219         mono_aot_parse_options (aot_options, &acfg->aot_opts);
6220
6221         if (acfg->aot_opts.static_link)
6222                 acfg->aot_opts.autoreg = TRUE;
6223
6224         //acfg->aot_opts.print_skipped_methods = TRUE;
6225
6226 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6227         if (acfg->aot_opts.full_aot) {
6228                 printf ("--aot=full is not supported on this platform.\n");
6229                 return 1;
6230         }
6231 #endif
6232
6233         if (acfg->aot_opts.static_link)
6234                 acfg->aot_opts.asm_writer = TRUE;
6235
6236         if (acfg->aot_opts.soft_debug) {
6237                 MonoDebugOptions *opt = mini_get_debug_options ();
6238
6239                 opt->mdb_optimizations = TRUE;
6240                 opt->gen_seq_points = TRUE;
6241
6242                 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6243                         fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6244                         return 1;
6245                 }
6246         }
6247
6248 #ifdef ENABLE_LLVM
6249         acfg->llvm = TRUE;
6250         acfg->aot_opts.asm_writer = TRUE;
6251         acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6252 #endif
6253
6254         if (acfg->aot_opts.full_aot)
6255                 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6256
6257         load_profile_files (acfg);
6258
6259         acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6260 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6261         acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6262 #endif
6263         acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6264
6265         acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6266         acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6267
6268         /* Get rid of characters which cannot occur in symbols */
6269         for (p = acfg->got_symbol_base; *p; ++p) {
6270                 if (!(isalnum (*p) || *p == '_'))
6271                         *p = '_';
6272         }
6273         for (p = acfg->plt_symbol; *p; ++p) {
6274                 if (!(isalnum (*p) || *p == '_'))
6275                         *p = '_';
6276         }
6277
6278         acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6279
6280         /*
6281          * The prefix LLVM likes to put in front of symbol names on darwin.
6282          * The mach-os specs require this for globals, but LLVM puts them in front of all
6283          * symbols. We need to handle this, since we need to refer to LLVM generated
6284          * symbols.
6285          */
6286         acfg->llvm_label_prefix = "";
6287         if (acfg->llvm)
6288                 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6289
6290         acfg->method_index = 1;
6291
6292         collect_methods (acfg);
6293
6294         acfg->cfgs_size = acfg->methods->len + 32;
6295         acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6296
6297         /* PLT offset 0 is reserved for the PLT trampoline */
6298         acfg->plt_offset = 1;
6299
6300 #ifdef ENABLE_LLVM
6301         llvm_acfg = acfg;
6302         mono_llvm_create_aot_module (acfg->got_symbol_base);
6303 #endif
6304
6305         /* GOT offset 0 is reserved for the address of the current assembly */
6306         {
6307                 MonoJumpInfo *ji;
6308
6309                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6310                 ji->type = MONO_PATCH_INFO_IMAGE;
6311                 ji->data.image = acfg->image;
6312
6313                 get_got_offset (acfg, ji);
6314
6315                 /* Slot 1 is reserved for the mscorlib got addr */
6316                 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6317                 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6318                 get_got_offset (acfg, ji);
6319         }
6320
6321         TV_GETTIME (atv);
6322
6323         compile_methods (acfg);
6324
6325         TV_GETTIME (btv);
6326
6327         acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6328
6329         TV_GETTIME (atv);
6330
6331 #ifdef ENABLE_LLVM
6332         if (acfg->llvm) {
6333                 if (acfg->aot_opts.asm_only) {
6334                         if (acfg->aot_opts.outfile)
6335                                 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6336                         else
6337                                 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6338                 } else {
6339                         acfg->tmpfname = g_strdup ("temp.s");
6340                 }
6341         }
6342
6343         emit_llvm_file (acfg);
6344 #endif
6345
6346         if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6347                 if (acfg->aot_opts.outfile)
6348                         outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6349                 else
6350                         outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6351
6352                 /* 
6353                  * Can't use g_file_open_tmp () as it will be deleted at exit, and
6354                  * it might be in another file system so the rename () won't work.
6355                  */
6356                 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6357
6358                 acfg->fp = fopen (tmp_outfile_name, "w");
6359                 if (!acfg->fp) {
6360                         printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6361                         return 1;
6362                 }
6363
6364                 acfg->w = img_writer_create (acfg->fp, TRUE);
6365                 acfg->use_bin_writer = TRUE;
6366         } else {
6367                 if (acfg->llvm) {
6368                         /* Append to the .s file created by llvm */
6369                         /* FIXME: Use multiple files instead */
6370                         acfg->fp = fopen (acfg->tmpfname, "a+");
6371                 } else {
6372                         if (acfg->aot_opts.asm_only) {
6373                                 if (acfg->aot_opts.outfile)
6374                                         acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6375                                 else
6376                                         acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6377                                 acfg->fp = fopen (acfg->tmpfname, "w+");
6378                         } else {
6379                                 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6380                                 acfg->fp = fdopen (i, "w+");
6381                         }
6382                         g_assert (acfg->fp);
6383                 }
6384                 acfg->w = img_writer_create (acfg->fp, FALSE);
6385                 
6386                 tmp_outfile_name = NULL;
6387                 outfile_name = NULL;
6388         }
6389
6390         acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6391
6392         /* Compute symbols for methods */
6393         for (i = 0; i < acfg->nmethods; ++i) {
6394                 if (acfg->cfgs [i]) {
6395                         MonoCompile *cfg = acfg->cfgs [i];
6396                         int method_index = get_method_index (acfg, cfg->orig_method);
6397
6398                         cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6399                 }
6400         }
6401
6402         if (!acfg->aot_opts.nodebug)
6403                 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6404
6405         img_writer_emit_start (acfg->w);
6406
6407         if (acfg->dwarf)
6408                 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6409
6410         emit_code (acfg);
6411
6412         emit_info (acfg);
6413
6414         emit_extra_methods (acfg);
6415
6416         emit_trampolines (acfg);
6417
6418         emit_class_name_table (acfg);
6419
6420         emit_got_info (acfg);
6421
6422         emit_exception_info (acfg);
6423
6424         emit_unwind_info (acfg);
6425
6426         emit_class_info (acfg);
6427
6428         emit_plt (acfg);
6429
6430         emit_image_table (acfg);
6431
6432         emit_got (acfg);
6433
6434         emit_file_info (acfg);
6435
6436         emit_blob (acfg);
6437
6438         emit_globals (acfg);
6439
6440         emit_autoreg (acfg);
6441
6442         if (acfg->dwarf) {
6443                 emit_dwarf_info (acfg);
6444                 mono_dwarf_writer_close (acfg->dwarf);
6445         }
6446
6447         emit_mem_end (acfg);
6448
6449         TV_GETTIME (btv);
6450
6451         acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6452
6453         if (acfg->llvm)
6454                 g_assert (acfg->got_offset <= acfg->final_got_size);
6455
6456         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);
6457
6458         TV_GETTIME (atv);
6459         res = img_writer_emit_writeout (acfg->w);
6460         if (res != 0) {
6461                 acfg_free (acfg);
6462                 return res;
6463         }
6464         if (acfg->use_bin_writer) {
6465                 int err = rename (tmp_outfile_name, outfile_name);
6466
6467                 if (err) {
6468                         printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6469                         return 1;
6470                 }
6471         } else {
6472                 res = compile_asm (acfg);
6473                 if (res != 0) {
6474                         acfg_free (acfg);
6475                         return res;
6476                 }
6477         }
6478         TV_GETTIME (btv);
6479         acfg->stats.link_time = TV_ELAPSED (atv, btv);
6480
6481         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);
6482         if (acfg->stats.genericcount)
6483                 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6484         if (acfg->stats.abscount)
6485                 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6486         if (acfg->stats.lmfcount)
6487                 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6488         if (acfg->stats.ocount)
6489                 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6490         if (acfg->llvm)
6491                 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6492         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);
6493         printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6494
6495         if (acfg->aot_opts.stats) {
6496                 int i;
6497
6498                 printf ("GOT slot distribution:\n");
6499                 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6500                         if (acfg->stats.got_slot_types [i])
6501                                 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6502         }
6503
6504         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);
6505
6506         acfg_free (acfg);
6507         
6508         return 0;
6509 }
6510
6511 #else
6512
6513 /* AOT disabled */
6514
6515 int
6516 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6517 {
6518         return 0;
6519 }
6520
6521 #endif