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