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