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