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