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