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