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