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