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