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