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