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