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