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