2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
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
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.
25 #include <sys/types.h>
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>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
74 #define RODATA_SECT ".text"
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)
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__APPLE__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
88 #define SHARED_EXT ".so"
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
95 typedef struct MonoAotOptions {
98 gboolean write_symbols;
99 gboolean metadata_only;
100 gboolean bind_to_runtime_version;
103 gboolean static_link;
110 int nrgctx_trampolines;
111 int nimt_trampolines;
112 gboolean print_skipped_methods;
120 typedef struct MonoAotStats {
121 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
122 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
123 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
124 int got_slots, offsets_size;
125 int got_slot_types [MONO_PATCH_INFO_NONE];
126 int jit_time, gen_time, link_time;
129 typedef struct MonoAotCompile {
132 GHashTable *method_indexes;
133 GHashTable *method_depth;
136 GHashTable *patch_to_plt_entry;
137 GHashTable *plt_offset_to_entry;
138 GHashTable *patch_to_got_offset;
139 GHashTable **patch_to_got_offset_by_type;
140 GPtrArray *got_patches;
141 GHashTable *image_hash;
142 GHashTable *method_to_cfg;
143 GHashTable *token_info_hash;
144 GPtrArray *extra_methods;
145 GPtrArray *image_table;
147 GPtrArray *method_order;
148 guint32 *plt_got_info_offsets;
149 guint32 got_offset, plt_offset, plt_got_offset_base;
150 guint32 final_got_size;
151 /* Number of GOT entries reserved for trampolines */
152 guint32 num_trampoline_got_entries;
154 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
155 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
156 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
158 MonoAotOptions aot_opts;
161 MonoMemPool *mempool;
164 char *static_linking_symbol;
165 CRITICAL_SECTION mutex;
166 gboolean use_bin_writer;
168 MonoDwarfWriter *dwarf;
172 GHashTable *unwind_info_offsets;
173 GPtrArray *unwind_ops;
174 guint32 unwind_info_offset;
175 char *got_symbol_base;
178 GHashTable *method_label_hash;
179 const char *temp_prefix;
180 const char *llvm_label_prefix;
181 guint32 label_generator;
183 MonoAotFileFlags flags;
184 MonoDynamicStream blob;
185 MonoClass **typespec_classes;
188 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
193 char *symbol, *llvm_symbol, *debug_sym;
195 gboolean jit_used, llvm_used;
198 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
199 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
201 /* This points to the current acfg in LLVM mode */
202 static MonoAotCompile *llvm_acfg;
204 #ifdef HAVE_ARRAY_ELEM_INIT
205 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
206 #define MSGSTRFIELD1(line) str##line
207 static const struct msgstr_t {
208 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
209 #include "patch-info.h"
212 #define PATCH_INFO(a,b) b,
213 #include "patch-info.h"
216 static const gint16 opidx [] = {
217 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
218 #include "patch-info.h"
222 static G_GNUC_UNUSED const char*
223 get_patch_name (int info)
225 return (const char*)&opstr + opidx [info];
229 #define PATCH_INFO(a,b) b,
230 static const char* const
231 patch_types [MONO_PATCH_INFO_NUM + 1] = {
232 #include "patch-info.h"
236 static G_GNUC_UNUSED const char*
237 get_patch_name (int info)
239 return patch_types [info];
244 /* Wrappers around the image writer functions */
247 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
249 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
253 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
255 img_writer_emit_push_section (acfg->w, section_name, subsection);
259 emit_pop_section (MonoAotCompile *acfg)
261 img_writer_emit_pop_section (acfg->w);
265 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
267 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
271 emit_label (MonoAotCompile *acfg, const char *name)
273 img_writer_emit_label (acfg->w, name);
277 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
279 img_writer_emit_bytes (acfg->w, buf, size);
283 emit_string (MonoAotCompile *acfg, const char *value)
285 img_writer_emit_string (acfg->w, value);
289 emit_line (MonoAotCompile *acfg)
291 img_writer_emit_line (acfg->w);
295 emit_alignment (MonoAotCompile *acfg, int size)
297 img_writer_emit_alignment (acfg->w, size);
301 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
303 img_writer_emit_pointer_unaligned (acfg->w, target);
307 emit_pointer (MonoAotCompile *acfg, const char *target)
309 img_writer_emit_pointer (acfg->w, target);
313 emit_int16 (MonoAotCompile *acfg, int value)
315 img_writer_emit_int16 (acfg->w, value);
319 emit_int32 (MonoAotCompile *acfg, int value)
321 img_writer_emit_int32 (acfg->w, value);
325 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
327 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
331 emit_zero_bytes (MonoAotCompile *acfg, int num)
333 img_writer_emit_zero_bytes (acfg->w, num);
337 emit_byte (MonoAotCompile *acfg, guint8 val)
339 img_writer_emit_byte (acfg->w, val);
342 #ifdef __native_client_codegen__
344 emit_nacl_call_alignment (MonoAotCompile *acfg)
346 img_writer_emit_nacl_call_alignment (acfg->w);
350 static G_GNUC_UNUSED void
351 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
353 img_writer_emit_global (acfg->w, name, func);
357 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
359 if (acfg->aot_opts.no_dlsym) {
360 g_ptr_array_add (acfg->globals, g_strdup (name));
361 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
363 img_writer_emit_global (acfg->w, name, func);
368 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
370 img_writer_emit_symbol_size (acfg->w, name, end_label);
374 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
376 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
378 /* On apple, all symbols need to be aligned to avoid warnings from ld */
379 emit_alignment (acfg, 4);
381 img_writer_emit_label (acfg->w, name);
382 img_writer_emit_string (acfg->w, value);
385 static G_GNUC_UNUSED void
386 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
389 guint8 b = value & 0x7f;
391 if (value != 0) /* more bytes to come */
397 static G_GNUC_UNUSED void
398 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
401 gboolean negative = (value < 0);
408 /* the following is unnecessary if the
409 * implementation of >>= uses an arithmetic rather
410 * than logical shift for a signed left operand
414 value |= - ((gint64)1 <<(size - 7));
415 /* sign bit of byte is second high order bit (0x40) */
416 if ((value == 0 && !(byte & 0x40)) ||
417 (value == -1 && (byte & 0x40)))
421 emit_byte (acfg, byte);
425 static G_GNUC_UNUSED void
426 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
431 guint8 b = value & 0x7f;
433 if (value != 0) /* more bytes to come */
441 static G_GNUC_UNUSED void
442 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
445 gboolean negative = (value < 0);
453 /* the following is unnecessary if the
454 * implementation of >>= uses an arithmetic rather
455 * than logical shift for a signed left operand
459 value |= - (1 <<(size - 7));
460 /* sign bit of byte is second high order bit (0x40) */
461 if ((value == 0 && !(byte & 0x40)) ||
462 (value == -1 && (byte & 0x40)))
472 /* ARCHITECTURE SPECIFIC CODE */
474 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
475 #define EMIT_DWARF_INFO 1
478 #if defined(TARGET_ARM)
479 #define AOT_FUNC_ALIGNMENT 4
481 #define AOT_FUNC_ALIGNMENT 16
483 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
484 #undef AOT_FUNC_ALIGNMENT
485 #define AOT_FUNC_ALIGNMENT 32
488 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
489 #define PPC_LD_OP "ld"
490 #define PPC_LDX_OP "ldx"
492 #define PPC_LD_OP "lwz"
493 #define PPC_LDX_OP "lwzx"
497 #define AOT_TARGET_STR "AMD64"
502 #define AOT_TARGET_STR "ARM (MACH)"
504 #define AOT_TARGET_STR "ARM (!MACH)"
508 #ifdef TARGET_POWERPC64
509 #ifdef __mono_ilp32__
510 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
512 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
515 #ifdef TARGET_POWERPC
516 #ifdef __mono_ilp32__
517 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
519 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
525 #define AOT_TARGET_STR "WIN32"
529 #ifdef __native_client_codegen__
530 #define AOT_TARGET_STR "X86 (native client codegen)"
532 #define AOT_TARGET_STR "X86 (!native client codegen)"
536 #ifndef AOT_TARGET_STR
537 #define AOT_TARGET_STR ""
541 arch_init (MonoAotCompile *acfg)
543 acfg->llc_args = g_string_new ("");
544 acfg->as_args = g_string_new ("");
547 * The prefix LLVM likes to put in front of symbol names on darwin.
548 * The mach-os specs require this for globals, but LLVM puts them in front of all
549 * symbols. We need to handle this, since we need to refer to LLVM generated
552 acfg->llvm_label_prefix = "";
555 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
556 g_string_append (acfg->llc_args, "-mattr=+v6");
559 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
560 g_string_append (acfg->as_args, " -mfpu=vfp3");
562 g_string_append (acfg->llc_args, " -soft-float");
565 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
566 acfg->thumb_mixed = TRUE;
568 if (acfg->aot_opts.mtriple)
569 mono_arch_set_target (acfg->aot_opts.mtriple);
573 acfg->llvm_label_prefix = "_";
574 acfg->need_no_dead_strip = TRUE;
577 #if defined(__linux__) && !defined(TARGET_ARM)
578 acfg->need_pt_gnu_stack = TRUE;
583 * arch_emit_direct_call:
585 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
589 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
591 #if defined(TARGET_X86) || defined(TARGET_AMD64)
592 /* Need to make sure this is exactly 5 bytes long */
593 emit_byte (acfg, '\xe8');
594 emit_symbol_diff (acfg, target, ".", -4);
596 #elif defined(TARGET_ARM)
597 if (acfg->use_bin_writer) {
604 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
605 emit_bytes (acfg, buf, 4);
607 img_writer_emit_unset_mode (acfg->w);
608 fprintf (acfg->fp, "bl %s\n", target);
611 #elif defined(TARGET_POWERPC)
612 if (acfg->use_bin_writer) {
613 g_assert_not_reached ();
615 img_writer_emit_unset_mode (acfg->w);
616 fprintf (acfg->fp, "bl %s\n", target);
620 g_assert_not_reached ();
626 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
628 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
629 * in in the 2. slot of every GOT, and require every method to place the GOT
630 * address in r30, even when it doesn't access the GOT otherwise. This way,
631 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
636 * PPC64 uses function descriptors which greatly complicate all code, since
637 * these are used very inconsistently in the runtime. Some functions like
638 * mono_compile_method () return ftn descriptors, while others like the
639 * trampoline creation functions do not.
640 * We assume that all GOT slots contain function descriptors, and create
641 * descriptors in aot-runtime.c when needed.
642 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
643 * from function descriptors, we could do the same, but it would require
644 * rewriting all the ppc/aot code to handle function descriptors properly.
645 * So instead, we use the same approach as on PPC32.
646 * This is a horrible mess, but fixing it would probably lead to an even bigger
652 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
655 #ifdef MONO_ARCH_AOT_SUPPORTED
657 * arch_emit_got_offset:
659 * The memory pointed to by CODE should hold native code for computing the GOT
660 * address. Emit this code while patching it with the offset between code and
661 * the GOT. CODE_SIZE is set to the number of bytes emitted.
664 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
666 #if defined(TARGET_POWERPC64)
667 g_assert (!acfg->use_bin_writer);
668 img_writer_emit_unset_mode (acfg->w);
670 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
671 * unsupported relocations. So we store the got address into the .Lgot_addr
672 * symbol which is in the text segment, compute its address, and load it.
674 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
675 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
676 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
677 fprintf (acfg->fp, "add 30, 30, 0\n");
678 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
679 acfg->label_generator ++;
681 #elif defined(TARGET_POWERPC)
682 g_assert (!acfg->use_bin_writer);
683 img_writer_emit_unset_mode (acfg->w);
684 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
685 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
686 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
687 acfg->label_generator ++;
690 guint32 offset = mono_arch_get_patch_offset (code);
691 emit_bytes (acfg, code, offset);
692 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
694 *code_size = offset + 4;
699 * arch_emit_got_access:
701 * The memory pointed to by CODE should hold native code for loading a GOT
702 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
703 * CODE_SIZE is set to the number of bytes emitted.
706 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
708 /* Emit beginning of instruction */
709 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
711 /* Emit the offset */
713 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
714 *code_size = mono_arch_get_patch_offset (code) + 4;
715 #elif defined(TARGET_X86)
716 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
717 *code_size = mono_arch_get_patch_offset (code) + 4;
718 #elif defined(TARGET_ARM)
719 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
720 *code_size = mono_arch_get_patch_offset (code) + 4;
721 #elif defined(TARGET_POWERPC)
727 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
728 g_assert (code - buf == 8);
729 emit_bytes (acfg, buf, code - buf);
730 *code_size = code - buf;
733 g_assert_not_reached ();
740 * arch_emit_plt_entry:
742 * Emit code for the PLT entry with index INDEX.
745 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
747 #if defined(TARGET_X86)
748 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
749 #if defined(__default_codegen__)
750 /* jmp *<offset>(%ebx) */
751 emit_byte (acfg, 0xff);
752 emit_byte (acfg, 0xa3);
753 emit_int32 (acfg, offset);
754 /* Used by mono_aot_get_plt_info_offset */
755 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
756 #elif defined(__native_client_codegen__)
757 const guint8 kSizeOfNaClJmp = 11;
758 guint8 bytes[kSizeOfNaClJmp];
759 guint8 *pbytes = &bytes[0];
761 x86_jump_membase32 (pbytes, X86_EBX, offset);
762 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
763 /* four bytes of data, used by mono_arch_patch_plt_entry */
764 /* For Native Client, make this work with data embedded in push. */
765 emit_byte (acfg, 0x68); /* hide data in a push */
766 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
767 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
768 #endif /*__native_client_codegen__*/
769 #elif defined(TARGET_AMD64)
770 #if defined(__default_codegen__)
772 * We can't emit jumps because they are 32 bits only so they can't be patched.
773 * So we make indirect calls through GOT entries which are patched by the AOT
774 * loader to point to .Lpd entries.
776 /* jmpq *<offset>(%rip) */
777 emit_byte (acfg, '\xff');
778 emit_byte (acfg, '\x25');
779 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
780 /* Used by mono_aot_get_plt_info_offset */
781 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
782 #elif defined(__native_client_codegen__)
784 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
785 guint8 *code = buf_aligned;
787 /* mov <OFFSET>(%rip), %r11d */
788 emit_byte (acfg, '\x45');
789 emit_byte (acfg, '\x8b');
790 emit_byte (acfg, '\x1d');
791 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
793 amd64_jump_reg (code, AMD64_R11);
794 /* This should be constant for the plt patch */
795 g_assert ((size_t)(code-buf_aligned) == 10);
796 emit_bytes (acfg, buf_aligned, code - buf_aligned);
798 /* Hide data in a push imm32 so it passes validation */
799 emit_byte (acfg, 0x68); /* push */
800 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
801 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
802 #endif /*__native_client_codegen__*/
803 #elif defined(TARGET_ARM)
808 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
809 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
810 emit_bytes (acfg, buf, code - buf);
811 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
812 /* Used by mono_aot_get_plt_info_offset */
813 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
814 #elif defined(TARGET_POWERPC)
815 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
817 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
818 g_assert (!acfg->use_bin_writer);
819 img_writer_emit_unset_mode (acfg->w);
820 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
821 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
822 fprintf (acfg->fp, "add 11, 11, 30\n");
823 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
824 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
825 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
826 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
828 fprintf (acfg->fp, "mtctr 11\n");
829 fprintf (acfg->fp, "bctr\n");
830 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
832 g_assert_not_reached ();
837 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
839 #if defined(TARGET_ARM)
841 /* LLVM calls the PLT entries using bl, so emit a stub */
842 /* FIXME: Too much overhead on every call */
843 fprintf (acfg->fp, ".thumb_func\n");
844 fprintf (acfg->fp, "bx pc\n");
845 fprintf (acfg->fp, "nop\n");
846 fprintf (acfg->fp, ".arm\n");
848 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
849 /* The caller already transitioned to thumb */
850 /* The code below should be 12 bytes long */
851 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
852 /* thumb can't encode ld pc, [pc, ip] */
853 fprintf (acfg->fp, "add ip, pc, ip\n");
854 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
855 fprintf (acfg->fp, "bx ip\n");
856 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
857 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
859 g_assert_not_reached ();
864 * arch_emit_specific_trampoline:
866 * Emit code for a specific trampoline. OFFSET is the offset of the first of
867 * two GOT slots which contain the generic trampoline address and the trampoline
868 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
871 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
874 * The trampolines created here are variations of the specific
875 * trampolines created in mono_arch_create_specific_trampoline (). The
877 * - the generic trampoline address is taken from a got slot.
878 * - the offset of the got slot where the trampoline argument is stored
879 * is embedded in the instruction stream, and the generic trampoline
880 * can load the argument by loading the offset, adding it to the
881 * address of the trampoline to get the address of the got slot, and
882 * loading the argument from there.
883 * - all the trampolines should be of the same length.
885 #if defined(TARGET_AMD64)
886 #if defined(__default_codegen__)
887 /* This should be exactly 16 bytes long */
889 /* call *<offset>(%rip) */
890 emit_byte (acfg, '\x41');
891 emit_byte (acfg, '\xff');
892 emit_byte (acfg, '\x15');
893 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
894 /* This should be relative to the start of the trampoline */
895 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
896 emit_zero_bytes (acfg, 5);
897 #elif defined(__native_client_codegen__)
899 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
900 guint8 *code = buf_aligned;
905 /* Emit this call in 'code' so we can find out how long it is. */
906 amd64_call_reg (code, AMD64_R11);
907 call_start = mono_arch_nacl_skip_nops (buf_aligned);
908 call_len = code - call_start;
910 /* The tramp_size is twice the NaCl alignment because it starts with */
911 /* a call which needs to be aligned to the end of the boundary. */
912 *tramp_size = kNaClAlignment*2;
914 /* Emit nops to align call site below which is 7 bytes plus */
915 /* the length of the call sequence emitted above. */
916 /* Note: this requires the specific trampoline starts on a */
917 /* kNaclAlignedment aligned address, which it does because */
918 /* it's its own function that is aligned. */
920 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
921 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
922 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
924 /* The trampoline is stored at the offset'th pointer, the -4 is */
925 /* present because RIP relative addressing starts at the end of */
926 /* the current instruction, while the label "." is relative to */
927 /* the beginning of the current asm location, which in this case */
928 /* is not the mov instruction, but the offset itself, due to the */
929 /* way the bytes and ints are emitted here. */
930 got_offset = (offset * sizeof(gpointer)) - 4;
932 /* mov <OFFSET>(%rip), %r11d */
933 emit_byte (acfg, '\x45');
934 emit_byte (acfg, '\x8b');
935 emit_byte (acfg, '\x1d');
936 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
939 emit_bytes (acfg, call_start, call_len);
941 /* The arg is stored at the offset+1 pointer, relative to beginning */
942 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
943 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
945 /* We can't emit this data directly, hide in a "push imm32" */
946 emit_byte (acfg, '\x68'); /* push */
947 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
948 emit_alignment (acfg, kNaClAlignment);
949 #endif /*__native_client_codegen__*/
950 #elif defined(TARGET_ARM)
954 /* This should be exactly 20 bytes long */
957 ARM_PUSH (code, 0x5fff);
958 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
959 /* Load the value from the GOT */
960 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
962 ARM_BLX_REG (code, ARMREG_R1);
964 g_assert (code - buf == 16);
967 emit_bytes (acfg, buf, code - buf);
969 * Only one offset is needed, since the second one would be equal to the
972 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
973 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
974 #elif defined(TARGET_POWERPC)
981 g_assert (!acfg->use_bin_writer);
984 * PPC has no ip relative addressing, so we need to compute the address
985 * of the mscorlib got. That is slow and complex, so instead, we store it
986 * in the second got slot of every aot image. The caller already computed
987 * the address of its got and placed it into r30.
989 img_writer_emit_unset_mode (acfg->w);
990 /* Load mscorlib got address */
991 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
992 /* Load generic trampoline address */
993 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
994 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
995 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
996 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
997 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
999 fprintf (acfg->fp, "mtctr 11\n");
1000 /* Load trampoline argument */
1001 /* On ppc, we pass it normally to the generic trampoline */
1002 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1003 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1004 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1005 /* Branch to generic trampoline */
1006 fprintf (acfg->fp, "bctr\n");
1008 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1009 *tramp_size = 10 * 4;
1011 *tramp_size = 9 * 4;
1013 #elif defined(TARGET_X86)
1017 /* Similar to the PPC code above */
1019 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1021 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1022 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1023 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1027 /* Load mscorlib got address */
1028 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1029 /* Push trampoline argument */
1030 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1031 /* Load generic trampoline address */
1032 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1033 /* Branch to generic trampoline */
1034 x86_jump_reg (code, X86_ECX);
1036 #ifdef __native_client_codegen__
1038 /* emit nops to next 32 byte alignment */
1039 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1040 while (code < (buf + a)) x86_nop(code);
1043 emit_bytes (acfg, buf, code - buf);
1045 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1046 g_assert (code - buf == *tramp_size);
1048 g_assert_not_reached ();
1053 * arch_emit_unbox_trampoline:
1055 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1056 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1059 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1061 #if defined(TARGET_AMD64)
1066 this_reg = mono_arch_get_this_arg_reg (NULL);
1068 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1070 emit_bytes (acfg, buf, code - buf);
1072 emit_byte (acfg, '\xe9');
1073 emit_symbol_diff (acfg, call_target, ".", -4);
1074 #elif defined(TARGET_X86)
1081 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1083 emit_bytes (acfg, buf, code - buf);
1086 emit_byte (acfg, '\xe9');
1087 emit_symbol_diff (acfg, call_target, ".", -4);
1088 #elif defined(TARGET_ARM)
1092 if (acfg->thumb_mixed && cfg->compile_llvm) {
1093 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1094 fprintf (acfg->fp, "b %s\n", call_target);
1095 fprintf (acfg->fp, ".arm\n");
1101 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1103 emit_bytes (acfg, buf, code - buf);
1104 /* jump to method */
1105 if (acfg->use_bin_writer) {
1112 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1113 emit_bytes (acfg, buf, 4);
1115 if (acfg->thumb_mixed && cfg->compile_llvm)
1116 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1118 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1120 #elif defined(TARGET_POWERPC)
1123 g_assert (!acfg->use_bin_writer);
1125 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1126 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1128 g_assert_not_reached ();
1133 * arch_emit_static_rgctx_trampoline:
1135 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1136 * two GOT slots which contain the rgctx argument, and the method to jump to.
1137 * TRAMP_SIZE is set to the size of the emitted trampoline.
1138 * These kinds of trampolines cannot be enumerated statically, since there could
1139 * be one trampoline per method instantiation, so we emit the same code for all
1140 * trampolines, and parameterize them using two GOT slots.
1143 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1145 #if defined(TARGET_AMD64)
1146 #if defined(__default_codegen__)
1147 /* This should be exactly 13 bytes long */
1150 /* mov <OFFSET>(%rip), %r10 */
1151 emit_byte (acfg, '\x4d');
1152 emit_byte (acfg, '\x8b');
1153 emit_byte (acfg, '\x15');
1154 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1156 /* jmp *<offset>(%rip) */
1157 emit_byte (acfg, '\xff');
1158 emit_byte (acfg, '\x25');
1159 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1160 #elif defined(__native_client_codegen__)
1162 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1163 guint8 *code = buf_aligned;
1165 /* mov <OFFSET>(%rip), %r10d */
1166 emit_byte (acfg, '\x45');
1167 emit_byte (acfg, '\x8b');
1168 emit_byte (acfg, '\x15');
1169 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1171 /* mov <OFFSET>(%rip), %r11d */
1172 emit_byte (acfg, '\x45');
1173 emit_byte (acfg, '\x8b');
1174 emit_byte (acfg, '\x1d');
1175 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1178 amd64_jump_reg (code, AMD64_R11);
1179 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1181 emit_alignment (acfg, kNaClAlignment);
1182 *tramp_size = kNaClAlignment;
1183 #endif /*__native_client_codegen__*/
1185 #elif defined(TARGET_ARM)
1189 /* This should be exactly 24 bytes long */
1192 /* Load rgctx value */
1193 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1194 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1195 /* Load branch addr + branch */
1196 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1197 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1199 g_assert (code - buf == 16);
1202 emit_bytes (acfg, buf, code - buf);
1203 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1204 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1205 #elif defined(TARGET_POWERPC)
1212 g_assert (!acfg->use_bin_writer);
1215 * PPC has no ip relative addressing, so we need to compute the address
1216 * of the mscorlib got. That is slow and complex, so instead, we store it
1217 * in the second got slot of every aot image. The caller already computed
1218 * the address of its got and placed it into r30.
1220 img_writer_emit_unset_mode (acfg->w);
1221 /* Load mscorlib got address */
1222 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1224 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1225 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1226 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1227 /* Load target address */
1228 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1229 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1230 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1231 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1232 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1233 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1235 fprintf (acfg->fp, "mtctr 11\n");
1236 /* Branch to the target address */
1237 fprintf (acfg->fp, "bctr\n");
1239 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1240 *tramp_size = 11 * 4;
1242 *tramp_size = 9 * 4;
1245 #elif defined(TARGET_X86)
1249 /* Similar to the PPC code above */
1251 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1254 /* Load mscorlib got address */
1255 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1257 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1258 /* Branch to the target address */
1259 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1261 #ifdef __native_client_codegen__
1263 /* emit nops to next 32 byte alignment */
1264 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1265 while (code < (buf + a)) x86_nop(code);
1269 emit_bytes (acfg, buf, code - buf);
1271 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1272 g_assert (code - buf == *tramp_size);
1274 g_assert_not_reached ();
1279 * arch_emit_imt_thunk:
1281 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1282 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1283 * key is the IMT key, and ptr holds the address of a memory location holding
1284 * the address to branch to if the IMT arg matches the key. The array is
1285 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1287 * TRAMP_SIZE is set to the size of the emitted trampoline.
1290 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1292 #if defined(TARGET_AMD64)
1294 #if defined(__native_client_codegen__)
1299 guint8 *mov_buf_ptr = mov_buf;
1301 const int kSizeOfMove = 7;
1302 #if defined(__default_codegen__)
1303 code = buf = g_malloc (256);
1304 #elif defined(__native_client_codegen__)
1305 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1306 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1307 /* The RIP relative move below is emitted first */
1312 /* FIXME: Optimize this, i.e. use binary search etc. */
1313 /* Maybe move the body into a separate function (slower, but much smaller) */
1315 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1318 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1320 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1323 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1325 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1328 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1329 amd64_jump_code (code, labels [0]);
1332 mono_amd64_patch (labels [2], code);
1333 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1334 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1338 mono_amd64_patch (labels [1], code);
1339 x86_breakpoint (code);
1341 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1342 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1343 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1344 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1345 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1346 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1348 emit_bytes (acfg, buf, code - buf);
1350 *tramp_size = code - buf + kSizeOfMove;
1351 #if defined(__native_client_codegen__)
1352 /* The tramp will be padded to the next kNaClAlignment bundle. */
1353 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1356 #if defined(__default_codegen__)
1358 #elif defined(__native_client_codegen__)
1362 #elif defined(TARGET_X86)
1364 #ifdef __native_client_codegen__
1369 #if defined(__default_codegen__)
1370 code = buf = g_malloc (256);
1371 #elif defined(__native_client_codegen__)
1372 buf_alloc = g_malloc (256 + kNaClAlignment);
1373 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1376 /* Allocate a temporary stack slot */
1377 x86_push_reg (code, X86_EAX);
1379 x86_push_reg (code, X86_EAX);
1381 /* Load mscorlib got address */
1382 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1384 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1387 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1389 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1392 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1394 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1397 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1398 x86_jump_code (code, labels [0]);
1401 mono_x86_patch (labels [2], code);
1402 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1403 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1404 /* Save the target address to the temporary stack location */
1405 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1407 x86_pop_reg (code, X86_EAX);
1408 /* Jump to the target address */
1413 mono_x86_patch (labels [1], code);
1414 x86_breakpoint (code);
1416 #ifdef __native_client_codegen__
1418 /* emit nops to next 32 byte alignment */
1419 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1420 while (code < (buf + a)) x86_nop(code);
1423 emit_bytes (acfg, buf, code - buf);
1425 *tramp_size = code - buf;
1427 #if defined(__default_codegen__)
1429 #elif defined(__native_client_codegen__)
1433 #elif defined(TARGET_ARM)
1435 guint8 *code, *code2, *labels [16];
1439 /* The IMT method is in v5 */
1441 /* Need at least two free registers, plus a slot for storing the pc */
1442 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1444 /* Load the parameter from the GOT */
1445 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1446 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1449 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1450 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1452 ARM_B_COND (code, ARMCOND_EQ, 0);
1454 /* End-of-loop check */
1455 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1457 ARM_B_COND (code, ARMCOND_EQ, 0);
1460 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1463 arm_patch (labels [4], labels [1]);
1466 arm_patch (labels [2], code);
1467 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1468 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1469 /* Save it to the third stack slot */
1470 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1471 /* Restore the registers and branch */
1472 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1475 arm_patch (labels [3], code);
1480 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1482 emit_bytes (acfg, buf, code - buf);
1483 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1485 *tramp_size = code - buf + 4;
1486 #elif defined(TARGET_POWERPC)
1488 guint8 *code, *labels [16];
1492 /* Load the mscorlib got address */
1493 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1494 /* Load the parameter from the GOT */
1495 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1496 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1498 /* Load and check key */
1500 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1501 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1503 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1505 /* End-of-loop check */
1506 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1508 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1511 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1514 mono_ppc_patch (labels [4], labels [1]);
1517 mono_ppc_patch (labels [2], code);
1518 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1519 /* r11 now contains the value of the vtable slot */
1520 /* this is not a function descriptor on ppc64 */
1521 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1522 ppc_mtctr (code, ppc_r11);
1523 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1526 mono_ppc_patch (labels [3], code);
1530 *tramp_size = code - buf;
1532 emit_bytes (acfg, buf, code - buf);
1534 g_assert_not_reached ();
1539 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1541 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1542 /* Based on code generated by gcc */
1543 img_writer_emit_unset_mode (acfg->w);
1546 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1547 ".section .ctors,\"aw\",@progbits\n"
1551 ".section .opd,\"aw\"\n"
1554 ".long .%s,.TOC.@tocbase32\n"
1557 ".type .%s,@function\n"
1559 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1561 ".section .ctors,\"aw\",@progbits\n"
1565 ".section .opd,\"aw\"\n"
1568 ".long .%1$s,.TOC.@tocbase32\n"
1569 ".size %1$s,.-%1$s\n"
1571 ".type .%1$s,@function\n"
1573 ".%1$s:\n", symbol);
1584 "lis 3, .Lglobals@h\n"
1585 "ori 3, 3, .Lglobals@l\n"
1586 "bl .mono_aot_register_module\n"
1594 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1596 ".size .%s,.-.%s\n", symbol, symbol);
1599 ".size .%1$s,.-.%1$s\n", symbol);
1605 /* END OF ARCH SPECIFIC CODE */
1608 mono_get_field_token (MonoClassField *field)
1610 MonoClass *klass = field->parent;
1613 for (i = 0; i < klass->field.count; ++i) {
1614 if (field == &klass->fields [i])
1615 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1618 g_assert_not_reached ();
1623 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1627 //printf ("ENCODE: %d 0x%x.\n", value, value);
1630 * Same encoding as the one used in the metadata, extended to handle values
1631 * greater than 0x1fffffff.
1633 if ((value >= 0) && (value <= 127))
1635 else if ((value >= 0) && (value <= 16383)) {
1636 p [0] = 0x80 | (value >> 8);
1637 p [1] = value & 0xff;
1639 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1640 p [0] = (value >> 24) | 0xc0;
1641 p [1] = (value >> 16) & 0xff;
1642 p [2] = (value >> 8) & 0xff;
1643 p [3] = value & 0xff;
1648 p [1] = (value >> 24) & 0xff;
1649 p [2] = (value >> 16) & 0xff;
1650 p [3] = (value >> 8) & 0xff;
1651 p [4] = value & 0xff;
1659 stream_init (MonoDynamicStream *sh)
1662 sh->alloc_size = 4096;
1663 sh->data = g_malloc (4096);
1665 /* So offsets are > 0 */
1671 make_room_in_stream (MonoDynamicStream *stream, int size)
1673 if (size <= stream->alloc_size)
1676 while (stream->alloc_size <= size) {
1677 if (stream->alloc_size < 4096)
1678 stream->alloc_size = 4096;
1680 stream->alloc_size *= 2;
1683 stream->data = g_realloc (stream->data, stream->alloc_size);
1687 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1691 make_room_in_stream (stream, stream->index + len);
1692 memcpy (stream->data + stream->index, data, len);
1693 idx = stream->index;
1694 stream->index += len;
1701 * Add data to the binary blob inside the aot image. Returns the offset inside the
1702 * blob where the data was stored.
1705 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1707 if (acfg->blob.alloc_size == 0)
1708 stream_init (&acfg->blob);
1710 return add_stream_data (&acfg->blob, (char*)data, data_len);
1714 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1719 if (acfg->blob.alloc_size == 0)
1720 stream_init (&acfg->blob);
1722 count = acfg->blob.index % align;
1724 /* we assume the stream data will be aligned */
1726 add_stream_data (&acfg->blob, buf, 4 - count);
1728 return add_stream_data (&acfg->blob, (char*)data, data_len);
1732 * emit_offset_table:
1734 * Emit a table of increasing offsets in a compact form using differential encoding.
1735 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1736 * group size, the more compact the table becomes, but the slower it becomes to compute
1737 * a given entry. Returns the size of the table.
1740 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1742 gint32 current_offset;
1743 int i, buf_size, ngroups, index_entry_size;
1745 guint32 *index_offsets;
1747 ngroups = (noffsets + (group_size - 1)) / group_size;
1749 index_offsets = g_new0 (guint32, ngroups);
1751 buf_size = noffsets * 4;
1752 p = buf = g_malloc0 (buf_size);
1755 for (i = 0; i < noffsets; ++i) {
1756 //printf ("D: %d -> %d\n", i, offsets [i]);
1757 if ((i % group_size) == 0) {
1758 index_offsets [i / group_size] = p - buf;
1759 /* Emit the full value for these entries */
1760 encode_value (offsets [i], p, &p);
1762 /* The offsets are allowed to be non-increasing */
1763 //g_assert (offsets [i] >= current_offset);
1764 encode_value (offsets [i] - current_offset, p, &p);
1766 current_offset = offsets [i];
1769 if (ngroups && index_offsets [ngroups - 1] < 65000)
1770 index_entry_size = 2;
1772 index_entry_size = 4;
1774 /* Emit the header */
1775 emit_int32 (acfg, noffsets);
1776 emit_int32 (acfg, group_size);
1777 emit_int32 (acfg, ngroups);
1778 emit_int32 (acfg, index_entry_size);
1780 /* Emit the index */
1781 for (i = 0; i < ngroups; ++i) {
1782 if (index_entry_size == 2)
1783 emit_int16 (acfg, index_offsets [i]);
1785 emit_int32 (acfg, index_offsets [i]);
1789 emit_bytes (acfg, buf, p - buf);
1791 return (int)(p - buf) + (ngroups * 4);
1795 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1799 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1803 index = g_hash_table_size (cfg->image_hash);
1804 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1805 g_ptr_array_add (cfg->image_table, image);
1811 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1814 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1816 /* FIXME: Search referenced images as well */
1817 if (!acfg->typespec_classes) {
1818 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1819 for (i = 0; i < len; ++i) {
1820 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1823 for (i = 0; i < len; ++i) {
1824 if (acfg->typespec_classes [i] == klass)
1829 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1835 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1840 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1841 * standard metadata encoding.
1844 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1848 if (klass->generic_class) {
1850 g_assert (klass->type_token);
1852 /* Find a typespec for a class if possible */
1853 token = find_typespec_for_class (acfg, klass);
1855 encode_value (token, p, &p);
1856 encode_value (get_image_index (acfg, acfg->image), p, &p);
1858 MonoClass *gclass = klass->generic_class->container_class;
1859 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1862 /* Encode it ourselves */
1864 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1865 encode_value (MONO_TYPE_GENERICINST, p, &p);
1866 encode_klass_ref (acfg, gclass, p, &p);
1867 encode_value (inst->type_argc, p, &p);
1868 for (i = 0; i < inst->type_argc; ++i)
1869 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1871 } else if (klass->type_token) {
1872 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1873 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1874 encode_value (get_image_index (acfg, klass->image), p, &p);
1875 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1876 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1877 g_assert (container);
1880 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1881 encode_value (klass->byval_arg.type, p, &p);
1883 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1885 encode_value (container->is_method, p, &p);
1886 if (container->is_method)
1887 encode_method_ref (acfg, container->owner.method, p, &p);
1889 encode_klass_ref (acfg, container->owner.klass, p, &p);
1892 g_assert (klass->rank > 0);
1893 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1894 encode_value (get_image_index (acfg, klass->image), p, &p);
1895 encode_value (klass->rank, p, &p);
1896 encode_klass_ref (acfg, klass->element_class, p, &p);
1902 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1904 guint32 token = mono_get_field_token (field);
1907 encode_klass_ref (cfg, field->parent, p, &p);
1908 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1909 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1914 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1918 MonoGenericInst *inst;
1920 /* Encode the context */
1921 inst = context->class_inst;
1922 encode_value (inst ? 1 : 0, p, &p);
1924 encode_value (inst->type_argc, p, &p);
1925 for (i = 0; i < inst->type_argc; ++i)
1926 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1928 inst = context->method_inst;
1929 encode_value (inst ? 1 : 0, p, &p);
1931 encode_value (inst->type_argc, p, &p);
1932 for (i = 0; i < inst->type_argc; ++i)
1933 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1939 #define MAX_IMAGE_INDEX 250
1942 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1944 guint32 image_index = get_image_index (acfg, method->klass->image);
1945 guint32 token = method->token;
1946 MonoJumpInfoToken *ji;
1951 * The encoding for most methods is as follows:
1952 * - image index encoded as a leb128
1953 * - token index encoded as a leb128
1954 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1955 * types of method encodings.
1958 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1960 /* Mark methods which can't use aot trampolines because they need the further
1961 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1963 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1964 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1965 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1968 * Some wrapper methods are shared using their signature, encode their
1969 * stringified signature instead.
1970 * FIXME: Optimize disk usage
1973 if (method->wrapper_type) {
1974 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1975 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1976 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1977 name = mono_aot_wrapper_name (method);
1978 } else if (mono_marshal_method_from_wrapper (method) != method) {
1979 /* Direct wrapper, encode it normally */
1981 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1984 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1985 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1986 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1988 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1989 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1990 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1992 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1993 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1994 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
2000 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
2001 strcpy ((char*)p, name);
2002 p += strlen (name) + 1;
2004 } else if (method->wrapper_type) {
2005 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2007 encode_value (method->wrapper_type, p, &p);
2009 switch (method->wrapper_type) {
2010 case MONO_WRAPPER_REMOTING_INVOKE:
2011 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2012 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2015 m = mono_marshal_method_from_wrapper (method);
2017 encode_method_ref (acfg, m, p, &p);
2020 case MONO_WRAPPER_PROXY_ISINST:
2021 case MONO_WRAPPER_LDFLD:
2022 case MONO_WRAPPER_LDFLDA:
2023 case MONO_WRAPPER_STFLD:
2024 case MONO_WRAPPER_ISINST: {
2025 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2026 encode_klass_ref (acfg, proxy_class, p, &p);
2029 case MONO_WRAPPER_LDFLD_REMOTE:
2030 case MONO_WRAPPER_STFLD_REMOTE:
2032 case MONO_WRAPPER_ALLOC: {
2033 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2035 /* The GC name is saved once in MonoAotFileInfo */
2036 g_assert (info->alloc_type != -1);
2037 encode_value (info->alloc_type, p, &p);
2040 case MONO_WRAPPER_WRITE_BARRIER:
2042 case MONO_WRAPPER_STELEMREF: {
2043 MonoClass *klass = mono_marshal_get_wrapper_info (method);
2045 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
2049 case MONO_WRAPPER_UNKNOWN:
2050 if (strcmp (method->name, "FastMonitorEnter") == 0) {
2051 encode_value (MONO_AOT_WRAPPER_MONITOR_ENTER, p, &p);
2052 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2053 encode_value (MONO_AOT_WRAPPER_MONITOR_EXIT, p, &p);
2054 } else if (strcmp (method->name, "FastMonitorEnterV4") == 0) {
2055 encode_value (MONO_AOT_WRAPPER_MONITOR_ENTER_V4, p, &p);
2056 } else if (strcmp (method->name, "PtrToStructure") == 0) {
2057 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2058 encode_klass_ref (acfg, method->klass, p, &p);
2059 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2060 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2061 encode_klass_ref (acfg, method->klass, p, &p);
2063 g_assert_not_reached ();
2066 case MONO_WRAPPER_SYNCHRONIZED:
2067 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2068 case MONO_WRAPPER_RUNTIME_INVOKE: {
2071 m = mono_marshal_method_from_wrapper (method);
2073 g_assert (m != method);
2074 encode_method_ref (acfg, m, p, &p);
2077 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2078 if (!strcmp (method->name, "ElementAddr")) {
2079 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2082 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2083 encode_value (info->rank, p, &p);
2084 encode_value (info->elem_size, p, &p);
2086 g_assert_not_reached ();
2089 case MONO_WRAPPER_CASTCLASS:
2090 if (!strcmp (method->name, "__castclass_with_cache")) {
2091 encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
2092 } else if (!strcmp (method->name, "__isinst_with_cache")) {
2093 encode_value (MONO_AOT_WRAPPER_ISINST_WITH_CACHE, p, &p);
2095 g_assert_not_reached ();
2099 g_assert_not_reached ();
2101 } else if (mono_method_signature (method)->is_inflated) {
2103 * This is a generic method, find the original token which referenced it and
2105 * Obtain the token from information recorded by the JIT.
2107 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2109 image_index = get_image_index (acfg, ji->image);
2110 g_assert (image_index < MAX_IMAGE_INDEX);
2113 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2114 encode_value (image_index, p, &p);
2115 encode_value (token, p, &p);
2117 MonoMethod *declaring;
2118 MonoGenericContext *context = mono_method_get_context (method);
2120 g_assert (method->is_inflated);
2121 declaring = ((MonoMethodInflated*)method)->declaring;
2124 * This might be a non-generic method of a generic instance, which
2125 * doesn't have a token since the reference is generated by the JIT
2126 * like Nullable:Box/Unbox, or by generic sharing.
2129 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2130 /* Encode the klass */
2131 encode_klass_ref (acfg, method->klass, p, &p);
2132 /* Encode the method */
2133 image_index = get_image_index (acfg, method->klass->image);
2134 g_assert (image_index < MAX_IMAGE_INDEX);
2135 g_assert (declaring->token);
2136 token = declaring->token;
2137 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2138 encode_value (image_index, p, &p);
2139 encode_value (token, p, &p);
2140 encode_generic_context (acfg, context, p, &p);
2142 } else if (token == 0) {
2143 /* This might be a method of a constructed type like int[,].Set */
2144 /* Obtain the token from information recorded by the JIT */
2145 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2147 image_index = get_image_index (acfg, ji->image);
2148 g_assert (image_index < MAX_IMAGE_INDEX);
2151 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2152 encode_value (image_index, p, &p);
2153 encode_value (token, p, &p);
2156 g_assert (method->klass->rank);
2158 /* Encode directly */
2159 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2160 encode_klass_ref (acfg, method->klass, p, &p);
2161 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2162 encode_value (0, p, &p);
2163 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2164 encode_value (1, p, &p);
2165 else if (!strcmp (method->name, "Get"))
2166 encode_value (2, p, &p);
2167 else if (!strcmp (method->name, "Address"))
2168 encode_value (3, p, &p);
2169 else if (!strcmp (method->name, "Set"))
2170 encode_value (4, p, &p);
2172 g_assert_not_reached ();
2175 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2176 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2182 compare_patches (gconstpointer a, gconstpointer b)
2186 i = (*(MonoJumpInfo**)a)->ip.i;
2187 j = (*(MonoJumpInfo**)b)->ip.i;
2198 static G_GNUC_UNUSED char*
2199 patch_to_string (MonoJumpInfo *patch_info)
2203 str = g_string_new ("");
2205 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2207 switch (patch_info->type) {
2208 case MONO_PATCH_INFO_VTABLE:
2209 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2214 g_string_append_printf (str, ")");
2215 return g_string_free (str, FALSE);
2221 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2224 static inline gboolean
2225 is_plt_patch (MonoJumpInfo *patch_info)
2227 switch (patch_info->type) {
2228 case MONO_PATCH_INFO_METHOD:
2229 case MONO_PATCH_INFO_INTERNAL_METHOD:
2230 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2231 case MONO_PATCH_INFO_ICALL_ADDR:
2232 case MONO_PATCH_INFO_CLASS_INIT:
2233 case MONO_PATCH_INFO_RGCTX_FETCH:
2234 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2235 case MONO_PATCH_INFO_MONITOR_ENTER:
2236 case MONO_PATCH_INFO_MONITOR_EXIT:
2237 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2247 * Return the symbol identifying the plt entry PLT_OFFSET.
2250 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2254 * The Apple linker reorganizes object files, so it doesn't like branches to local
2255 * labels, since those have no relocations.
2257 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2259 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2266 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2268 static MonoPltEntry*
2269 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2273 if (!is_plt_patch (patch_info))
2276 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2278 // FIXME: This breaks the calculation of final_got_size
2279 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2281 * Allocate a separate PLT slot for each such patch, since some plt
2282 * entries will refer to the method itself, and some will refer to the
2289 MonoJumpInfo *new_ji;
2291 g_assert (!acfg->final_got_size);
2293 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2295 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2296 res->plt_offset = acfg->plt_offset;
2298 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2299 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2301 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2303 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2305 acfg->plt_offset ++;
2314 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2315 * JI could be found if it exists, otherwise allocates a new one.
2318 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2322 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2324 return got_offset - 1;
2326 got_offset = acfg->got_offset;
2327 acfg->got_offset ++;
2329 if (acfg->final_got_size)
2330 g_assert (got_offset < acfg->final_got_size);
2332 acfg->stats.got_slots ++;
2333 acfg->stats.got_slot_types [ji->type] ++;
2335 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2336 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2337 g_ptr_array_add (acfg->got_patches, ji);
2342 /* Add a method to the list of methods which need to be emitted */
2344 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2347 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2348 g_ptr_array_add (acfg->methods, method);
2349 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2350 acfg->nmethods = acfg->methods->len + 1;
2353 if (method->wrapper_type || extra)
2354 g_ptr_array_add (acfg->extra_methods, method);
2358 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2360 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2368 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2372 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2376 index = acfg->method_index;
2377 add_method_with_index (acfg, method, index, extra);
2379 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2381 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2383 acfg->method_index ++;
2389 add_method (MonoAotCompile *acfg, MonoMethod *method)
2391 return add_method_full (acfg, method, FALSE, 0);
2395 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2397 add_method_full (acfg, method, TRUE, 0);
2401 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2403 add_method_full (acfg, method, TRUE, depth);
2407 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2409 MonoAotCompile *acfg = user_data;
2410 MonoJitICallInfo *callinfo = value;
2411 MonoMethod *wrapper;
2417 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2418 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2421 add_method (acfg, wrapper);
2425 get_runtime_invoke_sig (MonoMethodSignature *sig)
2427 MonoMethodBuilder *mb;
2430 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2431 m = mono_mb_create_method (mb, sig, 16);
2432 return mono_marshal_get_runtime_invoke (m, FALSE);
2436 can_marshal_struct (MonoClass *klass)
2438 MonoClassField *field;
2439 gboolean can_marshal = TRUE;
2440 gpointer iter = NULL;
2442 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2445 /* Only allow a few field types to avoid asserts in the marshalling code */
2446 while ((field = mono_class_get_fields (klass, &iter))) {
2447 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2450 switch (field->type->type) {
2455 case MONO_TYPE_BOOLEAN:
2458 case MONO_TYPE_CHAR:
2466 case MONO_TYPE_STRING:
2468 case MONO_TYPE_VALUETYPE:
2469 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2470 can_marshal = FALSE;
2473 can_marshal = FALSE;
2479 /* Its hard to compute whenever these can be marshalled or not */
2480 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2487 add_wrappers (MonoAotCompile *acfg)
2489 MonoMethod *method, *m;
2491 MonoMethodSignature *sig, *csig;
2495 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2496 * so there is only one wrapper of a given type, or inlining their contents into their
2501 * FIXME: This depends on the fact that different wrappers have different
2505 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2507 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2508 gboolean skip = FALSE;
2510 method = mono_get_method (acfg->image, token, NULL);
2512 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2513 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2514 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2517 if (method->is_generic || method->klass->generic_container)
2520 /* Skip methods which can not be handled by get_runtime_invoke () */
2521 sig = mono_method_signature (method);
2524 if ((sig->ret->type == MONO_TYPE_PTR) ||
2525 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2528 for (j = 0; j < sig->param_count; j++) {
2529 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2533 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2534 if (!method->klass->contextbound) {
2535 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2536 gboolean has_nullable = FALSE;
2538 for (j = 0; j < sig->param_count; j++) {
2539 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2540 has_nullable = TRUE;
2543 if (info && !has_nullable) {
2544 /* Supported by the dynamic runtime-invoke wrapper */
2552 //printf ("%s\n", mono_method_full_name (method, TRUE));
2553 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2557 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2558 #ifdef MONO_ARCH_HAVE_TLS_GET
2559 MonoMethodDesc *desc;
2560 MonoMethod *orig_method;
2564 /* Runtime invoke wrappers */
2566 /* void runtime-invoke () [.cctor] */
2567 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2568 csig->ret = &mono_defaults.void_class->byval_arg;
2569 add_method (acfg, get_runtime_invoke_sig (csig));
2571 /* void runtime-invoke () [Finalize] */
2572 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2574 csig->ret = &mono_defaults.void_class->byval_arg;
2575 add_method (acfg, get_runtime_invoke_sig (csig));
2577 /* void runtime-invoke (string) [exception ctor] */
2578 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2580 csig->ret = &mono_defaults.void_class->byval_arg;
2581 csig->params [0] = &mono_defaults.string_class->byval_arg;
2582 add_method (acfg, get_runtime_invoke_sig (csig));
2584 /* void runtime-invoke (string, string) [exception ctor] */
2585 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2587 csig->ret = &mono_defaults.void_class->byval_arg;
2588 csig->params [0] = &mono_defaults.string_class->byval_arg;
2589 csig->params [1] = &mono_defaults.string_class->byval_arg;
2590 add_method (acfg, get_runtime_invoke_sig (csig));
2592 /* string runtime-invoke () [Exception.ToString ()] */
2593 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2595 csig->ret = &mono_defaults.string_class->byval_arg;
2596 add_method (acfg, get_runtime_invoke_sig (csig));
2598 /* void runtime-invoke (string, Exception) [exception ctor] */
2599 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2601 csig->ret = &mono_defaults.void_class->byval_arg;
2602 csig->params [0] = &mono_defaults.string_class->byval_arg;
2603 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2604 add_method (acfg, get_runtime_invoke_sig (csig));
2606 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2607 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2609 csig->ret = &(mono_class_from_name (
2610 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2611 csig->params [0] = &mono_defaults.string_class->byval_arg;
2612 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2613 add_method (acfg, get_runtime_invoke_sig (csig));
2615 /* runtime-invoke used by finalizers */
2616 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2618 /* This is used by mono_runtime_capture_context () */
2619 method = mono_get_context_capture_method ();
2621 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2623 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2624 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2627 /* JIT icall wrappers */
2628 /* FIXME: locking */
2629 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2632 add_method (acfg, mono_marshal_get_stelemref ());
2634 #ifdef MONO_ARCH_HAVE_TLS_GET
2635 /* Managed Allocators */
2636 nallocators = mono_gc_get_managed_allocator_types ();
2637 for (i = 0; i < nallocators; ++i) {
2638 m = mono_gc_get_managed_allocator_by_type (i);
2640 add_method (acfg, m);
2643 /* Monitor Enter/Exit */
2644 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2645 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2646 g_assert (orig_method);
2647 mono_method_desc_free (desc);
2648 method = mono_monitor_get_fast_path (orig_method);
2650 add_method (acfg, method);
2652 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2653 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2654 g_assert (orig_method);
2655 mono_method_desc_free (desc);
2656 method = mono_monitor_get_fast_path (orig_method);
2658 add_method (acfg, method);
2661 /* Stelemref wrappers */
2662 /* There is only a constant number of these, iterating over all types should handle them all */
2663 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2666 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2667 klass = mono_class_get (acfg->image, token);
2669 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2671 mono_loader_clear_error ();
2674 /* castclass_with_check wrapper */
2675 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2676 /* isinst_with_check wrapper */
2677 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2679 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2681 MonoMethodDesc *desc;
2684 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2685 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2686 mono_method_desc_free (desc);
2688 m = mono_monitor_get_fast_path (m);
2689 add_method (acfg, m);
2696 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2697 * we use the original method instead at runtime.
2698 * Since full-aot doesn't support remoting, this is not a problem.
2701 /* remoting-invoke wrappers */
2702 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2703 MonoMethodSignature *sig;
2705 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2706 method = mono_get_method (acfg->image, token, NULL);
2708 sig = mono_method_signature (method);
2710 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2711 m = mono_marshal_get_remoting_invoke_with_check (method);
2713 add_method (acfg, m);
2718 /* delegate-invoke wrappers */
2719 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2722 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2723 klass = mono_class_get (acfg->image, token);
2726 mono_loader_clear_error ();
2730 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2731 method = mono_get_delegate_invoke (klass);
2733 m = mono_marshal_get_delegate_invoke (method, NULL);
2735 add_method (acfg, m);
2737 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2738 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2740 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2741 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2745 /* Synchronized wrappers */
2746 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2747 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2748 method = mono_get_method (acfg->image, token, NULL);
2750 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2751 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2754 /* pinvoke wrappers */
2755 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2757 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2759 method = mono_get_method (acfg->image, token, NULL);
2761 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2762 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2763 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2767 /* native-to-managed wrappers */
2768 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2770 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2771 MonoCustomAttrInfo *cattr;
2774 method = mono_get_method (acfg->image, token, NULL);
2777 * Only generate native-to-managed wrappers for methods which have an
2778 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2779 * name to avoid defining a new assembly to contain it.
2781 cattr = mono_custom_attrs_from_method (method);
2784 for (j = 0; j < cattr->num_attrs; ++j)
2785 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2787 if (j < cattr->num_attrs) {
2788 MonoCustomAttrEntry *e = &cattr->attrs [j];
2789 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2790 const char *p = (const char*)e->data;
2796 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2798 g_assert (sig->param_count == 1);
2799 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2802 * Decode the cattr manually since we can't create objects
2803 * during aot compilation.
2809 /* From load_cattr_value () in reflection.c */
2810 slen = mono_metadata_decode_value (p, &p);
2811 n = g_memdup (p, slen + 1);
2813 t = mono_reflection_type_from_name (n, acfg->image);
2817 klass = mono_class_from_mono_type (t);
2818 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2820 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2824 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2825 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2826 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2830 /* StructureToPtr/PtrToStructure wrappers */
2831 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2834 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2835 klass = mono_class_get (acfg->image, token);
2838 mono_loader_clear_error ();
2842 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2843 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2844 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2850 has_type_vars (MonoClass *klass)
2852 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2855 return has_type_vars (klass->element_class);
2856 if (klass->generic_class) {
2857 MonoGenericContext *context = &klass->generic_class->context;
2858 if (context->class_inst) {
2861 for (i = 0; i < context->class_inst->type_argc; ++i)
2862 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2870 method_has_type_vars (MonoMethod *method)
2872 if (has_type_vars (method->klass))
2875 if (method->is_inflated) {
2876 MonoGenericContext *context = mono_method_get_context (method);
2877 if (context->method_inst) {
2880 for (i = 0; i < context->method_inst->type_argc; ++i)
2881 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2888 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2891 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2893 /* This might lead to a huge code blowup so only do it if neccesary */
2894 if (!acfg->aot_opts.full_aot && !force)
2897 add_generic_class_with_depth (acfg, klass, 0);
2901 check_type_depth (MonoType *t, int depth)
2909 case MONO_TYPE_GENERICINST: {
2910 MonoGenericClass *gklass = t->data.generic_class;
2911 MonoGenericInst *ginst = gklass->context.class_inst;
2914 for (i = 0; i < ginst->type_argc; ++i) {
2915 if (check_type_depth (ginst->type_argv [i], depth + 1))
2929 * add_generic_class:
2931 * Add all methods of a generic class.
2934 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2939 mono_class_init (klass);
2941 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2944 if (has_type_vars (klass))
2947 if (!klass->generic_class && !klass->rank)
2950 if (check_type_depth (&klass->byval_arg, 0))
2954 while ((method = mono_class_get_methods (klass, &iter))) {
2955 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2959 if (method->is_generic)
2964 * FIXME: Instances which are referenced by these methods are not added,
2965 * for example Array.Resize<int> for List<int>.Add ().
2967 add_extra_method_with_depth (acfg, method, depth + 1);
2970 if (klass->delegate) {
2971 method = mono_get_delegate_invoke (klass);
2973 method = mono_marshal_get_delegate_invoke (method, NULL);
2975 add_method (acfg, method);
2979 * For ICollection<T>, add instances of the helper methods
2980 * in Array, since a T[] could be cast to ICollection<T>.
2982 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2983 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2984 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2985 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2989 if (!strcmp (klass->name, "IEnumerator`1"))
2990 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2992 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2994 /* Add the T[]/InternalEnumerator class */
2995 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2999 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3000 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3004 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3005 add_generic_class (acfg, nclass, FALSE);
3009 while ((method = mono_class_get_methods (array_class, &iter))) {
3010 if (strstr (method->name, name_prefix)) {
3011 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3012 add_extra_method_with_depth (acfg, m, depth);
3016 g_free (name_prefix);
3019 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3020 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3021 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3022 MonoClass *icomparable, *gcomparer;
3023 MonoGenericContext ctx;
3024 MonoType *args [16];
3026 memset (&ctx, 0, sizeof (ctx));
3028 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3029 g_assert (icomparable);
3030 args [0] = &tclass->byval_arg;
3031 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3033 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3034 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3035 g_assert (gcomparer);
3036 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3040 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3041 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3042 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3043 MonoClass *iface, *gcomparer;
3044 MonoGenericContext ctx;
3045 MonoType *args [16];
3047 memset (&ctx, 0, sizeof (ctx));
3049 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3051 args [0] = &tclass->byval_arg;
3052 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3054 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3055 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3056 g_assert (gcomparer);
3057 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3063 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3066 MonoGenericContext ctx;
3067 MonoType *args [16];
3069 memset (&ctx, 0, sizeof (ctx));
3071 for (i = 0; i < ninsts; ++i) {
3072 args [0] = insts [i];
3073 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3074 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3079 * add_generic_instances:
3081 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3084 add_generic_instances (MonoAotCompile *acfg)
3089 MonoMethodHeader *header;
3090 MonoMethodSignature *sig;
3091 MonoGenericContext *context;
3093 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3094 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3095 method = mono_get_method (acfg->image, token, NULL);
3100 if (method->klass->image != acfg->image)
3103 context = mono_method_get_context (method);
3105 if (context && ((context->class_inst && context->class_inst->is_open)))
3109 * For open methods, create an instantiation which can be passed to the JIT.
3110 * FIXME: Handle class_inst as well.
3112 if (context && context->method_inst && context->method_inst->is_open) {
3113 MonoGenericContext shared_context;
3114 MonoGenericInst *inst;
3115 MonoType **type_argv;
3117 MonoMethod *declaring_method;
3118 gboolean supported = TRUE;
3120 /* Check that the context doesn't contain open constructed types */
3121 if (context->class_inst) {
3122 inst = context->class_inst;
3123 for (i = 0; i < inst->type_argc; ++i) {
3124 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)
3126 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3130 if (context->method_inst) {
3131 inst = context->method_inst;
3132 for (i = 0; i < inst->type_argc; ++i) {
3133 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)
3135 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3143 memset (&shared_context, 0, sizeof (MonoGenericContext));
3145 inst = context->class_inst;
3147 type_argv = g_new0 (MonoType*, inst->type_argc);
3148 for (i = 0; i < inst->type_argc; ++i) {
3149 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)
3150 type_argv [i] = &mono_defaults.object_class->byval_arg;
3152 type_argv [i] = inst->type_argv [i];
3155 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3159 inst = context->method_inst;
3161 type_argv = g_new0 (MonoType*, inst->type_argc);
3162 for (i = 0; i < inst->type_argc; ++i) {
3163 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)
3164 type_argv [i] = &mono_defaults.object_class->byval_arg;
3166 type_argv [i] = inst->type_argv [i];
3169 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3173 if (method->is_generic || method->klass->generic_container)
3174 declaring_method = method;
3176 declaring_method = mono_method_get_declaring_generic_method (method);
3178 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3182 * If the method is fully sharable, it was already added in place of its
3183 * generic definition.
3185 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3189 * FIXME: Partially shared methods are not shared here, so we end up with
3190 * many identical methods.
3192 add_extra_method (acfg, method);
3195 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3198 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3200 klass = mono_class_get (acfg->image, token);
3201 if (!klass || klass->rank) {
3202 mono_loader_clear_error ();
3206 add_generic_class (acfg, klass, FALSE);
3209 /* Add types of args/locals */
3210 for (i = 0; i < acfg->methods->len; ++i) {
3213 method = g_ptr_array_index (acfg->methods, i);
3215 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3217 sig = mono_method_signature (method);
3220 for (j = 0; j < sig->param_count; ++j)
3221 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3222 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3225 header = mono_method_get_header (method);
3228 for (j = 0; j < header->num_locals; ++j)
3229 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3230 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3234 if (acfg->image == mono_defaults.corlib) {
3236 MonoType *insts [256];
3239 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3240 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3241 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3242 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3243 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3244 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3245 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3246 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3247 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3248 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3249 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3250 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3252 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3253 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3255 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3256 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3258 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3260 /* Add instances of the array generic interfaces for primitive types */
3261 /* This will add instances of the InternalArray_ helper methods in Array too */
3262 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3264 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3265 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3267 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3268 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3270 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3273 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3274 * used for all instances of GetGenericValueImpl by the AOT runtime.
3277 MonoGenericContext ctx;
3278 MonoType *args [16];
3279 MonoMethod *get_method;
3280 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3282 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3285 memset (&ctx, 0, sizeof (ctx));
3286 args [0] = &mono_defaults.object_class->byval_arg;
3287 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3288 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3292 /* Same for CompareExchange<T> */
3294 MonoGenericContext ctx;
3295 MonoType *args [16];
3296 MonoMethod *cas_method;
3297 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3298 gpointer iter = NULL;
3300 while ((cas_method = mono_class_get_methods (interlocked_klass, &iter))) {
3301 if (!strcmp (cas_method->name, "CompareExchange") && cas_method->is_generic) {
3302 memset (&ctx, 0, sizeof (ctx));
3303 args [0] = &mono_defaults.object_class->byval_arg;
3304 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3305 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (cas_method, &ctx), TRUE, TRUE));
3313 * is_direct_callable:
3315 * Return whenever the method identified by JI is directly callable without
3316 * going through the PLT.
3319 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3321 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3322 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3324 gboolean direct_callable = TRUE;
3326 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3327 direct_callable = FALSE;
3328 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3329 // FIXME: Maybe call the wrapper directly ?
3330 direct_callable = FALSE;
3332 if (direct_callable)
3341 * emit_and_reloc_code:
3343 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3344 * is true, calls are made through the GOT too. This is used for emitting trampolines
3345 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3346 * since trampolines are needed to make PTL work.
3349 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3351 int i, pindex, start_index, method_index;
3353 MonoJumpInfo *patch_info;
3354 MonoMethodHeader *header;
3355 gboolean skip, direct_call;
3357 char direct_call_target [1024];
3360 header = mono_method_get_header (method);
3362 method_index = get_method_index (acfg, method);
3365 /* Collect and sort relocations */
3366 patches = g_ptr_array_new ();
3367 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3368 g_ptr_array_add (patches, patch_info);
3369 g_ptr_array_sort (patches, compare_patches);
3372 for (i = 0; i < code_len; i++) {
3374 for (pindex = start_index; pindex < patches->len; ++pindex) {
3375 patch_info = g_ptr_array_index (patches, pindex);
3376 if (patch_info->ip.i >= i)
3380 #ifdef MONO_ARCH_AOT_SUPPORTED
3382 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3383 start_index = pindex;
3385 switch (patch_info->type) {
3386 case MONO_PATCH_INFO_NONE:
3388 case MONO_PATCH_INFO_GOT_OFFSET: {
3391 arch_emit_got_offset (acfg, code + i, &code_size);
3394 patch_info->type = MONO_PATCH_INFO_NONE;
3399 * If this patch is a call, try emitting a direct call instead of
3400 * through a PLT entry. This is possible if the called method is in
3401 * the same assembly and requires no initialization.
3403 direct_call = FALSE;
3404 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3405 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3406 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3407 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3409 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3410 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3411 patch_info->type = MONO_PATCH_INFO_NONE;
3412 acfg->stats.direct_calls ++;
3415 acfg->stats.all_calls ++;
3418 if (!got_only && !direct_call) {
3419 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3421 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3423 sprintf (direct_call_target, "%s", plt_entry->symbol);
3425 /* Nullify the patch */
3426 patch_info->type = MONO_PATCH_INFO_NONE;
3427 plt_entry->jit_used = TRUE;
3434 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3439 got_slot = get_got_offset (acfg, patch_info);
3441 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3448 #endif /* MONO_ARCH_AOT_SUPPORTED */
3451 /* Find next patch */
3453 for (pindex = start_index; pindex < patches->len; ++pindex) {
3454 patch_info = g_ptr_array_index (patches, pindex);
3455 if (patch_info->ip.i >= i)
3459 /* Try to emit multiple bytes at once */
3460 if (pindex < patches->len && patch_info->ip.i > i) {
3461 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3462 i = patch_info->ip.i - 1;
3464 emit_bytes (acfg, code + i, 1);
3473 * Modify SYMBOL so it only includes characters permissible in symbols.
3476 sanitize_symbol (char *symbol)
3478 int i, len = strlen (symbol);
3480 for (i = 0; i < len; ++i)
3481 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3486 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3488 char *name1, *name2, *cached;
3489 int i, j, len, count;
3491 name1 = mono_method_full_name (method, TRUE);
3492 len = strlen (name1);
3493 name2 = malloc (strlen (prefix) + len + 16);
3494 memcpy (name2, prefix, strlen (prefix));
3495 j = strlen (prefix);
3496 for (i = 0; i < len; ++i) {
3497 if (isalnum (name1 [i])) {
3498 name2 [j ++] = name1 [i];
3499 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3501 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3504 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3513 while (g_hash_table_lookup (cache, name2)) {
3514 sprintf (name2 + j, "_%d", count);
3518 cached = g_strdup (name2);
3519 g_hash_table_insert (cache, cached, cached);
3525 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3530 char *debug_sym = NULL;
3532 int func_alignment = AOT_FUNC_ALIGNMENT;
3533 MonoMethodHeader *header;
3535 method = cfg->orig_method;
3536 code = cfg->native_code;
3537 header = cfg->header;
3539 method_index = get_method_index (acfg, method);
3541 /* Make the labels local */
3542 sprintf (symbol, "%s", cfg->asm_symbol);
3544 emit_section_change (acfg, ".text", 0);
3545 emit_alignment (acfg, func_alignment);
3546 emit_label (acfg, symbol);
3548 if (acfg->aot_opts.write_symbols) {
3550 * Write a C style symbol for every method, this has two uses:
3551 * - it works on platforms where the dwarf debugging info is not
3553 * - it allows the setting of breakpoints of aot-ed methods.
3555 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3557 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3558 if (acfg->need_no_dead_strip)
3559 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3560 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3561 emit_label (acfg, debug_sym);
3564 if (cfg->verbose_level > 0)
3565 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3567 acfg->stats.code_size += cfg->code_len;
3569 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3571 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3575 if (acfg->aot_opts.write_symbols) {
3576 emit_symbol_size (acfg, debug_sym, ".");
3580 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3581 emit_label (acfg, symbol);
3587 * Encode PATCH_INFO into its disk representation.
3590 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3594 switch (patch_info->type) {
3595 case MONO_PATCH_INFO_NONE:
3597 case MONO_PATCH_INFO_IMAGE:
3598 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3600 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3601 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3602 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3604 case MONO_PATCH_INFO_METHOD_REL:
3605 encode_value ((gint)patch_info->data.offset, p, &p);
3607 case MONO_PATCH_INFO_SWITCH: {
3608 gpointer *table = (gpointer *)patch_info->data.table->table;
3611 encode_value (patch_info->data.table->table_size, p, &p);
3612 for (k = 0; k < patch_info->data.table->table_size; k++)
3613 encode_value ((int)(gssize)table [k], p, &p);
3616 case MONO_PATCH_INFO_METHODCONST:
3617 case MONO_PATCH_INFO_METHOD:
3618 case MONO_PATCH_INFO_METHOD_JUMP:
3619 case MONO_PATCH_INFO_ICALL_ADDR:
3620 case MONO_PATCH_INFO_METHOD_RGCTX:
3621 encode_method_ref (acfg, patch_info->data.method, p, &p);
3623 case MONO_PATCH_INFO_INTERNAL_METHOD:
3624 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3625 guint32 len = strlen (patch_info->data.name);
3627 encode_value (len, p, &p);
3629 memcpy (p, patch_info->data.name, len);
3634 case MONO_PATCH_INFO_LDSTR: {
3635 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3636 guint32 token = patch_info->data.token->token;
3637 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3638 encode_value (image_index, p, &p);
3639 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3642 case MONO_PATCH_INFO_RVA:
3643 case MONO_PATCH_INFO_DECLSEC:
3644 case MONO_PATCH_INFO_LDTOKEN:
3645 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3646 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3647 encode_value (patch_info->data.token->token, p, &p);
3648 encode_value (patch_info->data.token->has_context, p, &p);
3649 if (patch_info->data.token->has_context)
3650 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3652 case MONO_PATCH_INFO_EXC_NAME: {
3653 MonoClass *ex_class;
3656 mono_class_from_name (mono_defaults.exception_class->image,
3657 "System", patch_info->data.target);
3658 g_assert (ex_class);
3659 encode_klass_ref (acfg, ex_class, p, &p);
3662 case MONO_PATCH_INFO_R4:
3663 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3665 case MONO_PATCH_INFO_R8:
3666 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3667 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3669 case MONO_PATCH_INFO_VTABLE:
3670 case MONO_PATCH_INFO_CLASS:
3671 case MONO_PATCH_INFO_IID:
3672 case MONO_PATCH_INFO_ADJUSTED_IID:
3673 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3675 case MONO_PATCH_INFO_CLASS_INIT:
3676 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3677 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3679 case MONO_PATCH_INFO_FIELD:
3680 case MONO_PATCH_INFO_SFLDA:
3681 encode_field_info (acfg, patch_info->data.field, p, &p);
3683 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3685 case MONO_PATCH_INFO_RGCTX_FETCH: {
3686 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3688 encode_method_ref (acfg, entry->method, p, &p);
3689 encode_value (entry->in_mrgctx, p, &p);
3690 encode_value (entry->info_type, p, &p);
3691 encode_value (entry->data->type, p, &p);
3692 encode_patch (acfg, entry->data, p, &p);
3695 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3696 case MONO_PATCH_INFO_MONITOR_ENTER:
3697 case MONO_PATCH_INFO_MONITOR_EXIT:
3698 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3700 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3701 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3702 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3705 g_warning ("unable to handle jump info %d", patch_info->type);
3706 g_assert_not_reached ();
3713 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3716 guint32 pindex, offset;
3717 MonoJumpInfo *patch_info;
3719 encode_value (n_patches, p, &p);
3721 for (pindex = 0; pindex < patches->len; ++pindex) {
3722 patch_info = g_ptr_array_index (patches, pindex);
3724 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3728 offset = get_got_offset (acfg, patch_info);
3729 encode_value (offset, p, &p);
3736 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3740 int pindex, buf_size, n_patches;
3742 MonoJumpInfo *patch_info;
3743 MonoMethodHeader *header;
3744 guint32 method_index;
3746 guint32 first_got_offset;
3748 method = cfg->orig_method;
3749 header = mono_method_get_header (method);
3751 method_index = get_method_index (acfg, method);
3753 /* Sort relocations */
3754 patches = g_ptr_array_new ();
3755 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3756 g_ptr_array_add (patches, patch_info);
3757 g_ptr_array_sort (patches, compare_patches);
3759 first_got_offset = acfg->cfgs [method_index]->got_offset;
3761 /**********************/
3762 /* Encode method info */
3763 /**********************/
3765 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3766 p = buf = g_malloc (buf_size);
3768 if (mono_class_get_cctor (method->klass))
3769 encode_klass_ref (acfg, method->klass, p, &p);
3771 /* Not needed when loading the method */
3772 encode_value (0, p, &p);
3775 if (cfg->opt & MONO_OPT_SHARED) {
3776 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3777 for (l = cfg->ldstr_list; l; l = l->next) {
3778 encode_value ((long)l->data, p, &p);
3782 /* Used only in shared mode */
3783 g_assert (!cfg->ldstr_list);
3786 for (pindex = 0; pindex < patches->len; ++pindex) {
3787 patch_info = g_ptr_array_index (patches, pindex);
3789 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3790 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3791 patch_info->type = MONO_PATCH_INFO_NONE;
3796 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3797 /* Stored in a GOT slot initialized at module load time */
3798 patch_info->type = MONO_PATCH_INFO_NONE;
3802 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3803 /* Stored in a GOT slot initialized at module load time */
3804 patch_info->type = MONO_PATCH_INFO_NONE;
3808 if (is_plt_patch (patch_info)) {
3809 /* Calls are made through the PLT */
3810 patch_info->type = MONO_PATCH_INFO_NONE;
3818 g_assert (cfg->has_got_slots);
3820 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3822 acfg->stats.info_size += p - buf;
3824 g_assert (p - buf < buf_size);
3826 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3831 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3833 guint32 cache_index;
3836 /* Reuse the unwind module to canonize and store unwind info entries */
3837 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3839 /* Use +/- 1 to distinguish 0s from missing entries */
3840 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3848 * It would be easier to use assembler symbols, but the caller needs an
3851 offset = acfg->unwind_info_offset;
3852 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3853 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3856 encode_value (encoded_len, p, &p);
3858 acfg->unwind_info_offset += encoded_len + (p - buf);
3864 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3867 int i, k, buf_size, method_index;
3868 guint32 debug_info_size;
3870 MonoMethodHeader *header;
3871 guint8 *p, *buf, *debug_info;
3872 MonoJitInfo *jinfo = cfg->jit_info;
3874 gboolean use_unwind_ops = FALSE;
3875 MonoSeqPointInfo *seq_points;
3877 method = cfg->orig_method;
3878 code = cfg->native_code;
3879 header = cfg->header;
3881 method_index = get_method_index (acfg, method);
3883 if (!acfg->aot_opts.nodebug) {
3884 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3887 debug_info_size = 0;
3890 seq_points = cfg->seq_point_info;
3892 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3893 p = buf = g_malloc (buf_size);
3895 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3896 use_unwind_ops = cfg->unwind_ops != NULL;
3899 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0);
3901 encode_value (flags, p, &p);
3903 if (use_unwind_ops) {
3904 guint32 encoded_len;
3908 * This is a duplicate of the data in the .debug_frame section, but that
3909 * section cannot be accessed using the dl interface.
3911 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3912 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3915 encode_value (jinfo->used_regs, p, &p);
3918 /*Encode the number of holes before the number of clauses to make decoding easier*/
3919 if (jinfo->has_try_block_holes) {
3920 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3921 encode_value (table->num_holes, p, &p);
3924 /* Exception table */
3925 if (cfg->compile_llvm) {
3927 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3928 * since the information is only available to llc. Instead, we let llc save the data
3929 * into the LSDA, and read it from there at runtime.
3931 /* The assembly might be CIL stripped so emit the data ourselves */
3932 if (header->num_clauses)
3933 encode_value (header->num_clauses, p, &p);
3935 for (k = 0; k < header->num_clauses; ++k) {
3936 MonoExceptionClause *clause;
3938 clause = &header->clauses [k];
3940 encode_value (clause->flags, p, &p);
3941 if (clause->data.catch_class) {
3942 encode_value (1, p, &p);
3943 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3945 encode_value (0, p, &p);
3948 /* Emit a list of nesting clauses */
3949 for (i = 0; i < header->num_clauses; ++i) {
3951 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3953 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3955 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3956 encode_value (i, p, &p);
3958 encode_value (-1, p, &p);
3961 if (jinfo->num_clauses)
3962 encode_value (jinfo->num_clauses, p, &p);
3964 for (k = 0; k < jinfo->num_clauses; ++k) {
3965 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3967 encode_value (ei->flags, p, &p);
3968 encode_value (ei->exvar_offset, p, &p);
3970 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3971 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3973 if (ei->data.catch_class) {
3974 encode_value (1, p, &p);
3975 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3977 encode_value (0, p, &p);
3981 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3982 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3983 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3987 if (jinfo->has_generic_jit_info) {
3988 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3990 if (!cfg->compile_llvm) {
3991 encode_value (gi->has_this ? 1 : 0, p, &p);
3992 encode_value (gi->this_reg, p, &p);
3993 encode_value (gi->this_offset, p, &p);
3997 * Need to encode jinfo->method too, since it is not equal to 'method'
3998 * when using generic sharing.
4000 encode_method_ref (acfg, jinfo->method, p, &p);
4003 if (jinfo->has_try_block_holes) {
4004 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4005 for (i = 0; i < table->num_holes; ++i) {
4006 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4007 encode_value (hole->clause, p, &p);
4008 encode_value (hole->length, p, &p);
4009 encode_value (hole->offset, p, &p);
4014 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4016 encode_value (seq_points->len, p, &p);
4017 last_il_offset = last_native_offset = 0;
4018 for (i = 0; i < seq_points->len; ++i) {
4019 SeqPoint *sp = &seq_points->seq_points [i];
4020 il_offset = sp->il_offset;
4021 native_offset = sp->native_offset;
4022 encode_value (il_offset - last_il_offset, p, &p);
4023 encode_value (native_offset - last_native_offset, p, &p);
4024 last_il_offset = il_offset;
4025 last_native_offset = native_offset;
4027 encode_value (sp->next_len, p, &p);
4028 for (j = 0; j < sp->next_len; ++j)
4029 encode_value (sp->next [j], p, &p);
4033 g_assert (debug_info_size < buf_size);
4035 encode_value (debug_info_size, p, &p);
4036 if (debug_info_size) {
4037 memcpy (p, debug_info, debug_info_size);
4038 p += debug_info_size;
4039 g_free (debug_info);
4044 encode_value (cfg->gc_map_size, p, &p);
4045 /* The GC map requires 4 bytes of alignment */
4046 while ((gsize)p % 4)
4048 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4049 p += cfg->gc_map_size;
4052 acfg->stats.ex_info_size += p - buf;
4054 g_assert (p - buf < buf_size);
4057 /* The GC Map requires 4 byte alignment */
4058 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4063 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4065 MonoClass *klass = mono_class_get (acfg->image, token);
4067 int i, buf_size, res;
4068 gboolean no_special_static, cant_encode;
4069 gpointer iter = NULL;
4072 mono_loader_clear_error ();
4076 p = buf = g_malloc (buf_size);
4078 /* Mark as unusable */
4079 encode_value (-1, p, &p);
4081 res = add_to_blob (acfg, buf, p - buf);
4087 buf_size = 10240 + (klass->vtable_size * 16);
4088 p = buf = g_malloc (buf_size);
4092 mono_class_init (klass);
4094 mono_class_get_nested_types (klass, &iter);
4095 g_assert (klass->nested_classes_inited);
4097 mono_class_setup_vtable (klass);
4100 * Emit all the information which is required for creating vtables so
4101 * the runtime does not need to create the MonoMethod structures which
4102 * take up a lot of space.
4105 no_special_static = !mono_class_has_special_static_fields (klass);
4107 /* Check whenever we have enough info to encode the vtable */
4108 cant_encode = FALSE;
4109 for (i = 0; i < klass->vtable_size; ++i) {
4110 MonoMethod *cm = klass->vtable [i];
4112 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4116 if (klass->generic_container || cant_encode) {
4117 encode_value (-1, p, &p);
4119 encode_value (klass->vtable_size, p, &p);
4120 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);
4121 if (klass->has_cctor)
4122 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4123 if (klass->has_finalize)
4124 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4126 encode_value (klass->instance_size, p, &p);
4127 encode_value (mono_class_data_size (klass), p, &p);
4128 encode_value (klass->packing_size, p, &p);
4129 encode_value (klass->min_align, p, &p);
4131 for (i = 0; i < klass->vtable_size; ++i) {
4132 MonoMethod *cm = klass->vtable [i];
4135 encode_method_ref (acfg, cm, p, &p);
4137 encode_value (0, p, &p);
4141 acfg->stats.class_info_size += p - buf;
4143 g_assert (p - buf < buf_size);
4144 res = add_to_blob (acfg, buf, p - buf);
4151 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4153 char *debug_sym = NULL;
4156 case MONO_PATCH_INFO_METHOD:
4157 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4159 case MONO_PATCH_INFO_INTERNAL_METHOD:
4160 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4162 case MONO_PATCH_INFO_CLASS_INIT:
4163 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4164 sanitize_symbol (debug_sym);
4166 case MONO_PATCH_INFO_RGCTX_FETCH:
4167 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4169 case MONO_PATCH_INFO_ICALL_ADDR: {
4170 char *s = get_debug_sym (ji->data.method, "", cache);
4172 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4176 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4177 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4179 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4180 debug_sym = g_strdup_printf ("plt__generic_class_init");
4190 * Calls made from AOTed code are routed through a table of jumps similar to the
4191 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4192 * control to the AOT runtime through a trampoline.
4195 emit_plt (MonoAotCompile *acfg)
4201 cache = g_hash_table_new (g_str_hash, g_str_equal);
4204 sprintf (symbol, "plt");
4206 emit_section_change (acfg, ".text", 0);
4207 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4208 emit_label (acfg, symbol);
4209 emit_label (acfg, acfg->plt_symbol);
4211 for (i = 0; i < acfg->plt_offset; ++i) {
4212 char *debug_sym = NULL;
4213 MonoPltEntry *plt_entry = NULL;
4218 * The first plt entry is unused.
4222 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4227 * If the target is directly callable, alias the plt symbol to point to
4229 * FIXME: Use this to simplify emit_and_reloc_code ().
4230 * FIXME: Avoid the got slot.
4231 * FIXME: Add support to the binary writer.
4233 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4234 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4236 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4237 /* LLVM calls the PLT entries using bl, so emit a stub */
4238 fprintf (acfg->fp, "\n.thumb_func\n");
4239 emit_label (acfg, plt_entry->llvm_symbol);
4240 fprintf (acfg->fp, "bx pc\n");
4241 fprintf (acfg->fp, "nop\n");
4242 fprintf (acfg->fp, ".arm\n");
4243 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4245 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4251 if (acfg->aot_opts.write_symbols)
4252 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4253 debug_sym = plt_entry->debug_sym;
4255 if (acfg->thumb_mixed && !plt_entry->jit_used)
4256 /* Emit only a thumb version */
4259 if (!acfg->thumb_mixed)
4260 emit_label (acfg, plt_entry->llvm_symbol);
4263 if (acfg->need_no_dead_strip)
4264 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4265 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4266 emit_label (acfg, debug_sym);
4269 emit_label (acfg, plt_entry->symbol);
4271 arch_emit_plt_entry (acfg, i);
4274 emit_symbol_size (acfg, debug_sym, ".");
4277 if (acfg->thumb_mixed) {
4278 /* Make sure the ARM symbols don't alias the thumb ones */
4279 emit_zero_bytes (acfg, 16);
4282 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4285 for (i = 0; i < acfg->plt_offset; ++i) {
4286 char *debug_sym = NULL;
4287 MonoPltEntry *plt_entry = NULL;
4293 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4296 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4299 /* Skip plt entries not actually called by LLVM code */
4300 if (!plt_entry->llvm_used)
4303 if (acfg->aot_opts.write_symbols) {
4304 if (plt_entry->debug_sym)
4305 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4309 #if defined(__APPLE__)
4310 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4311 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4313 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4314 emit_label (acfg, debug_sym);
4316 fprintf (acfg->fp, "\n.thumb_func\n");
4318 emit_label (acfg, plt_entry->llvm_symbol);
4320 arch_emit_llvm_plt_entry (acfg, i);
4323 emit_symbol_size (acfg, debug_sym, ".");
4329 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4331 sprintf (symbol, "plt_end");
4332 emit_label (acfg, symbol);
4334 g_hash_table_destroy (cache);
4337 static G_GNUC_UNUSED void
4338 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4340 char start_symbol [256];
4342 guint32 buf_size, info_offset;
4343 MonoJumpInfo *patch_info;
4354 code_size = info->code_size;
4356 unwind_ops = info->unwind_ops;
4358 #ifdef __native_client_codegen__
4359 mono_nacl_fix_patches (code, ji);
4364 sprintf (start_symbol, "%s", name);
4366 emit_section_change (acfg, ".text", 0);
4367 emit_global (acfg, start_symbol, TRUE);
4368 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4369 emit_label (acfg, start_symbol);
4371 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4372 emit_label (acfg, symbol);
4375 * The code should access everything through the GOT, so we pass
4378 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4380 emit_symbol_size (acfg, start_symbol, ".");
4384 /* Sort relocations */
4385 patches = g_ptr_array_new ();
4386 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4387 if (patch_info->type != MONO_PATCH_INFO_NONE)
4388 g_ptr_array_add (patches, patch_info);
4389 g_ptr_array_sort (patches, compare_patches);
4391 buf_size = patches->len * 128 + 128;
4392 buf = g_malloc (buf_size);
4395 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4396 g_assert (p - buf < buf_size);
4398 sprintf (symbol, "%s_p", name);
4400 info_offset = add_to_blob (acfg, buf, p - buf);
4402 emit_section_change (acfg, RODATA_SECT, 0);
4403 emit_global (acfg, symbol, FALSE);
4404 emit_label (acfg, symbol);
4406 emit_int32 (acfg, info_offset);
4408 /* Emit debug info */
4412 sprintf (symbol, "%s", name);
4413 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4416 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4421 emit_trampolines (MonoAotCompile *acfg)
4424 char end_symbol [256];
4425 int i, tramp_got_offset;
4426 MonoAotTrampoline ntype;
4427 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4431 if (!acfg->aot_opts.full_aot)
4434 g_assert (acfg->image->assembly);
4436 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4437 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4438 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4439 MonoTrampInfo *info;
4442 * Emit the generic trampolines.
4444 * We could save some code by treating the generic trampolines as a wrapper
4445 * method, but that approach has its own complexities, so we choose the simpler
4448 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4449 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4450 emit_trampoline (acfg, acfg->got_offset, info);
4453 mono_arch_get_nullified_class_init_trampoline (&info);
4454 emit_trampoline (acfg, acfg->got_offset, info);
4455 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4456 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4457 emit_trampoline (acfg, acfg->got_offset, info);
4458 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4459 emit_trampoline (acfg, acfg->got_offset, info);
4462 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4463 emit_trampoline (acfg, acfg->got_offset, info);
4465 /* Emit the exception related code pieces */
4466 mono_arch_get_restore_context (&info, TRUE);
4467 emit_trampoline (acfg, acfg->got_offset, info);
4468 mono_arch_get_call_filter (&info, TRUE);
4469 emit_trampoline (acfg, acfg->got_offset, info);
4470 mono_arch_get_throw_exception (&info, TRUE);
4471 emit_trampoline (acfg, acfg->got_offset, info);
4472 mono_arch_get_rethrow_exception (&info, TRUE);
4473 emit_trampoline (acfg, acfg->got_offset, info);
4474 mono_arch_get_throw_corlib_exception (&info, TRUE);
4475 emit_trampoline (acfg, acfg->got_offset, info);
4477 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4479 GSList *l = mono_arch_get_trampolines (TRUE);
4482 MonoTrampInfo *info = l->data;
4484 emit_trampoline (acfg, acfg->got_offset, info);
4490 for (i = 0; i < 128; ++i) {
4493 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4494 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4495 emit_trampoline (acfg, acfg->got_offset, info);
4497 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4498 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4499 emit_trampoline (acfg, acfg->got_offset, info);
4505 /* delegate_invoke_impl trampolines */
4506 l = mono_arch_get_delegate_invoke_impls ();
4508 MonoTrampInfo *info = l->data;
4510 emit_trampoline (acfg, acfg->got_offset, info);
4515 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4517 /* Emit trampolines which are numerous */
4520 * These include the following:
4521 * - specific trampolines
4522 * - static rgctx invoke trampolines
4524 * These trampolines have the same code, they are parameterized by GOT
4526 * They are defined in this file, in the arch_... routines instead of
4527 * in tramp-<ARCH>.c, since it is easier to do it this way.
4531 * When running in aot-only mode, we can't create specific trampolines at
4532 * runtime, so we create a few, and save them in the AOT file.
4533 * Normal trampolines embed their argument as a literal inside the
4534 * trampoline code, we can't do that here, so instead we embed an offset
4535 * which needs to be added to the trampoline address to get the address of
4536 * the GOT slot which contains the argument value.
4537 * The generated trampolines jump to the generic trampolines using another
4538 * GOT slot, which will be setup by the AOT loader to point to the
4539 * generic trampoline code of the given type.
4543 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4547 emit_section_change (acfg, ".text", 0);
4549 tramp_got_offset = acfg->got_offset;
4551 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4553 case MONO_AOT_TRAMP_SPECIFIC:
4554 sprintf (symbol, "specific_trampolines");
4556 case MONO_AOT_TRAMP_STATIC_RGCTX:
4557 sprintf (symbol, "static_rgctx_trampolines");
4559 case MONO_AOT_TRAMP_IMT_THUNK:
4560 sprintf (symbol, "imt_thunks");
4563 g_assert_not_reached ();
4566 sprintf (end_symbol, "%s_e", symbol);
4568 if (acfg->aot_opts.write_symbols)
4569 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
4571 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4572 emit_label (acfg, symbol);
4574 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4576 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4580 case MONO_AOT_TRAMP_SPECIFIC:
4581 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4582 tramp_got_offset += 2;
4584 case MONO_AOT_TRAMP_STATIC_RGCTX:
4585 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4586 tramp_got_offset += 2;
4588 case MONO_AOT_TRAMP_IMT_THUNK:
4589 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4590 tramp_got_offset += 1;
4593 g_assert_not_reached ();
4595 #ifdef __native_client_codegen__
4596 /* align to avoid 32-byte boundary crossings */
4597 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4600 if (!acfg->trampoline_size [ntype]) {
4601 g_assert (tramp_size);
4602 acfg->trampoline_size [ntype] = tramp_size;
4606 emit_label (acfg, end_symbol);
4609 /* Reserve some entries at the end of the GOT for our use */
4610 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4613 acfg->got_offset += acfg->num_trampoline_got_entries;
4617 str_begins_with (const char *str1, const char *str2)
4619 int len = strlen (str2);
4620 return strncmp (str1, str2, len) == 0;
4624 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4626 gchar **args, **ptr;
4628 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4629 for (ptr = args; ptr && *ptr; ptr ++) {
4630 const char *arg = *ptr;
4632 if (str_begins_with (arg, "outfile=")) {
4633 opts->outfile = g_strdup (arg + strlen ("outfile="));
4634 } else if (str_begins_with (arg, "save-temps")) {
4635 opts->save_temps = TRUE;
4636 } else if (str_begins_with (arg, "keep-temps")) {
4637 opts->save_temps = TRUE;
4638 } else if (str_begins_with (arg, "write-symbols")) {
4639 opts->write_symbols = TRUE;
4640 } else if (str_begins_with (arg, "no-write-symbols")) {
4641 opts->write_symbols = FALSE;
4642 } else if (str_begins_with (arg, "metadata-only")) {
4643 opts->metadata_only = TRUE;
4644 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4645 opts->bind_to_runtime_version = TRUE;
4646 } else if (str_begins_with (arg, "full")) {
4647 opts->full_aot = TRUE;
4648 } else if (str_begins_with (arg, "threads=")) {
4649 opts->nthreads = atoi (arg + strlen ("threads="));
4650 } else if (str_begins_with (arg, "static")) {
4651 opts->static_link = TRUE;
4652 opts->no_dlsym = TRUE;
4653 } else if (str_begins_with (arg, "asmonly")) {
4654 opts->asm_only = TRUE;
4655 } else if (str_begins_with (arg, "asmwriter")) {
4656 opts->asm_writer = TRUE;
4657 } else if (str_begins_with (arg, "nodebug")) {
4658 opts->nodebug = TRUE;
4659 } else if (str_begins_with (arg, "ntrampolines=")) {
4660 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4661 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4662 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4663 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4664 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4665 } else if (str_begins_with (arg, "autoreg")) {
4666 opts->autoreg = TRUE;
4667 } else if (str_begins_with (arg, "tool-prefix=")) {
4668 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4669 } else if (str_begins_with (arg, "soft-debug")) {
4670 opts->soft_debug = TRUE;
4671 } else if (str_begins_with (arg, "print-skipped")) {
4672 opts->print_skipped_methods = TRUE;
4673 } else if (str_begins_with (arg, "stats")) {
4675 } else if (str_begins_with (arg, "mtriple=")) {
4676 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4677 } else if (str_begins_with (arg, "llvm-path=")) {
4678 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4679 } else if (str_begins_with (arg, "info")) {
4680 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
4682 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
4683 printf ("Supported options for --aot:\n");
4684 printf (" outfile=\n");
4685 printf (" save-temps\n");
4686 printf (" keep-temps\n");
4687 printf (" write-symbols\n");
4688 printf (" metadata-only\n");
4689 printf (" bind-to-runtime-version\n");
4691 printf (" threads=\n");
4692 printf (" static\n");
4693 printf (" asmonly\n");
4694 printf (" asmwriter\n");
4695 printf (" nodebug\n");
4696 printf (" ntrampolines=\n");
4697 printf (" nrgctx-trampolines=\n");
4698 printf (" nimt-trampolines=\n");
4699 printf (" autoreg\n");
4700 printf (" tool-prefix=\n");
4701 printf (" soft-debug\n");
4702 printf (" print-skipped\n");
4703 printf (" stats\n");
4705 printf (" help/?\n");
4708 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4717 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4719 MonoMethod *method = (MonoMethod*)key;
4720 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4721 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4722 MonoAotCompile *acfg = user_data;
4724 new_ji->image = ji->image;
4725 new_ji->token = ji->token;
4726 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4730 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4732 if (klass->type_token)
4734 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4737 return can_encode_class (acfg, klass->element_class);
4742 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4744 switch (patch_info->type) {
4745 case MONO_PATCH_INFO_METHOD:
4746 case MONO_PATCH_INFO_METHODCONST: {
4747 MonoMethod *method = patch_info->data.method;
4749 if (method->wrapper_type) {
4750 switch (method->wrapper_type) {
4751 case MONO_WRAPPER_NONE:
4752 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4753 case MONO_WRAPPER_XDOMAIN_INVOKE:
4754 case MONO_WRAPPER_STFLD:
4755 case MONO_WRAPPER_LDFLD:
4756 case MONO_WRAPPER_LDFLDA:
4757 case MONO_WRAPPER_LDFLD_REMOTE:
4758 case MONO_WRAPPER_STFLD_REMOTE:
4759 case MONO_WRAPPER_STELEMREF:
4760 case MONO_WRAPPER_ISINST:
4761 case MONO_WRAPPER_PROXY_ISINST:
4762 case MONO_WRAPPER_ALLOC:
4763 case MONO_WRAPPER_REMOTING_INVOKE:
4764 case MONO_WRAPPER_UNKNOWN:
4765 case MONO_WRAPPER_WRITE_BARRIER:
4767 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4768 if (!strcmp (method->name, "ElementAddr"))
4772 case MONO_WRAPPER_CASTCLASS:
4773 if (!strcmp (method->name, "__castclass_with_cache"))
4775 else if (!strcmp (method->name, "__isinst_with_cache"))
4780 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4784 if (!method->token) {
4785 /* The method is part of a constructed type like Int[,].Set (). */
4786 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4787 if (method->klass->rank)
4795 case MONO_PATCH_INFO_VTABLE:
4796 case MONO_PATCH_INFO_CLASS_INIT:
4797 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4798 case MONO_PATCH_INFO_CLASS:
4799 case MONO_PATCH_INFO_IID:
4800 case MONO_PATCH_INFO_ADJUSTED_IID:
4801 if (!can_encode_class (acfg, patch_info->data.klass)) {
4802 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4806 case MONO_PATCH_INFO_RGCTX_FETCH: {
4807 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4809 if (!can_encode_patch (acfg, entry->data))
4823 * AOT compile a given method.
4824 * This function might be called by multiple threads, so it must be thread-safe.
4827 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4830 MonoJumpInfo *patch_info;
4833 MonoMethod *wrapped;
4835 if (acfg->aot_opts.metadata_only)
4838 mono_acfg_lock (acfg);
4839 index = get_method_index (acfg, method);
4840 mono_acfg_unlock (acfg);
4842 /* fixme: maybe we can also precompile wrapper methods */
4843 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4844 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4845 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4846 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4850 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4853 wrapped = mono_marshal_method_from_wrapper (method);
4854 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4855 // FIXME: The wrapper should be generic too, but it is not
4858 InterlockedIncrement (&acfg->stats.mcount);
4861 if (method->is_generic || method->klass->generic_container) {
4862 InterlockedIncrement (&acfg->stats.genericcount);
4867 //acfg->aot_opts.print_skipped_methods = TRUE;
4870 * Since these methods are the only ones which are compiled with
4871 * AOT support, and they are not used by runtime startup/shutdown code,
4872 * the runtime will not see AOT methods during AOT compilation,so it
4873 * does not need to support them by creating a fake GOT etc.
4875 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4876 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4877 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4878 InterlockedIncrement (&acfg->stats.genericcount);
4881 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4882 //printf ("E: %s\n", mono_method_full_name (method, TRUE));
4883 /* Let the exception happen at runtime */
4887 if (cfg->disable_aot) {
4888 if (acfg->aot_opts.print_skipped_methods)
4889 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4890 InterlockedIncrement (&acfg->stats.ocount);
4891 mono_destroy_compile (cfg);
4895 /* Nullify patches which need no aot processing */
4896 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4897 switch (patch_info->type) {
4898 case MONO_PATCH_INFO_LABEL:
4899 case MONO_PATCH_INFO_BB:
4900 patch_info->type = MONO_PATCH_INFO_NONE;
4907 /* Collect method->token associations from the cfg */
4908 mono_acfg_lock (acfg);
4909 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4910 mono_acfg_unlock (acfg);
4913 * Check for absolute addresses.
4916 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4917 switch (patch_info->type) {
4918 case MONO_PATCH_INFO_ABS:
4919 /* unable to handle this */
4928 if (acfg->aot_opts.print_skipped_methods)
4929 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4930 InterlockedIncrement (&acfg->stats.abscount);
4931 mono_destroy_compile (cfg);
4935 /* Lock for the rest of the code */
4936 mono_acfg_lock (acfg);
4939 * Check for methods/klasses we can't encode.
4942 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4943 if (!can_encode_patch (acfg, patch_info))
4948 if (acfg->aot_opts.print_skipped_methods)
4949 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4950 acfg->stats.ocount++;
4951 mono_destroy_compile (cfg);
4952 mono_acfg_unlock (acfg);
4956 /* Adds generic instances referenced by this method */
4958 * The depth is used to avoid infinite loops when generic virtual recursion is
4961 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4963 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4964 switch (patch_info->type) {
4965 case MONO_PATCH_INFO_METHOD: {
4966 MonoMethod *m = patch_info->data.method;
4967 if (m->is_inflated) {
4968 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4969 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4970 !method_has_type_vars (m)) {
4971 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4972 if (acfg->aot_opts.full_aot)
4973 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4975 add_extra_method_with_depth (acfg, m, depth + 1);
4978 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4980 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4981 add_extra_method_with_depth (acfg, m, depth + 1);
4984 case MONO_PATCH_INFO_VTABLE: {
4985 MonoClass *klass = patch_info->data.klass;
4987 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4988 add_generic_class_with_depth (acfg, klass, depth + 5);
4997 /* Determine whenever the method has GOT slots */
4998 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4999 switch (patch_info->type) {
5000 case MONO_PATCH_INFO_GOT_OFFSET:
5001 case MONO_PATCH_INFO_NONE:
5002 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5004 case MONO_PATCH_INFO_IMAGE:
5005 /* The assembly is stored in GOT slot 0 */
5006 if (patch_info->data.image != acfg->image)
5007 cfg->has_got_slots = TRUE;
5010 if (!is_plt_patch (patch_info))
5011 cfg->has_got_slots = TRUE;
5016 if (!cfg->has_got_slots)
5017 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5020 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5022 /* Make a copy of the patch info which is in the mempool */
5024 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5026 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5027 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5030 patches = new_patch_info;
5032 patches_end->next = new_patch_info;
5033 patches_end = new_patch_info;
5035 cfg->patch_info = patches;
5037 /* Make a copy of the unwind info */
5039 GSList *l, *unwind_ops;
5043 for (l = cfg->unwind_ops; l; l = l->next) {
5044 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5045 memcpy (op, l->data, sizeof (MonoUnwindOp));
5046 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5048 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5050 /* Make a copy of the argument/local info */
5052 MonoInst **args, **locals;
5053 MonoMethodSignature *sig;
5054 MonoMethodHeader *header;
5057 sig = mono_method_signature (method);
5058 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5059 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5060 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5061 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5065 header = mono_method_get_header (method);
5066 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5067 for (i = 0; i < header->num_locals; ++i) {
5068 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5069 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5071 cfg->locals = locals;
5074 /* Free some fields used by cfg to conserve memory */
5075 mono_mempool_destroy (cfg->mempool);
5076 cfg->mempool = NULL;
5077 g_free (cfg->varinfo);
5078 cfg->varinfo = NULL;
5082 mono_regstate_free (cfg->rs);
5086 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5088 while (index >= acfg->cfgs_size) {
5089 MonoCompile **new_cfgs;
5092 new_size = acfg->cfgs_size * 2;
5093 new_cfgs = g_new0 (MonoCompile*, new_size);
5094 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5095 g_free (acfg->cfgs);
5096 acfg->cfgs = new_cfgs;
5097 acfg->cfgs_size = new_size;
5099 acfg->cfgs [index] = cfg;
5101 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5104 if (cfg->orig_method->wrapper_type)
5105 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5108 mono_acfg_unlock (acfg);
5110 InterlockedIncrement (&acfg->stats.ccount);
5114 compile_thread_main (gpointer *user_data)
5116 MonoDomain *domain = user_data [0];
5117 MonoAotCompile *acfg = user_data [1];
5118 GPtrArray *methods = user_data [2];
5121 mono_thread_attach (domain);
5123 for (i = 0; i < methods->len; ++i)
5124 compile_method (acfg, g_ptr_array_index (methods, i));
5128 load_profile_files (MonoAotCompile *acfg)
5132 int file_index, res, method_index, i;
5135 GList *unordered, *l;
5140 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5142 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5147 infile = fopen (tmp, "r");
5150 printf ("Using profile data file '%s'\n", tmp);
5155 res = fscanf (infile, "%32s\n", ver);
5156 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5157 printf ("Profile file has wrong version or invalid.\n");
5164 MonoMethodDesc *desc;
5167 if (fgets (name, 1023, infile) == NULL)
5170 /* Kill the newline */
5171 if (strlen (name) > 0)
5172 name [strlen (name) - 1] = '\0';
5174 desc = mono_method_desc_new (name, TRUE);
5176 method = mono_method_desc_search_in_image (desc, acfg->image);
5178 if (method && mono_method_get_token (method)) {
5179 token = mono_method_get_token (method);
5180 method_index = mono_metadata_token_index (token) - 1;
5183 for (i = 0; i < acfg->method_order->len; ++i) {
5184 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5190 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5192 //printf ("No method found matching '%s'.\n", name);
5198 /* Add missing methods */
5200 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5202 for (i = 0; i < acfg->method_order->len; ++i) {
5203 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5209 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5211 unordered = g_list_reverse (unordered);
5212 for (l = unordered; l; l = l->next)
5213 g_ptr_array_add (acfg->method_order, l->data);
5216 /* Used by the LLVM backend */
5218 mono_aot_get_got_offset (MonoJumpInfo *ji)
5220 return get_got_offset (llvm_acfg, ji);
5224 mono_aot_get_method_name (MonoCompile *cfg)
5226 if (llvm_acfg->aot_opts.static_link)
5227 /* Include the assembly name too to avoid duplicate symbol errors */
5228 return g_strdup_printf ("%s_%s", llvm_acfg->image->assembly->aname.name, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5230 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5234 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5236 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5237 MonoPltEntry *plt_entry;
5240 ji->data.target = data;
5242 if (!can_encode_patch (llvm_acfg, ji))
5245 plt_entry = get_plt_entry (llvm_acfg, ji);
5246 plt_entry->llvm_used = TRUE;
5248 #if defined(__APPLE__)
5249 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5251 return g_strdup_printf (plt_entry->llvm_symbol);
5256 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5260 mono_acfg_lock (llvm_acfg);
5261 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5262 mono_acfg_unlock (llvm_acfg);
5272 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5276 emit_llvm_file (MonoAotCompile *acfg)
5278 char *command, *opts;
5280 MonoJumpInfo *patch_info;
5283 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5287 /* Compute the final size of the got */
5288 for (i = 0; i < acfg->nmethods; ++i) {
5289 if (acfg->cfgs [i]) {
5290 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5291 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5292 if (!is_plt_patch (patch_info))
5293 get_got_offset (acfg, patch_info);
5295 get_plt_entry (acfg, patch_info);
5301 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5303 if (acfg->aot_opts.full_aot) {
5307 * Need to add the got entries used by the trampolines.
5308 * This is only a conservative approximation.
5310 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5311 /* For the generic + rgctx trampolines */
5312 acfg->final_got_size += 200;
5313 /* For the specific trampolines */
5314 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5315 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5320 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5323 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5324 * a lot of time, and doesn't seem to save much space.
5325 * The following optimizations cannot be enabled:
5327 * - 'jump-threading' changes our blockaddress references to int constants.
5328 * The opt list below was produced by taking the output of:
5329 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5330 * then removing tailcallelim + the global opts, and adding a second gvn.
5332 opts = g_strdup ("-instcombine -simplifycfg");
5333 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5335 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5336 printf ("Executing opt: %s\n", command);
5337 if (system (command) != 0) {
5343 if (!acfg->llc_args)
5344 acfg->llc_args = g_string_new ("");
5346 /* Verbose asm slows down llc greatly */
5347 g_string_append (acfg->llc_args, " -asm-verbose=false");
5349 if (acfg->aot_opts.mtriple)
5350 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5352 if (llvm_acfg->aot_opts.static_link)
5353 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5355 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5356 unlink (acfg->tmpfname);
5358 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5360 printf ("Executing llc: %s\n", command);
5362 if (system (command) != 0) {
5369 emit_code (MonoAotCompile *acfg)
5373 char end_symbol [256];
5375 #if defined(TARGET_POWERPC64)
5376 sprintf (symbol, ".Lgot_addr");
5377 emit_section_change (acfg, ".text", 0);
5378 emit_alignment (acfg, 8);
5379 emit_label (acfg, symbol);
5380 emit_pointer (acfg, acfg->got_symbol);
5384 * This global symbol is used to compute the address of each method using the
5385 * code_offsets array. It is also used to compute the memory ranges occupied by
5386 * AOT code, so it must be equal to the address of the first emitted method.
5388 sprintf (symbol, "methods");
5389 emit_section_change (acfg, ".text", 0);
5390 emit_alignment (acfg, 8);
5392 for (i = 0; i < acfg->nmethods; ++i) {
5393 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5394 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5398 if (i == acfg->nmethods)
5399 /* No LLVM compiled methods */
5400 emit_label (acfg, symbol);
5402 emit_label (acfg, symbol);
5406 * Emit some padding so the local symbol for the first method doesn't have the
5407 * same address as 'methods'.
5409 #if defined(__default_codegen__)
5410 emit_zero_bytes (acfg, 16);
5411 #elif defined(__native_client_codegen__)
5413 const int kPaddingSize = 16;
5414 guint8 pad_buffer[kPaddingSize];
5415 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5416 emit_bytes (acfg, pad_buffer, kPaddingSize);
5420 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5424 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5426 cfg = acfg->cfgs [i];
5431 method = cfg->orig_method;
5433 /* Emit unbox trampoline */
5434 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5435 if (!method->wrapper_type && !method->is_inflated) {
5436 g_assert (method->token);
5437 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5439 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5442 emit_section_change (acfg, ".text", 0);
5443 #ifdef __native_client_codegen__
5444 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5446 emit_global (acfg, symbol, TRUE);
5448 if (acfg->thumb_mixed && cfg->compile_llvm)
5449 fprintf (acfg->fp, "\n.thumb_func\n");
5451 emit_label (acfg, symbol);
5453 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5456 if (cfg->compile_llvm)
5457 acfg->stats.llvm_count ++;
5459 emit_method_code (acfg, cfg);
5462 sprintf (symbol, "methods_end");
5463 emit_section_change (acfg, ".text", 0);
5464 emit_alignment (acfg, 8);
5465 emit_label (acfg, symbol);
5468 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5469 * from optimizing them away, since it doesn't see that code_offsets references them.
5470 * JITted methods don't need this since they are referenced using assembler local
5472 * FIXME: This is why write-symbols doesn't work on OSX ?
5474 if (acfg->llvm && acfg->need_no_dead_strip) {
5475 fprintf (acfg->fp, "\n");
5476 for (i = 0; i < acfg->nmethods; ++i) {
5477 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5478 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5482 sprintf (symbol, "code_offsets");
5483 emit_section_change (acfg, RODATA_SECT, 1);
5484 emit_alignment (acfg, 8);
5485 emit_label (acfg, symbol);
5487 acfg->stats.offsets_size += acfg->nmethods * 4;
5489 sprintf (end_symbol, "methods");
5490 for (i = 0; i < acfg->nmethods; ++i) {
5491 if (acfg->cfgs [i]) {
5492 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5494 emit_int32 (acfg, 0xffffffff);
5501 emit_info (MonoAotCompile *acfg)
5507 offsets = g_new0 (gint32, acfg->nmethods);
5509 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5510 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5512 if (acfg->cfgs [i]) {
5513 emit_method_info (acfg, acfg->cfgs [i]);
5514 offsets [i] = acfg->cfgs [i]->method_info_offset;
5520 sprintf (symbol, "method_info_offsets");
5521 emit_section_change (acfg, RODATA_SECT, 1);
5522 emit_alignment (acfg, 8);
5523 emit_label (acfg, symbol);
5525 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5530 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5532 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5533 #define mix(a,b,c) { \
5534 a -= c; a ^= rot(c, 4); c += b; \
5535 b -= a; b ^= rot(a, 6); a += c; \
5536 c -= b; c ^= rot(b, 8); b += a; \
5537 a -= c; a ^= rot(c,16); c += b; \
5538 b -= a; b ^= rot(a,19); a += c; \
5539 c -= b; c ^= rot(b, 4); b += a; \
5541 #define final(a,b,c) { \
5542 c ^= b; c -= rot(b,14); \
5543 a ^= c; a -= rot(c,11); \
5544 b ^= a; b -= rot(a,25); \
5545 c ^= b; c -= rot(b,16); \
5546 a ^= c; a -= rot(c,4); \
5547 b ^= a; b -= rot(a,14); \
5548 c ^= b; c -= rot(b,24); \
5552 mono_aot_type_hash (MonoType *t1)
5554 guint hash = t1->type;
5556 hash |= t1->byref << 6; /* do not collide with t1->type values */
5558 case MONO_TYPE_VALUETYPE:
5559 case MONO_TYPE_CLASS:
5560 case MONO_TYPE_SZARRAY:
5561 /* check if the distribution is good enough */
5562 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5564 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5565 case MONO_TYPE_ARRAY:
5566 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5567 case MONO_TYPE_GENERICINST:
5568 return ((hash << 5) - hash) ^ 0;
5575 * mono_aot_method_hash:
5577 * Return a hash code for methods which only depends on metadata.
5580 mono_aot_method_hash (MonoMethod *method)
5582 MonoMethodSignature *sig;
5586 guint32 *hashes_start, *hashes;
5588 MonoGenericInst *ginst = NULL;
5590 /* Similar to the hash in mono_method_get_imt_slot () */
5592 sig = mono_method_signature (method);
5594 if (method->is_inflated)
5595 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5597 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5598 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5599 hashes = hashes_start;
5601 /* Some wrappers are assigned to random classes */
5602 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5603 klass = method->klass;
5605 klass = mono_defaults.object_class;
5607 if (!method->wrapper_type) {
5608 char *full_name = mono_type_full_name (&klass->byval_arg);
5610 hashes [0] = mono_metadata_str_hash (full_name);
5614 hashes [0] = mono_metadata_str_hash (klass->name);
5615 hashes [1] = mono_metadata_str_hash (klass->name_space);
5617 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5618 /* The method name includes a stringified pointer */
5621 hashes [2] = mono_metadata_str_hash (method->name);
5622 hashes [3] = method->wrapper_type;
5623 hashes [4] = mono_aot_type_hash (sig->ret);
5625 for (i = 0; i < sig->param_count; i++) {
5626 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5629 for (i = 0; i < ginst->type_argc; ++i)
5630 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5632 g_assert (hindex == hashes_count);
5634 /* Setup internal state */
5635 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5637 /* Handle most of the hashes */
5638 while (hashes_count > 3) {
5647 /* Handle the last 3 hashes (all the case statements fall through) */
5648 switch (hashes_count) {
5649 case 3 : c += hashes [2];
5650 case 2 : b += hashes [1];
5651 case 1 : a += hashes [0];
5653 case 0: /* nothing left to add */
5657 free (hashes_start);
5666 * mono_aot_wrapper_name:
5668 * Return a string which uniqely identifies the given wrapper method.
5671 mono_aot_wrapper_name (MonoMethod *method)
5673 char *name, *tmpsig, *klass_desc;
5675 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5677 switch (method->wrapper_type) {
5678 case MONO_WRAPPER_RUNTIME_INVOKE:
5679 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5680 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5682 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5685 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5686 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5687 g_free (klass_desc);
5697 * mono_aot_get_array_helper_from_wrapper;
5699 * Get the helper method in Array called by an array wrapper method.
5702 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5706 MonoGenericContext ctx;
5707 MonoType *args [16];
5708 char *mname, *iname, *s, *s2, *helper_name = NULL;
5710 prefix = "System.Collections.Generic";
5711 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5712 s2 = strstr (s, "`1.");
5718 //printf ("X: %s %s\n", iname, mname);
5720 if (!strcmp (iname, "IList"))
5721 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5723 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5724 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5726 g_free (helper_name);
5729 if (m->is_generic) {
5730 memset (&ctx, 0, sizeof (ctx));
5731 args [0] = &method->klass->element_class->byval_arg;
5732 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5733 m = mono_class_inflate_generic_method (m, &ctx);
5739 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5741 typedef struct HashEntry {
5742 guint32 key, value, index;
5743 struct HashEntry *next;
5747 * emit_extra_methods:
5749 * Emit methods which are not in the METHOD table, like wrappers.
5752 emit_extra_methods (MonoAotCompile *acfg)
5754 int i, table_size, buf_size;
5757 guint32 *info_offsets;
5760 HashEntry *entry, *new_entry;
5761 int nmethods, max_chain_length;
5764 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5766 /* Emit method info */
5768 for (i = 0; i < acfg->extra_methods->len; ++i) {
5769 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5770 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5777 p = buf = g_malloc (buf_size);
5781 method = cfg->method_to_register;
5784 if (method->wrapper_type) {
5785 gboolean encode_ref = FALSE;
5788 * We encode some wrappers using their name, since encoding them
5789 * directly would be difficult. This works because at runtime, we only need to
5790 * check whenever a method ref matches an existing MonoMethod. The downside is
5791 * that the method names are large, so we use the binary encoding if possible.
5793 switch (method->wrapper_type) {
5794 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5795 case MONO_WRAPPER_SYNCHRONIZED:
5798 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5799 /* Skip JIT icall wrappers */
5800 if (!strstr (method->name, "__icall_wrapper"))
5803 case MONO_WRAPPER_UNKNOWN:
5804 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5807 case MONO_WRAPPER_RUNTIME_INVOKE:
5808 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5809 /* Direct wrapper, encode normally */
5817 name = mono_aot_wrapper_name (method);
5821 encode_value (1, p, &p);
5822 encode_value (method->wrapper_type, p, &p);
5823 strcpy ((char*)p, name);
5824 p += strlen (name ) + 1;
5827 encode_value (0, p, &p);
5828 encode_method_ref (acfg, method, p, &p);
5831 g_assert ((p - buf) < buf_size);
5833 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5838 * Construct a chained hash table for mapping indexes in extra_method_info to
5841 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5842 table = g_ptr_array_sized_new (table_size);
5843 for (i = 0; i < table_size; ++i)
5844 g_ptr_array_add (table, NULL);
5845 chain_lengths = g_new0 (int, table_size);
5846 max_chain_length = 0;
5847 for (i = 0; i < acfg->extra_methods->len; ++i) {
5848 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5849 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5855 key = info_offsets [i];
5856 value = get_method_index (acfg, method);
5858 hash = mono_aot_method_hash (method) % table_size;
5860 chain_lengths [hash] ++;
5861 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5863 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5864 new_entry->key = key;
5865 new_entry->value = value;
5867 entry = g_ptr_array_index (table, hash);
5868 if (entry == NULL) {
5869 new_entry->index = hash;
5870 g_ptr_array_index (table, hash) = new_entry;
5873 entry = entry->next;
5875 entry->next = new_entry;
5876 new_entry->index = table->len;
5877 g_ptr_array_add (table, new_entry);
5881 //printf ("MAX: %d\n", max_chain_length);
5883 /* Emit the table */
5884 sprintf (symbol, "extra_method_table");
5885 emit_section_change (acfg, RODATA_SECT, 0);
5886 emit_alignment (acfg, 8);
5887 emit_label (acfg, symbol);
5889 emit_int32 (acfg, table_size);
5890 for (i = 0; i < table->len; ++i) {
5891 HashEntry *entry = g_ptr_array_index (table, i);
5893 if (entry == NULL) {
5894 emit_int32 (acfg, 0);
5895 emit_int32 (acfg, 0);
5896 emit_int32 (acfg, 0);
5898 //g_assert (entry->key > 0);
5899 emit_int32 (acfg, entry->key);
5900 emit_int32 (acfg, entry->value);
5902 emit_int32 (acfg, entry->next->index);
5904 emit_int32 (acfg, 0);
5909 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5910 * This is used by mono_aot_find_jit_info ().
5912 sprintf (symbol, "extra_method_info_offsets");
5913 emit_section_change (acfg, RODATA_SECT, 0);
5914 emit_alignment (acfg, 8);
5915 emit_label (acfg, symbol);
5917 emit_int32 (acfg, acfg->extra_methods->len);
5918 for (i = 0; i < acfg->extra_methods->len; ++i) {
5919 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5921 emit_int32 (acfg, get_method_index (acfg, method));
5922 emit_int32 (acfg, info_offsets [i]);
5927 emit_exception_info (MonoAotCompile *acfg)
5933 offsets = g_new0 (gint32, acfg->nmethods);
5934 for (i = 0; i < acfg->nmethods; ++i) {
5935 if (acfg->cfgs [i]) {
5936 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5937 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5943 sprintf (symbol, "ex_info_offsets");
5944 emit_section_change (acfg, RODATA_SECT, 1);
5945 emit_alignment (acfg, 8);
5946 emit_label (acfg, symbol);
5948 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5953 emit_unwind_info (MonoAotCompile *acfg)
5959 * The unwind info contains a lot of duplicates so we emit each unique
5960 * entry once, and only store the offset from the start of the table in the
5964 sprintf (symbol, "unwind_info");
5965 emit_section_change (acfg, RODATA_SECT, 1);
5966 emit_alignment (acfg, 8);
5967 emit_label (acfg, symbol);
5969 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5970 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5971 guint8 *unwind_info;
5972 guint32 unwind_info_len;
5976 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5979 encode_value (unwind_info_len, p, &p);
5980 emit_bytes (acfg, buf, p - buf);
5981 emit_bytes (acfg, unwind_info, unwind_info_len);
5983 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5988 emit_class_info (MonoAotCompile *acfg)
5994 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5995 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5996 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5998 sprintf (symbol, "class_info_offsets");
5999 emit_section_change (acfg, RODATA_SECT, 1);
6000 emit_alignment (acfg, 8);
6001 emit_label (acfg, symbol);
6003 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6007 typedef struct ClassNameTableEntry {
6008 guint32 token, index;
6009 struct ClassNameTableEntry *next;
6010 } ClassNameTableEntry;
6013 emit_class_name_table (MonoAotCompile *acfg)
6016 guint32 token, hash;
6021 ClassNameTableEntry *entry, *new_entry;
6024 * Construct a chained hash table for mapping class names to typedef tokens.
6026 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6027 table = g_ptr_array_sized_new (table_size);
6028 for (i = 0; i < table_size; ++i)
6029 g_ptr_array_add (table, NULL);
6030 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6031 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6032 klass = mono_class_get (acfg->image, token);
6034 mono_loader_clear_error ();
6037 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6038 hash = mono_metadata_str_hash (full_name) % table_size;
6041 /* FIXME: Allocate from the mempool */
6042 new_entry = g_new0 (ClassNameTableEntry, 1);
6043 new_entry->token = token;
6045 entry = g_ptr_array_index (table, hash);
6046 if (entry == NULL) {
6047 new_entry->index = hash;
6048 g_ptr_array_index (table, hash) = new_entry;
6051 entry = entry->next;
6053 entry->next = new_entry;
6054 new_entry->index = table->len;
6055 g_ptr_array_add (table, new_entry);
6059 /* Emit the table */
6060 sprintf (symbol, "class_name_table");
6061 emit_section_change (acfg, RODATA_SECT, 0);
6062 emit_alignment (acfg, 8);
6063 emit_label (acfg, symbol);
6065 /* FIXME: Optimize memory usage */
6066 g_assert (table_size < 65000);
6067 emit_int16 (acfg, table_size);
6068 g_assert (table->len < 65000);
6069 for (i = 0; i < table->len; ++i) {
6070 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6072 if (entry == NULL) {
6073 emit_int16 (acfg, 0);
6074 emit_int16 (acfg, 0);
6076 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6078 emit_int16 (acfg, entry->next->index);
6080 emit_int16 (acfg, 0);
6086 emit_image_table (MonoAotCompile *acfg)
6092 * The image table is small but referenced in a lot of places.
6093 * So we emit it at once, and reference its elements by an index.
6096 sprintf (symbol, "image_table");
6097 emit_section_change (acfg, RODATA_SECT, 1);
6098 emit_alignment (acfg, 8);
6099 emit_label (acfg, symbol);
6101 emit_int32 (acfg, acfg->image_table->len);
6102 for (i = 0; i < acfg->image_table->len; i++) {
6103 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6104 MonoAssemblyName *aname = &image->assembly->aname;
6106 /* FIXME: Support multi-module assemblies */
6107 g_assert (image->assembly->image == image);
6109 emit_string (acfg, image->assembly_name);
6110 emit_string (acfg, image->guid);
6111 emit_string (acfg, aname->culture ? aname->culture : "");
6112 emit_string (acfg, (const char*)aname->public_key_token);
6114 emit_alignment (acfg, 8);
6115 emit_int32 (acfg, aname->flags);
6116 emit_int32 (acfg, aname->major);
6117 emit_int32 (acfg, aname->minor);
6118 emit_int32 (acfg, aname->build);
6119 emit_int32 (acfg, aname->revision);
6124 emit_got_info (MonoAotCompile *acfg)
6127 int i, first_plt_got_patch, buf_size;
6129 guint32 *got_info_offsets;
6131 /* Add the patches needed by the PLT to the GOT */
6132 acfg->plt_got_offset_base = acfg->got_offset;
6133 first_plt_got_patch = acfg->got_patches->len;
6134 for (i = 1; i < acfg->plt_offset; ++i) {
6135 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6137 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6140 acfg->got_offset += acfg->plt_offset;
6144 * - optimize offsets table.
6145 * - reduce number of exported symbols.
6146 * - emit info for a klass only once.
6147 * - determine when a method uses a GOT slot which is guaranteed to be already
6149 * - clean up and document the code.
6150 * - use String.Empty in class libs.
6153 /* Encode info required to decode shared GOT entries */
6154 buf_size = acfg->got_patches->len * 128;
6155 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6156 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6157 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6159 if (acfg->plt_offset)
6160 acfg->plt_got_info_offsets [0] = 0;
6161 for (i = 0; i < acfg->got_patches->len; ++i) {
6162 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6166 encode_value (ji->type, p, &p);
6167 encode_patch (acfg, ji, p, &p);
6169 g_assert (p - buf <= buf_size);
6170 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6172 if (i >= first_plt_got_patch)
6173 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6174 acfg->stats.got_info_size += p - buf;
6177 /* Emit got_info_offsets table */
6178 sprintf (symbol, "got_info_offsets");
6179 emit_section_change (acfg, RODATA_SECT, 1);
6180 emit_alignment (acfg, 8);
6181 emit_label (acfg, symbol);
6183 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6184 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6188 emit_got (MonoAotCompile *acfg)
6193 /* Don't make GOT global so accesses to it don't need relocations */
6194 sprintf (symbol, "%s", acfg->got_symbol);
6195 emit_section_change (acfg, ".bss", 0);
6196 emit_alignment (acfg, 8);
6197 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6198 emit_label (acfg, symbol);
6199 if (acfg->got_offset > 0)
6200 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6202 sprintf (symbol, "got_end");
6203 emit_label (acfg, symbol);
6207 typedef struct GlobalsTableEntry {
6208 guint32 value, index;
6209 struct GlobalsTableEntry *next;
6210 } GlobalsTableEntry;
6213 emit_globals (MonoAotCompile *acfg)
6219 GlobalsTableEntry *entry, *new_entry;
6221 if (!acfg->aot_opts.static_link)
6225 * When static linking, we emit a table containing our globals.
6229 * Construct a chained hash table for mapping global names to their index in
6230 * the globals table.
6232 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6233 table = g_ptr_array_sized_new (table_size);
6234 for (i = 0; i < table_size; ++i)
6235 g_ptr_array_add (table, NULL);
6236 for (i = 0; i < acfg->globals->len; ++i) {
6237 char *name = g_ptr_array_index (acfg->globals, i);
6239 hash = mono_metadata_str_hash (name) % table_size;
6241 /* FIXME: Allocate from the mempool */
6242 new_entry = g_new0 (GlobalsTableEntry, 1);
6243 new_entry->value = i;
6245 entry = g_ptr_array_index (table, hash);
6246 if (entry == NULL) {
6247 new_entry->index = hash;
6248 g_ptr_array_index (table, hash) = new_entry;
6251 entry = entry->next;
6253 entry->next = new_entry;
6254 new_entry->index = table->len;
6255 g_ptr_array_add (table, new_entry);
6259 /* Emit the table */
6260 sprintf (symbol, ".Lglobals_hash");
6261 emit_section_change (acfg, RODATA_SECT, 0);
6262 emit_alignment (acfg, 8);
6263 emit_label (acfg, symbol);
6265 /* FIXME: Optimize memory usage */
6266 g_assert (table_size < 65000);
6267 emit_int16 (acfg, table_size);
6268 for (i = 0; i < table->len; ++i) {
6269 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6271 if (entry == NULL) {
6272 emit_int16 (acfg, 0);
6273 emit_int16 (acfg, 0);
6275 emit_int16 (acfg, entry->value + 1);
6277 emit_int16 (acfg, entry->next->index);
6279 emit_int16 (acfg, 0);
6283 /* Emit the names */
6284 for (i = 0; i < acfg->globals->len; ++i) {
6285 char *name = g_ptr_array_index (acfg->globals, i);
6287 sprintf (symbol, "name_%d", i);
6288 emit_section_change (acfg, RODATA_SECT, 1);
6290 emit_alignment (acfg, 4);
6292 emit_label (acfg, symbol);
6293 emit_string (acfg, name);
6296 /* Emit the globals table */
6297 sprintf (symbol, "globals");
6298 emit_section_change (acfg, ".data", 0);
6299 /* This is not a global, since it is accessed by the init function */
6300 emit_alignment (acfg, 8);
6301 emit_label (acfg, symbol);
6303 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6304 emit_pointer (acfg, symbol);
6306 for (i = 0; i < acfg->globals->len; ++i) {
6307 char *name = g_ptr_array_index (acfg->globals, i);
6309 sprintf (symbol, "name_%d", i);
6310 emit_pointer (acfg, symbol);
6312 sprintf (symbol, "%s", name);
6313 emit_pointer (acfg, symbol);
6315 /* Null terminate the table */
6316 emit_int32 (acfg, 0);
6317 emit_int32 (acfg, 0);
6321 emit_autoreg (MonoAotCompile *acfg)
6326 * Emit a function into the .ctor section which will be called by the ELF
6327 * loader to register this module with the runtime.
6329 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6332 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6334 arch_emit_autoreg (acfg, symbol);
6340 emit_mem_end (MonoAotCompile *acfg)
6344 sprintf (symbol, "mem_end");
6345 emit_section_change (acfg, ".text", 1);
6346 emit_alignment (acfg, 8);
6347 emit_label (acfg, symbol);
6351 * Emit a structure containing all the information not stored elsewhere.
6354 emit_file_info (MonoAotCompile *acfg)
6359 const char *gc_name;
6362 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6364 if (acfg->aot_opts.bind_to_runtime_version) {
6365 build_info = mono_get_runtime_build_info ();
6366 emit_string_symbol (acfg, "runtime_version", build_info);
6367 g_free (build_info);
6369 emit_string_symbol (acfg, "runtime_version", "");
6372 /* Emit a string holding the assembly name */
6373 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6376 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6379 gc_name = mono_gc_get_gc_name ();
6380 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6382 sprintf (symbol, "mono_aot_file_info");
6383 emit_section_change (acfg, ".data", 0);
6384 emit_alignment (acfg, 8);
6385 emit_label (acfg, symbol);
6386 if (!acfg->aot_opts.static_link)
6387 emit_global (acfg, symbol, FALSE);
6389 /* The data emitted here must match MonoAotFileInfo. */
6391 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6392 emit_int32 (acfg, 0);
6395 * We emit pointers to our data structures instead of emitting global symbols which
6396 * point to them, to reduce the number of globals, and because using globals leads to
6397 * various problems (i.e. arm/thumb).
6399 emit_pointer (acfg, acfg->got_symbol);
6400 emit_pointer (acfg, "methods");
6403 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6405 emit_pointer (acfg, "mono_eh_frame");
6407 emit_pointer (acfg, NULL);
6409 emit_pointer (acfg, "blob");
6410 emit_pointer (acfg, "class_name_table");
6411 emit_pointer (acfg, "class_info_offsets");
6412 emit_pointer (acfg, "method_info_offsets");
6413 emit_pointer (acfg, "ex_info_offsets");
6414 emit_pointer (acfg, "code_offsets");
6415 emit_pointer (acfg, "extra_method_info_offsets");
6416 emit_pointer (acfg, "extra_method_table");
6417 emit_pointer (acfg, "got_info_offsets");
6418 emit_pointer (acfg, "methods_end");
6419 emit_pointer (acfg, "unwind_info");
6420 emit_pointer (acfg, "mem_end");
6421 emit_pointer (acfg, "image_table");
6422 emit_pointer (acfg, "plt");
6423 emit_pointer (acfg, "plt_end");
6424 emit_pointer (acfg, "assembly_guid");
6425 emit_pointer (acfg, "runtime_version");
6426 if (acfg->num_trampoline_got_entries) {
6427 emit_pointer (acfg, "specific_trampolines");
6428 emit_pointer (acfg, "static_rgctx_trampolines");
6429 emit_pointer (acfg, "imt_thunks");
6431 emit_pointer (acfg, NULL);
6432 emit_pointer (acfg, NULL);
6433 emit_pointer (acfg, NULL);
6435 if (acfg->thumb_mixed) {
6436 emit_pointer (acfg, "thumb_end");
6438 emit_pointer (acfg, NULL);
6440 if (acfg->aot_opts.static_link) {
6441 emit_pointer (acfg, "globals");
6443 emit_pointer (acfg, NULL);
6445 emit_pointer (acfg, "assembly_name");
6447 emit_int32 (acfg, acfg->plt_got_offset_base);
6448 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6449 emit_int32 (acfg, acfg->plt_offset);
6450 emit_int32 (acfg, acfg->nmethods);
6451 emit_int32 (acfg, acfg->flags);
6452 emit_int32 (acfg, acfg->opts);
6453 emit_int32 (acfg, gc_name_offset);
6455 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6456 emit_int32 (acfg, acfg->num_trampolines [i]);
6457 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6458 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6459 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6460 emit_int32 (acfg, acfg->trampoline_size [i]);
6462 #if defined (TARGET_ARM) && defined (__APPLE__)
6467 t.type = MONO_TYPE_R8;
6468 mono_type_size (&t, &align);
6470 emit_int32 (acfg, align);
6472 t.type = MONO_TYPE_I8;
6473 mono_type_size (&t, &align);
6475 emit_int32 (acfg, align);
6478 emit_int32 (acfg, __alignof__ (double));
6479 emit_int32 (acfg, __alignof__ (gint64));
6482 if (acfg->aot_opts.static_link) {
6486 * Emit a global symbol which can be passed by an embedding app to
6487 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6490 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6491 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6493 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6496 /* Get rid of characters which cannot occur in symbols */
6498 for (p = symbol; *p; ++p) {
6499 if (!(isalnum (*p) || *p == '_'))
6502 acfg->static_linking_symbol = g_strdup (symbol);
6503 emit_global_inner (acfg, symbol, FALSE);
6504 emit_label (acfg, symbol);
6505 emit_pointer (acfg, "mono_aot_file_info");
6510 emit_blob (MonoAotCompile *acfg)
6514 sprintf (symbol, "blob");
6515 emit_section_change (acfg, RODATA_SECT, 1);
6516 emit_alignment (acfg, 8);
6517 emit_label (acfg, symbol);
6519 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6523 emit_dwarf_info (MonoAotCompile *acfg)
6525 #ifdef EMIT_DWARF_INFO
6527 char symbol [128], symbol2 [128];
6529 /* DIEs for methods */
6530 for (i = 0; i < acfg->nmethods; ++i) {
6531 MonoCompile *cfg = acfg->cfgs [i];
6536 // FIXME: LLVM doesn't define .Lme_...
6537 if (cfg->compile_llvm)
6540 sprintf (symbol, "%s", cfg->asm_symbol);
6541 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6543 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 ()));
6549 collect_methods (MonoAotCompile *acfg)
6552 MonoImage *image = acfg->image;
6554 /* Collect methods */
6555 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6557 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6559 method = mono_get_method (acfg->image, token, NULL);
6562 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6566 /* Load all methods eagerly to skip the slower lazy loading code */
6567 mono_class_setup_methods (method->klass);
6569 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6570 /* Compile the wrapper instead */
6571 /* We do this here instead of add_wrappers () because it is easy to do it here */
6572 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6576 /* FIXME: Some mscorlib methods don't have debug info */
6578 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6579 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6580 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6581 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6582 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6583 if (!mono_debug_lookup_method (method)) {
6584 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6591 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6592 add_method_with_index (acfg, method, i, FALSE);
6593 acfg->method_index ++;
6596 add_generic_instances (acfg);
6598 if (acfg->aot_opts.full_aot)
6599 add_wrappers (acfg);
6603 compile_methods (MonoAotCompile *acfg)
6607 if (acfg->aot_opts.nthreads > 0) {
6612 gpointer *user_data;
6613 MonoMethod **methods;
6615 methods_len = acfg->methods->len;
6617 len = acfg->methods->len / acfg->aot_opts.nthreads;
6620 * Partition the list of methods into fragments, and hand it to threads to
6623 threads = g_ptr_array_new ();
6624 /* Make a copy since acfg->methods is modified by compile_method () */
6625 methods = g_new0 (MonoMethod*, methods_len);
6626 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6627 for (i = 0; i < methods_len; ++i)
6628 methods [i] = g_ptr_array_index (acfg->methods, i);
6630 while (i < methods_len) {
6631 frag = g_ptr_array_new ();
6632 for (j = 0; j < len; ++j) {
6633 if (i < methods_len) {
6634 g_ptr_array_add (frag, methods [i]);
6639 user_data = g_new0 (gpointer, 3);
6640 user_data [0] = mono_domain_get ();
6641 user_data [1] = acfg;
6642 user_data [2] = frag;
6644 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6645 g_ptr_array_add (threads, handle);
6649 for (i = 0; i < threads->len; ++i) {
6650 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6656 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6657 for (i = methods_len; i < acfg->methods->len; ++i) {
6658 /* This can new methods to acfg->methods */
6659 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6664 compile_asm (MonoAotCompile *acfg)
6666 char *command, *objfile;
6667 char *outfile_name, *tmp_outfile_name;
6668 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6670 #if defined(TARGET_AMD64)
6671 #define AS_OPTIONS "--64"
6672 #elif defined(TARGET_POWERPC64)
6673 #define AS_OPTIONS "-a64 -mppc64"
6674 #define LD_OPTIONS "-m elf64ppc"
6675 #elif defined(sparc) && SIZEOF_VOID_P == 8
6676 #define AS_OPTIONS "-xarch=v9"
6677 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6678 #define AS_OPTIONS "-arch i386 -W"
6680 #define AS_OPTIONS ""
6683 #ifdef __native_client_codegen__
6684 #if defined(TARGET_AMD64)
6685 #define AS_NAME "nacl64-as"
6687 #define AS_NAME "nacl-as"
6690 #define AS_NAME "as"
6694 #define LD_OPTIONS ""
6697 #define EH_LD_OPTIONS ""
6699 if (acfg->aot_opts.asm_only) {
6700 printf ("Output file: '%s'.\n", acfg->tmpfname);
6701 if (acfg->aot_opts.static_link)
6702 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6706 if (acfg->aot_opts.static_link) {
6707 if (acfg->aot_opts.outfile)
6708 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6710 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6712 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6714 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
6715 printf ("Executing the native assembler: %s\n", command);
6716 if (system (command) != 0) {
6724 if (acfg->aot_opts.static_link) {
6725 printf ("Output file: '%s'.\n", objfile);
6726 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6731 if (acfg->aot_opts.outfile)
6732 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6734 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6736 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6739 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6740 #elif defined(__ppc__) && defined(__APPLE__)
6741 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6742 #elif defined(HOST_WIN32)
6743 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6744 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6745 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6747 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6749 printf ("Executing the native linker: %s\n", command);
6750 if (system (command) != 0) {
6751 g_free (tmp_outfile_name);
6752 g_free (outfile_name);
6760 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6761 printf ("Stripping the binary: %s\n", com);
6765 #if defined(TARGET_ARM) && !defined(__APPLE__)
6767 * gas generates 'mapping symbols' each time code and data is mixed, which
6768 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6770 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6771 printf ("Stripping the binary: %s\n", command);
6772 if (system (command) != 0) {
6773 g_free (tmp_outfile_name);
6774 g_free (outfile_name);
6781 rename (tmp_outfile_name, outfile_name);
6783 g_free (tmp_outfile_name);
6784 g_free (outfile_name);
6787 if (acfg->aot_opts.save_temps)
6788 printf ("Retained input file.\n");
6790 unlink (acfg->tmpfname);
6795 static MonoAotCompile*
6796 acfg_create (MonoAssembly *ass, guint32 opts)
6798 MonoImage *image = ass->image;
6799 MonoAotCompile *acfg;
6802 acfg = g_new0 (MonoAotCompile, 1);
6803 acfg->methods = g_ptr_array_new ();
6804 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6805 acfg->method_depth = g_hash_table_new (NULL, NULL);
6806 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6807 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6808 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6809 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6810 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6811 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6812 acfg->got_patches = g_ptr_array_new ();
6813 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6814 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6815 acfg->image_hash = g_hash_table_new (NULL, NULL);
6816 acfg->image_table = g_ptr_array_new ();
6817 acfg->globals = g_ptr_array_new ();
6818 acfg->image = image;
6820 acfg->mempool = mono_mempool_new ();
6821 acfg->extra_methods = g_ptr_array_new ();
6822 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6823 acfg->unwind_ops = g_ptr_array_new ();
6824 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6825 acfg->method_order = g_ptr_array_new ();
6826 InitializeCriticalSection (&acfg->mutex);
6832 acfg_free (MonoAotCompile *acfg)
6836 img_writer_destroy (acfg->w);
6837 for (i = 0; i < acfg->nmethods; ++i)
6839 g_free (acfg->cfgs [i]);
6840 g_free (acfg->cfgs);
6841 g_free (acfg->static_linking_symbol);
6842 g_free (acfg->got_symbol);
6843 g_free (acfg->plt_symbol);
6844 g_ptr_array_free (acfg->methods, TRUE);
6845 g_ptr_array_free (acfg->got_patches, TRUE);
6846 g_ptr_array_free (acfg->image_table, TRUE);
6847 g_ptr_array_free (acfg->globals, TRUE);
6848 g_ptr_array_free (acfg->unwind_ops, TRUE);
6849 g_hash_table_destroy (acfg->method_indexes);
6850 g_hash_table_destroy (acfg->method_depth);
6851 g_hash_table_destroy (acfg->plt_offset_to_entry);
6852 g_hash_table_destroy (acfg->patch_to_plt_entry);
6853 g_hash_table_destroy (acfg->patch_to_got_offset);
6854 g_hash_table_destroy (acfg->method_to_cfg);
6855 g_hash_table_destroy (acfg->token_info_hash);
6856 g_hash_table_destroy (acfg->image_hash);
6857 g_hash_table_destroy (acfg->unwind_info_offsets);
6858 g_hash_table_destroy (acfg->method_label_hash);
6859 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6860 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6861 g_free (acfg->patch_to_got_offset_by_type);
6862 mono_mempool_destroy (acfg->mempool);
6867 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6869 MonoImage *image = ass->image;
6871 MonoAotCompile *acfg;
6872 char *outfile_name, *tmp_outfile_name, *p;
6876 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6878 acfg = acfg_create (ass, opts);
6880 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6881 acfg->aot_opts.write_symbols = TRUE;
6882 acfg->aot_opts.ntrampolines = 1024;
6883 acfg->aot_opts.nrgctx_trampolines = 1024;
6884 acfg->aot_opts.nimt_trampolines = 128;
6885 acfg->aot_opts.llvm_path = g_strdup ("");
6887 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6889 if (acfg->aot_opts.static_link)
6890 acfg->aot_opts.autoreg = TRUE;
6892 //acfg->aot_opts.print_skipped_methods = TRUE;
6894 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6895 if (acfg->aot_opts.full_aot) {
6896 printf ("--aot=full is not supported on this platform.\n");
6901 if (acfg->aot_opts.static_link)
6902 acfg->aot_opts.asm_writer = TRUE;
6904 if (acfg->aot_opts.soft_debug) {
6905 MonoDebugOptions *opt = mini_get_debug_options ();
6907 opt->mdb_optimizations = TRUE;
6908 opt->gen_seq_points = TRUE;
6910 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6911 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6914 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6917 if (mono_use_llvm) {
6919 acfg->aot_opts.asm_writer = TRUE;
6920 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6922 if (acfg->aot_opts.soft_debug) {
6923 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6928 if (acfg->aot_opts.full_aot)
6929 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6931 load_profile_files (acfg);
6933 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6934 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6935 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6937 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6939 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6943 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6944 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6946 /* Get rid of characters which cannot occur in symbols */
6947 for (p = acfg->got_symbol_base; *p; ++p) {
6948 if (!(isalnum (*p) || *p == '_'))
6951 for (p = acfg->plt_symbol; *p; ++p) {
6952 if (!(isalnum (*p) || *p == '_'))
6956 acfg->method_index = 1;
6958 collect_methods (acfg);
6960 acfg->cfgs_size = acfg->methods->len + 32;
6961 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6963 /* PLT offset 0 is reserved for the PLT trampoline */
6964 acfg->plt_offset = 1;
6969 mono_llvm_create_aot_module (acfg->got_symbol_base);
6973 /* GOT offset 0 is reserved for the address of the current assembly */
6977 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6978 ji->type = MONO_PATCH_INFO_IMAGE;
6979 ji->data.image = acfg->image;
6981 get_got_offset (acfg, ji);
6983 /* Slot 1 is reserved for the mscorlib got addr */
6984 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6985 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6986 get_got_offset (acfg, ji);
6988 /* This is very common */
6989 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6990 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6991 get_got_offset (acfg, ji);
6996 compile_methods (acfg);
7000 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7006 if (acfg->aot_opts.asm_only) {
7007 if (acfg->aot_opts.outfile)
7008 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7010 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7012 acfg->tmpfname = g_strdup ("temp.s");
7015 emit_llvm_file (acfg);
7019 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7020 if (acfg->aot_opts.outfile)
7021 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7023 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7026 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7027 * it might be in another file system so the rename () won't work.
7029 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7031 acfg->fp = fopen (tmp_outfile_name, "w");
7033 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7037 acfg->w = img_writer_create (acfg->fp, TRUE);
7038 acfg->use_bin_writer = TRUE;
7041 /* Append to the .s file created by llvm */
7042 /* FIXME: Use multiple files instead */
7043 acfg->fp = fopen (acfg->tmpfname, "a+");
7045 if (acfg->aot_opts.asm_only) {
7046 if (acfg->aot_opts.outfile)
7047 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7049 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7050 acfg->fp = fopen (acfg->tmpfname, "w+");
7052 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7053 acfg->fp = fdopen (i, "w+");
7055 g_assert (acfg->fp);
7057 acfg->w = img_writer_create (acfg->fp, FALSE);
7059 tmp_outfile_name = NULL;
7060 outfile_name = NULL;
7063 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7065 /* Compute symbols for methods */
7066 for (i = 0; i < acfg->nmethods; ++i) {
7067 if (acfg->cfgs [i]) {
7068 MonoCompile *cfg = acfg->cfgs [i];
7069 int method_index = get_method_index (acfg, cfg->orig_method);
7071 if (COMPILE_LLVM (cfg))
7072 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7074 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7078 if (!acfg->aot_opts.nodebug)
7079 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7081 img_writer_emit_start (acfg->w);
7084 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7086 if (acfg->thumb_mixed) {
7089 * This global symbol marks the end of THUMB code, and the beginning of ARM
7090 * code generated by our JIT.
7092 sprintf (symbol, "thumb_end");
7093 emit_section_change (acfg, ".text", 0);
7094 emit_label (acfg, symbol);
7095 emit_zero_bytes (acfg, 16);
7097 fprintf (acfg->fp, ".arm\n");
7104 emit_extra_methods (acfg);
7106 emit_trampolines (acfg);
7108 emit_class_name_table (acfg);
7110 emit_got_info (acfg);
7112 emit_exception_info (acfg);
7114 emit_unwind_info (acfg);
7116 emit_class_info (acfg);
7120 emit_image_table (acfg);
7124 emit_file_info (acfg);
7128 emit_globals (acfg);
7130 emit_autoreg (acfg);
7133 emit_dwarf_info (acfg);
7134 mono_dwarf_writer_close (acfg->dwarf);
7137 emit_mem_end (acfg);
7139 if (acfg->need_pt_gnu_stack) {
7140 /* This is required so the .so doesn't have an executable stack */
7141 /* The bin writer already emits this */
7142 if (!acfg->use_bin_writer)
7143 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7148 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7151 g_assert (acfg->got_offset <= acfg->final_got_size);
7153 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);
7156 res = img_writer_emit_writeout (acfg->w);
7161 if (acfg->use_bin_writer) {
7162 int err = rename (tmp_outfile_name, outfile_name);
7165 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7169 res = compile_asm (acfg);
7176 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7178 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);
7179 if (acfg->stats.genericcount)
7180 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7181 if (acfg->stats.abscount)
7182 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7183 if (acfg->stats.lmfcount)
7184 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7185 if (acfg->stats.ocount)
7186 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7188 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7189 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);
7190 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7192 if (acfg->aot_opts.stats) {
7195 printf ("GOT slot distribution:\n");
7196 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7197 if (acfg->stats.got_slot_types [i])
7198 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7201 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);
7213 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)