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