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