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