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