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