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