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