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