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