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