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