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