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