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