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