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