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