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