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