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_MONO_ENTER, p, &p);
2052 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2053 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2054 } else if (strcmp (method->name, "PtrToStructure") == 0) {
2055 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2056 encode_klass_ref (acfg, method->klass, p, &p);
2057 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2058 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2059 encode_klass_ref (acfg, method->klass, p, &p);
2061 g_assert_not_reached ();
2064 case MONO_WRAPPER_SYNCHRONIZED:
2065 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2066 case MONO_WRAPPER_RUNTIME_INVOKE: {
2069 m = mono_marshal_method_from_wrapper (method);
2071 g_assert (m != method);
2072 encode_method_ref (acfg, m, p, &p);
2075 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2076 if (!strcmp (method->name, "ElementAddr")) {
2077 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2080 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2081 encode_value (info->rank, p, &p);
2082 encode_value (info->elem_size, p, &p);
2084 g_assert_not_reached ();
2087 case MONO_WRAPPER_CASTCLASS:
2088 if (!strcmp (method->name, "__castclass_with_cache")) {
2089 encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
2090 } else if (!strcmp (method->name, "__isinst_with_cache")) {
2091 encode_value (MONO_AOT_WRAPPER_ISINST_WITH_CACHE, p, &p);
2093 g_assert_not_reached ();
2097 g_assert_not_reached ();
2099 } else if (mono_method_signature (method)->is_inflated) {
2101 * This is a generic method, find the original token which referenced it and
2103 * Obtain the token from information recorded by the JIT.
2105 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2107 image_index = get_image_index (acfg, ji->image);
2108 g_assert (image_index < MAX_IMAGE_INDEX);
2111 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2112 encode_value (image_index, p, &p);
2113 encode_value (token, p, &p);
2115 MonoMethod *declaring;
2116 MonoGenericContext *context = mono_method_get_context (method);
2118 g_assert (method->is_inflated);
2119 declaring = ((MonoMethodInflated*)method)->declaring;
2122 * This might be a non-generic method of a generic instance, which
2123 * doesn't have a token since the reference is generated by the JIT
2124 * like Nullable:Box/Unbox, or by generic sharing.
2127 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2128 /* Encode the klass */
2129 encode_klass_ref (acfg, method->klass, p, &p);
2130 /* Encode the method */
2131 image_index = get_image_index (acfg, method->klass->image);
2132 g_assert (image_index < MAX_IMAGE_INDEX);
2133 g_assert (declaring->token);
2134 token = declaring->token;
2135 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2136 encode_value (image_index, p, &p);
2137 encode_value (token, p, &p);
2138 encode_generic_context (acfg, context, p, &p);
2140 } else if (token == 0) {
2141 /* This might be a method of a constructed type like int[,].Set */
2142 /* Obtain the token from information recorded by the JIT */
2143 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2145 image_index = get_image_index (acfg, ji->image);
2146 g_assert (image_index < MAX_IMAGE_INDEX);
2149 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2150 encode_value (image_index, p, &p);
2151 encode_value (token, p, &p);
2154 g_assert (method->klass->rank);
2156 /* Encode directly */
2157 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2158 encode_klass_ref (acfg, method->klass, p, &p);
2159 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2160 encode_value (0, p, &p);
2161 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2162 encode_value (1, p, &p);
2163 else if (!strcmp (method->name, "Get"))
2164 encode_value (2, p, &p);
2165 else if (!strcmp (method->name, "Address"))
2166 encode_value (3, p, &p);
2167 else if (!strcmp (method->name, "Set"))
2168 encode_value (4, p, &p);
2170 g_assert_not_reached ();
2173 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2174 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2180 compare_patches (gconstpointer a, gconstpointer b)
2184 i = (*(MonoJumpInfo**)a)->ip.i;
2185 j = (*(MonoJumpInfo**)b)->ip.i;
2196 static G_GNUC_UNUSED char*
2197 patch_to_string (MonoJumpInfo *patch_info)
2201 str = g_string_new ("");
2203 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2205 switch (patch_info->type) {
2206 case MONO_PATCH_INFO_VTABLE:
2207 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2212 g_string_append_printf (str, ")");
2213 return g_string_free (str, FALSE);
2219 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2222 static inline gboolean
2223 is_plt_patch (MonoJumpInfo *patch_info)
2225 switch (patch_info->type) {
2226 case MONO_PATCH_INFO_METHOD:
2227 case MONO_PATCH_INFO_INTERNAL_METHOD:
2228 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2229 case MONO_PATCH_INFO_ICALL_ADDR:
2230 case MONO_PATCH_INFO_CLASS_INIT:
2231 case MONO_PATCH_INFO_RGCTX_FETCH:
2232 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2233 case MONO_PATCH_INFO_MONITOR_ENTER:
2234 case MONO_PATCH_INFO_MONITOR_EXIT:
2235 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2245 * Return the symbol identifying the plt entry PLT_OFFSET.
2248 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2252 * The Apple linker reorganizes object files, so it doesn't like branches to local
2253 * labels, since those have no relocations.
2255 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2257 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2264 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2266 static MonoPltEntry*
2267 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2271 if (!is_plt_patch (patch_info))
2274 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2276 // FIXME: This breaks the calculation of final_got_size
2277 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2279 * Allocate a separate PLT slot for each such patch, since some plt
2280 * entries will refer to the method itself, and some will refer to the
2287 MonoJumpInfo *new_ji;
2289 g_assert (!acfg->final_got_size);
2291 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2293 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2294 res->plt_offset = acfg->plt_offset;
2296 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2297 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2299 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2301 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2303 acfg->plt_offset ++;
2312 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2313 * JI could be found if it exists, otherwise allocates a new one.
2316 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2320 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2322 return got_offset - 1;
2324 got_offset = acfg->got_offset;
2325 acfg->got_offset ++;
2327 if (acfg->final_got_size)
2328 g_assert (got_offset < acfg->final_got_size);
2330 acfg->stats.got_slots ++;
2331 acfg->stats.got_slot_types [ji->type] ++;
2333 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2334 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2335 g_ptr_array_add (acfg->got_patches, ji);
2340 /* Add a method to the list of methods which need to be emitted */
2342 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2345 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2346 g_ptr_array_add (acfg->methods, method);
2347 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2348 acfg->nmethods = acfg->methods->len + 1;
2351 if (method->wrapper_type || extra)
2352 g_ptr_array_add (acfg->extra_methods, method);
2356 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2358 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2366 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2370 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2374 index = acfg->method_index;
2375 add_method_with_index (acfg, method, index, extra);
2377 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2379 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2381 acfg->method_index ++;
2387 add_method (MonoAotCompile *acfg, MonoMethod *method)
2389 return add_method_full (acfg, method, FALSE, 0);
2393 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2395 add_method_full (acfg, method, TRUE, 0);
2399 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2401 add_method_full (acfg, method, TRUE, depth);
2405 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2407 MonoAotCompile *acfg = user_data;
2408 MonoJitICallInfo *callinfo = value;
2409 MonoMethod *wrapper;
2415 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2416 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2419 add_method (acfg, wrapper);
2423 get_runtime_invoke_sig (MonoMethodSignature *sig)
2425 MonoMethodBuilder *mb;
2428 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2429 m = mono_mb_create_method (mb, sig, 16);
2430 return mono_marshal_get_runtime_invoke (m, FALSE);
2434 can_marshal_struct (MonoClass *klass)
2436 MonoClassField *field;
2437 gboolean can_marshal = TRUE;
2438 gpointer iter = NULL;
2440 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2443 /* Only allow a few field types to avoid asserts in the marshalling code */
2444 while ((field = mono_class_get_fields (klass, &iter))) {
2445 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2448 switch (field->type->type) {
2453 case MONO_TYPE_BOOLEAN:
2456 case MONO_TYPE_CHAR:
2464 case MONO_TYPE_STRING:
2466 case MONO_TYPE_VALUETYPE:
2467 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2468 can_marshal = FALSE;
2471 can_marshal = FALSE;
2477 /* Its hard to compute whenever these can be marshalled or not */
2478 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2485 add_wrappers (MonoAotCompile *acfg)
2487 MonoMethod *method, *m;
2489 MonoMethodSignature *sig, *csig;
2493 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2494 * so there is only one wrapper of a given type, or inlining their contents into their
2499 * FIXME: This depends on the fact that different wrappers have different
2503 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2505 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2506 gboolean skip = FALSE;
2508 method = mono_get_method (acfg->image, token, NULL);
2510 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2511 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2512 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2515 if (method->is_generic || method->klass->generic_container)
2518 /* Skip methods which can not be handled by get_runtime_invoke () */
2519 sig = mono_method_signature (method);
2522 if ((sig->ret->type == MONO_TYPE_PTR) ||
2523 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2526 for (j = 0; j < sig->param_count; j++) {
2527 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2531 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2532 if (!method->klass->contextbound) {
2533 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2534 gboolean has_nullable = FALSE;
2536 for (j = 0; j < sig->param_count; j++) {
2537 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2538 has_nullable = TRUE;
2541 if (info && !has_nullable) {
2542 /* Supported by the dynamic runtime-invoke wrapper */
2550 //printf ("%s\n", mono_method_full_name (method, TRUE));
2551 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2555 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2556 #ifdef MONO_ARCH_HAVE_TLS_GET
2557 MonoMethodDesc *desc;
2558 MonoMethod *orig_method;
2562 /* Runtime invoke wrappers */
2564 /* void runtime-invoke () [.cctor] */
2565 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2566 csig->ret = &mono_defaults.void_class->byval_arg;
2567 add_method (acfg, get_runtime_invoke_sig (csig));
2569 /* void runtime-invoke () [Finalize] */
2570 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2572 csig->ret = &mono_defaults.void_class->byval_arg;
2573 add_method (acfg, get_runtime_invoke_sig (csig));
2575 /* void runtime-invoke (string) [exception ctor] */
2576 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2578 csig->ret = &mono_defaults.void_class->byval_arg;
2579 csig->params [0] = &mono_defaults.string_class->byval_arg;
2580 add_method (acfg, get_runtime_invoke_sig (csig));
2582 /* void runtime-invoke (string, string) [exception ctor] */
2583 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2585 csig->ret = &mono_defaults.void_class->byval_arg;
2586 csig->params [0] = &mono_defaults.string_class->byval_arg;
2587 csig->params [1] = &mono_defaults.string_class->byval_arg;
2588 add_method (acfg, get_runtime_invoke_sig (csig));
2590 /* string runtime-invoke () [Exception.ToString ()] */
2591 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2593 csig->ret = &mono_defaults.string_class->byval_arg;
2594 add_method (acfg, get_runtime_invoke_sig (csig));
2596 /* void runtime-invoke (string, Exception) [exception ctor] */
2597 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2599 csig->ret = &mono_defaults.void_class->byval_arg;
2600 csig->params [0] = &mono_defaults.string_class->byval_arg;
2601 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2602 add_method (acfg, get_runtime_invoke_sig (csig));
2604 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2605 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2607 csig->ret = &(mono_class_from_name (
2608 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2609 csig->params [0] = &mono_defaults.string_class->byval_arg;
2610 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2611 add_method (acfg, get_runtime_invoke_sig (csig));
2613 /* runtime-invoke used by finalizers */
2614 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2616 /* This is used by mono_runtime_capture_context () */
2617 method = mono_get_context_capture_method ();
2619 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2621 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2622 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2625 /* JIT icall wrappers */
2626 /* FIXME: locking */
2627 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2630 add_method (acfg, mono_marshal_get_stelemref ());
2632 #ifdef MONO_ARCH_HAVE_TLS_GET
2633 /* Managed Allocators */
2634 nallocators = mono_gc_get_managed_allocator_types ();
2635 for (i = 0; i < nallocators; ++i) {
2636 m = mono_gc_get_managed_allocator_by_type (i);
2638 add_method (acfg, m);
2641 /* Monitor Enter/Exit */
2642 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2643 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2644 g_assert (orig_method);
2645 mono_method_desc_free (desc);
2646 method = mono_monitor_get_fast_path (orig_method);
2648 add_method (acfg, method);
2650 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2651 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2652 g_assert (orig_method);
2653 mono_method_desc_free (desc);
2654 method = mono_monitor_get_fast_path (orig_method);
2656 add_method (acfg, method);
2659 /* Stelemref wrappers */
2660 /* There is only a constant number of these, iterating over all types should handle them all */
2661 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2664 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2665 klass = mono_class_get (acfg->image, token);
2667 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2669 mono_loader_clear_error ();
2672 /* castclass_with_check wrapper */
2673 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2674 /* isinst_with_check wrapper */
2675 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2679 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2680 * we use the original method instead at runtime.
2681 * Since full-aot doesn't support remoting, this is not a problem.
2684 /* remoting-invoke wrappers */
2685 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2686 MonoMethodSignature *sig;
2688 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2689 method = mono_get_method (acfg->image, token, NULL);
2691 sig = mono_method_signature (method);
2693 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2694 m = mono_marshal_get_remoting_invoke_with_check (method);
2696 add_method (acfg, m);
2701 /* delegate-invoke wrappers */
2702 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2705 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2706 klass = mono_class_get (acfg->image, token);
2709 mono_loader_clear_error ();
2713 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2714 method = mono_get_delegate_invoke (klass);
2716 m = mono_marshal_get_delegate_invoke (method, NULL);
2718 add_method (acfg, m);
2720 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2721 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2723 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2724 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2728 /* Synchronized wrappers */
2729 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2730 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2731 method = mono_get_method (acfg->image, token, NULL);
2733 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2734 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2737 /* pinvoke wrappers */
2738 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2740 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2742 method = mono_get_method (acfg->image, token, NULL);
2744 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2745 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2746 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2750 /* native-to-managed wrappers */
2751 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2753 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2754 MonoCustomAttrInfo *cattr;
2757 method = mono_get_method (acfg->image, token, NULL);
2760 * Only generate native-to-managed wrappers for methods which have an
2761 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2762 * name to avoid defining a new assembly to contain it.
2764 cattr = mono_custom_attrs_from_method (method);
2767 for (j = 0; j < cattr->num_attrs; ++j)
2768 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2770 if (j < cattr->num_attrs) {
2771 MonoCustomAttrEntry *e = &cattr->attrs [j];
2772 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2773 const char *p = (const char*)e->data;
2779 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2781 g_assert (sig->param_count == 1);
2782 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2785 * Decode the cattr manually since we can't create objects
2786 * during aot compilation.
2792 /* From load_cattr_value () in reflection.c */
2793 slen = mono_metadata_decode_value (p, &p);
2794 n = g_memdup (p, slen + 1);
2796 t = mono_reflection_type_from_name (n, acfg->image);
2800 klass = mono_class_from_mono_type (t);
2801 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2803 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2807 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2808 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2809 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2813 /* StructureToPtr/PtrToStructure wrappers */
2814 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2817 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2818 klass = mono_class_get (acfg->image, token);
2821 mono_loader_clear_error ();
2825 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2826 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2827 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2833 has_type_vars (MonoClass *klass)
2835 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2838 return has_type_vars (klass->element_class);
2839 if (klass->generic_class) {
2840 MonoGenericContext *context = &klass->generic_class->context;
2841 if (context->class_inst) {
2844 for (i = 0; i < context->class_inst->type_argc; ++i)
2845 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2853 method_has_type_vars (MonoMethod *method)
2855 if (has_type_vars (method->klass))
2858 if (method->is_inflated) {
2859 MonoGenericContext *context = mono_method_get_context (method);
2860 if (context->method_inst) {
2863 for (i = 0; i < context->method_inst->type_argc; ++i)
2864 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2871 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2874 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2876 /* This might lead to a huge code blowup so only do it if neccesary */
2877 if (!acfg->aot_opts.full_aot && !force)
2880 add_generic_class_with_depth (acfg, klass, 0);
2884 check_type_depth (MonoType *t, int depth)
2892 case MONO_TYPE_GENERICINST: {
2893 MonoGenericClass *gklass = t->data.generic_class;
2894 MonoGenericInst *ginst = gklass->context.class_inst;
2897 for (i = 0; i < ginst->type_argc; ++i) {
2898 if (check_type_depth (ginst->type_argv [i], depth + 1))
2912 * add_generic_class:
2914 * Add all methods of a generic class.
2917 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2922 mono_class_init (klass);
2924 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2927 if (has_type_vars (klass))
2930 if (!klass->generic_class && !klass->rank)
2933 if (check_type_depth (&klass->byval_arg, 0))
2937 while ((method = mono_class_get_methods (klass, &iter))) {
2938 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2942 if (method->is_generic)
2947 * FIXME: Instances which are referenced by these methods are not added,
2948 * for example Array.Resize<int> for List<int>.Add ().
2950 add_extra_method_with_depth (acfg, method, depth + 1);
2953 if (klass->delegate) {
2954 method = mono_get_delegate_invoke (klass);
2956 method = mono_marshal_get_delegate_invoke (method, NULL);
2958 add_method (acfg, method);
2962 * For ICollection<T>, add instances of the helper methods
2963 * in Array, since a T[] could be cast to ICollection<T>.
2965 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2966 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2967 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2968 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2972 if (!strcmp (klass->name, "IEnumerator`1"))
2973 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2975 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2977 /* Add the T[]/InternalEnumerator class */
2978 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2982 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2983 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2987 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2988 add_generic_class (acfg, nclass, FALSE);
2992 while ((method = mono_class_get_methods (array_class, &iter))) {
2993 if (strstr (method->name, name_prefix)) {
2994 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2995 add_extra_method_with_depth (acfg, m, depth);
2999 g_free (name_prefix);
3002 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3003 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3004 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3005 MonoClass *icomparable, *gcomparer;
3006 MonoGenericContext ctx;
3007 MonoType *args [16];
3009 memset (&ctx, 0, sizeof (ctx));
3011 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3012 g_assert (icomparable);
3013 args [0] = &tclass->byval_arg;
3014 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3016 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3017 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3018 g_assert (gcomparer);
3019 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3023 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3024 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3025 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3026 MonoClass *iface, *gcomparer;
3027 MonoGenericContext ctx;
3028 MonoType *args [16];
3030 memset (&ctx, 0, sizeof (ctx));
3032 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3034 args [0] = &tclass->byval_arg;
3035 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3037 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3038 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3039 g_assert (gcomparer);
3040 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3046 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3049 MonoGenericContext ctx;
3050 MonoType *args [16];
3052 memset (&ctx, 0, sizeof (ctx));
3054 for (i = 0; i < ninsts; ++i) {
3055 args [0] = insts [i];
3056 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3057 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3062 * add_generic_instances:
3064 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3067 add_generic_instances (MonoAotCompile *acfg)
3072 MonoMethodHeader *header;
3073 MonoMethodSignature *sig;
3074 MonoGenericContext *context;
3076 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3077 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3078 method = mono_get_method (acfg->image, token, NULL);
3083 if (method->klass->image != acfg->image)
3086 context = mono_method_get_context (method);
3088 if (context && ((context->class_inst && context->class_inst->is_open)))
3092 * For open methods, create an instantiation which can be passed to the JIT.
3093 * FIXME: Handle class_inst as well.
3095 if (context && context->method_inst && context->method_inst->is_open) {
3096 MonoGenericContext shared_context;
3097 MonoGenericInst *inst;
3098 MonoType **type_argv;
3100 MonoMethod *declaring_method;
3101 gboolean supported = TRUE;
3103 /* Check that the context doesn't contain open constructed types */
3104 if (context->class_inst) {
3105 inst = context->class_inst;
3106 for (i = 0; i < inst->type_argc; ++i) {
3107 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)
3109 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3113 if (context->method_inst) {
3114 inst = context->method_inst;
3115 for (i = 0; i < inst->type_argc; ++i) {
3116 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)
3118 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3126 memset (&shared_context, 0, sizeof (MonoGenericContext));
3128 inst = context->class_inst;
3130 type_argv = g_new0 (MonoType*, inst->type_argc);
3131 for (i = 0; i < inst->type_argc; ++i) {
3132 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)
3133 type_argv [i] = &mono_defaults.object_class->byval_arg;
3135 type_argv [i] = inst->type_argv [i];
3138 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3142 inst = context->method_inst;
3144 type_argv = g_new0 (MonoType*, inst->type_argc);
3145 for (i = 0; i < inst->type_argc; ++i) {
3146 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)
3147 type_argv [i] = &mono_defaults.object_class->byval_arg;
3149 type_argv [i] = inst->type_argv [i];
3152 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3156 if (method->is_generic || method->klass->generic_container)
3157 declaring_method = method;
3159 declaring_method = mono_method_get_declaring_generic_method (method);
3161 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3165 * If the method is fully sharable, it was already added in place of its
3166 * generic definition.
3168 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3172 * FIXME: Partially shared methods are not shared here, so we end up with
3173 * many identical methods.
3175 add_extra_method (acfg, method);
3178 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3181 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3183 klass = mono_class_get (acfg->image, token);
3184 if (!klass || klass->rank) {
3185 mono_loader_clear_error ();
3189 add_generic_class (acfg, klass, FALSE);
3192 /* Add types of args/locals */
3193 for (i = 0; i < acfg->methods->len; ++i) {
3196 method = g_ptr_array_index (acfg->methods, i);
3198 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3200 sig = mono_method_signature (method);
3203 for (j = 0; j < sig->param_count; ++j)
3204 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3205 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3208 header = mono_method_get_header (method);
3211 for (j = 0; j < header->num_locals; ++j)
3212 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3213 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3217 if (acfg->image == mono_defaults.corlib) {
3219 MonoType *insts [256];
3222 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3223 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3224 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3225 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3226 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3227 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3228 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3229 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3230 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3231 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3232 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3233 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3235 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3236 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3238 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3239 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3241 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3243 /* Add instances of the array generic interfaces for primitive types */
3244 /* This will add instances of the InternalArray_ helper methods in Array too */
3245 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3247 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3248 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3250 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3251 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3253 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3256 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3257 * used for all instances of GetGenericValueImpl by the AOT runtime.
3260 MonoGenericContext ctx;
3261 MonoType *args [16];
3262 MonoMethod *get_method;
3263 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3265 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3268 memset (&ctx, 0, sizeof (ctx));
3269 args [0] = &mono_defaults.object_class->byval_arg;
3270 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3271 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3275 /* Same for CompareExchange<T> */
3277 MonoGenericContext ctx;
3278 MonoType *args [16];
3279 MonoMethod *cas_method;
3280 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3281 gpointer iter = NULL;
3283 while ((cas_method = mono_class_get_methods (interlocked_klass, &iter))) {
3284 if (!strcmp (cas_method->name, "CompareExchange") && cas_method->is_generic) {
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 (cas_method, &ctx), TRUE, TRUE));
3296 * is_direct_callable:
3298 * Return whenever the method identified by JI is directly callable without
3299 * going through the PLT.
3302 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3304 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3305 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3307 gboolean direct_callable = TRUE;
3309 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3310 direct_callable = FALSE;
3311 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3312 // FIXME: Maybe call the wrapper directly ?
3313 direct_callable = FALSE;
3315 if (direct_callable)
3324 * emit_and_reloc_code:
3326 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3327 * is true, calls are made through the GOT too. This is used for emitting trampolines
3328 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3329 * since trampolines are needed to make PTL work.
3332 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3334 int i, pindex, start_index, method_index;
3336 MonoJumpInfo *patch_info;
3337 MonoMethodHeader *header;
3338 gboolean skip, direct_call;
3340 char direct_call_target [1024];
3343 header = mono_method_get_header (method);
3345 method_index = get_method_index (acfg, method);
3348 /* Collect and sort relocations */
3349 patches = g_ptr_array_new ();
3350 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3351 g_ptr_array_add (patches, patch_info);
3352 g_ptr_array_sort (patches, compare_patches);
3355 for (i = 0; i < code_len; i++) {
3357 for (pindex = start_index; pindex < patches->len; ++pindex) {
3358 patch_info = g_ptr_array_index (patches, pindex);
3359 if (patch_info->ip.i >= i)
3363 #ifdef MONO_ARCH_AOT_SUPPORTED
3365 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3366 start_index = pindex;
3368 switch (patch_info->type) {
3369 case MONO_PATCH_INFO_NONE:
3371 case MONO_PATCH_INFO_GOT_OFFSET: {
3374 arch_emit_got_offset (acfg, code + i, &code_size);
3377 patch_info->type = MONO_PATCH_INFO_NONE;
3382 * If this patch is a call, try emitting a direct call instead of
3383 * through a PLT entry. This is possible if the called method is in
3384 * the same assembly and requires no initialization.
3386 direct_call = FALSE;
3387 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3388 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3389 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3390 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3392 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3393 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3394 patch_info->type = MONO_PATCH_INFO_NONE;
3395 acfg->stats.direct_calls ++;
3398 acfg->stats.all_calls ++;
3401 if (!got_only && !direct_call) {
3402 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3404 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3406 sprintf (direct_call_target, "%s", plt_entry->symbol);
3408 /* Nullify the patch */
3409 patch_info->type = MONO_PATCH_INFO_NONE;
3410 plt_entry->jit_used = TRUE;
3417 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3422 got_slot = get_got_offset (acfg, patch_info);
3424 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3431 #endif /* MONO_ARCH_AOT_SUPPORTED */
3434 /* Find next patch */
3436 for (pindex = start_index; pindex < patches->len; ++pindex) {
3437 patch_info = g_ptr_array_index (patches, pindex);
3438 if (patch_info->ip.i >= i)
3442 /* Try to emit multiple bytes at once */
3443 if (pindex < patches->len && patch_info->ip.i > i) {
3444 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3445 i = patch_info->ip.i - 1;
3447 emit_bytes (acfg, code + i, 1);
3456 * Modify SYMBOL so it only includes characters permissible in symbols.
3459 sanitize_symbol (char *symbol)
3461 int i, len = strlen (symbol);
3463 for (i = 0; i < len; ++i)
3464 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3469 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3471 char *name1, *name2, *cached;
3472 int i, j, len, count;
3474 name1 = mono_method_full_name (method, TRUE);
3475 len = strlen (name1);
3476 name2 = malloc (strlen (prefix) + len + 16);
3477 memcpy (name2, prefix, strlen (prefix));
3478 j = strlen (prefix);
3479 for (i = 0; i < len; ++i) {
3480 if (isalnum (name1 [i])) {
3481 name2 [j ++] = name1 [i];
3482 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3484 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3487 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3496 while (g_hash_table_lookup (cache, name2)) {
3497 sprintf (name2 + j, "_%d", count);
3501 cached = g_strdup (name2);
3502 g_hash_table_insert (cache, cached, cached);
3508 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3513 char *debug_sym = NULL;
3515 int func_alignment = AOT_FUNC_ALIGNMENT;
3516 MonoMethodHeader *header;
3518 method = cfg->orig_method;
3519 code = cfg->native_code;
3520 header = cfg->header;
3522 method_index = get_method_index (acfg, method);
3524 /* Make the labels local */
3525 sprintf (symbol, "%s", cfg->asm_symbol);
3527 emit_section_change (acfg, ".text", 0);
3528 emit_alignment (acfg, func_alignment);
3529 emit_label (acfg, symbol);
3531 if (acfg->aot_opts.write_symbols) {
3533 * Write a C style symbol for every method, this has two uses:
3534 * - it works on platforms where the dwarf debugging info is not
3536 * - it allows the setting of breakpoints of aot-ed methods.
3538 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3540 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3541 if (acfg->need_no_dead_strip)
3542 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3543 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3544 emit_label (acfg, debug_sym);
3547 if (cfg->verbose_level > 0)
3548 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3550 acfg->stats.code_size += cfg->code_len;
3552 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3554 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3558 if (acfg->aot_opts.write_symbols) {
3559 emit_symbol_size (acfg, debug_sym, ".");
3563 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3564 emit_label (acfg, symbol);
3570 * Encode PATCH_INFO into its disk representation.
3573 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3577 switch (patch_info->type) {
3578 case MONO_PATCH_INFO_NONE:
3580 case MONO_PATCH_INFO_IMAGE:
3581 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3583 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3584 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3585 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3587 case MONO_PATCH_INFO_METHOD_REL:
3588 encode_value ((gint)patch_info->data.offset, p, &p);
3590 case MONO_PATCH_INFO_SWITCH: {
3591 gpointer *table = (gpointer *)patch_info->data.table->table;
3594 encode_value (patch_info->data.table->table_size, p, &p);
3595 for (k = 0; k < patch_info->data.table->table_size; k++)
3596 encode_value ((int)(gssize)table [k], p, &p);
3599 case MONO_PATCH_INFO_METHODCONST:
3600 case MONO_PATCH_INFO_METHOD:
3601 case MONO_PATCH_INFO_METHOD_JUMP:
3602 case MONO_PATCH_INFO_ICALL_ADDR:
3603 case MONO_PATCH_INFO_METHOD_RGCTX:
3604 encode_method_ref (acfg, patch_info->data.method, p, &p);
3606 case MONO_PATCH_INFO_INTERNAL_METHOD:
3607 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3608 guint32 len = strlen (patch_info->data.name);
3610 encode_value (len, p, &p);
3612 memcpy (p, patch_info->data.name, len);
3617 case MONO_PATCH_INFO_LDSTR: {
3618 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3619 guint32 token = patch_info->data.token->token;
3620 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3621 encode_value (image_index, p, &p);
3622 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3625 case MONO_PATCH_INFO_RVA:
3626 case MONO_PATCH_INFO_DECLSEC:
3627 case MONO_PATCH_INFO_LDTOKEN:
3628 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3629 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3630 encode_value (patch_info->data.token->token, p, &p);
3631 encode_value (patch_info->data.token->has_context, p, &p);
3632 if (patch_info->data.token->has_context)
3633 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3635 case MONO_PATCH_INFO_EXC_NAME: {
3636 MonoClass *ex_class;
3639 mono_class_from_name (mono_defaults.exception_class->image,
3640 "System", patch_info->data.target);
3641 g_assert (ex_class);
3642 encode_klass_ref (acfg, ex_class, p, &p);
3645 case MONO_PATCH_INFO_R4:
3646 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3648 case MONO_PATCH_INFO_R8:
3649 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3650 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3652 case MONO_PATCH_INFO_VTABLE:
3653 case MONO_PATCH_INFO_CLASS:
3654 case MONO_PATCH_INFO_IID:
3655 case MONO_PATCH_INFO_ADJUSTED_IID:
3656 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3658 case MONO_PATCH_INFO_CLASS_INIT:
3659 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3660 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3662 case MONO_PATCH_INFO_FIELD:
3663 case MONO_PATCH_INFO_SFLDA:
3664 encode_field_info (acfg, patch_info->data.field, p, &p);
3666 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3668 case MONO_PATCH_INFO_RGCTX_FETCH: {
3669 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3671 encode_method_ref (acfg, entry->method, p, &p);
3672 encode_value (entry->in_mrgctx, p, &p);
3673 encode_value (entry->info_type, p, &p);
3674 encode_value (entry->data->type, p, &p);
3675 encode_patch (acfg, entry->data, p, &p);
3678 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3679 case MONO_PATCH_INFO_MONITOR_ENTER:
3680 case MONO_PATCH_INFO_MONITOR_EXIT:
3681 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3683 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3684 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3685 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3688 g_warning ("unable to handle jump info %d", patch_info->type);
3689 g_assert_not_reached ();
3696 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3699 guint32 pindex, offset;
3700 MonoJumpInfo *patch_info;
3702 encode_value (n_patches, p, &p);
3704 for (pindex = 0; pindex < patches->len; ++pindex) {
3705 patch_info = g_ptr_array_index (patches, pindex);
3707 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3711 offset = get_got_offset (acfg, patch_info);
3712 encode_value (offset, p, &p);
3719 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3723 int pindex, buf_size, n_patches;
3726 MonoJumpInfo *patch_info;
3727 MonoMethodHeader *header;
3728 guint32 method_index;
3730 guint32 first_got_offset;
3732 method = cfg->orig_method;
3733 code = cfg->native_code;
3734 header = mono_method_get_header (method);
3736 method_index = get_method_index (acfg, method);
3738 /* Sort relocations */
3739 patches = g_ptr_array_new ();
3740 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3741 g_ptr_array_add (patches, patch_info);
3742 g_ptr_array_sort (patches, compare_patches);
3744 first_got_offset = acfg->cfgs [method_index]->got_offset;
3746 /**********************/
3747 /* Encode method info */
3748 /**********************/
3750 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3751 p = buf = g_malloc (buf_size);
3753 if (mono_class_get_cctor (method->klass))
3754 encode_klass_ref (acfg, method->klass, p, &p);
3756 /* Not needed when loading the method */
3757 encode_value (0, p, &p);
3760 if (cfg->opt & MONO_OPT_SHARED) {
3761 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3762 for (l = cfg->ldstr_list; l; l = l->next) {
3763 encode_value ((long)l->data, p, &p);
3767 /* Used only in shared mode */
3768 g_assert (!cfg->ldstr_list);
3771 for (pindex = 0; pindex < patches->len; ++pindex) {
3772 patch_info = g_ptr_array_index (patches, pindex);
3774 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3775 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3776 patch_info->type = MONO_PATCH_INFO_NONE;
3781 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3782 /* Stored in a GOT slot initialized at module load time */
3783 patch_info->type = MONO_PATCH_INFO_NONE;
3787 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3788 /* Stored in a GOT slot initialized at module load time */
3789 patch_info->type = MONO_PATCH_INFO_NONE;
3793 if (is_plt_patch (patch_info)) {
3794 /* Calls are made through the PLT */
3795 patch_info->type = MONO_PATCH_INFO_NONE;
3803 g_assert (cfg->has_got_slots);
3805 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3807 acfg->stats.info_size += p - buf;
3809 g_assert (p - buf < buf_size);
3811 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3816 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3818 guint32 cache_index;
3821 /* Reuse the unwind module to canonize and store unwind info entries */
3822 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3824 /* Use +/- 1 to distinguish 0s from missing entries */
3825 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3833 * It would be easier to use assembler symbols, but the caller needs an
3836 offset = acfg->unwind_info_offset;
3837 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3838 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3841 encode_value (encoded_len, p, &p);
3843 acfg->unwind_info_offset += encoded_len + (p - buf);
3849 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3852 int i, k, buf_size, method_index;
3853 guint32 debug_info_size;
3855 MonoMethodHeader *header;
3856 guint8 *p, *buf, *debug_info;
3857 MonoJitInfo *jinfo = cfg->jit_info;
3859 gboolean use_unwind_ops = FALSE;
3860 MonoSeqPointInfo *seq_points;
3862 method = cfg->orig_method;
3863 code = cfg->native_code;
3864 header = cfg->header;
3866 method_index = get_method_index (acfg, method);
3868 if (!acfg->aot_opts.nodebug) {
3869 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3872 debug_info_size = 0;
3875 seq_points = cfg->seq_point_info;
3877 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3878 p = buf = g_malloc (buf_size);
3880 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3881 use_unwind_ops = cfg->unwind_ops != NULL;
3884 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);
3886 encode_value (flags, p, &p);
3888 if (use_unwind_ops) {
3889 guint32 encoded_len;
3893 * This is a duplicate of the data in the .debug_frame section, but that
3894 * section cannot be accessed using the dl interface.
3896 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3897 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3900 encode_value (jinfo->used_regs, p, &p);
3903 /*Encode the number of holes before the number of clauses to make decoding easier*/
3904 if (jinfo->has_try_block_holes) {
3905 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3906 encode_value (table->num_holes, p, &p);
3909 /* Exception table */
3910 if (cfg->compile_llvm) {
3912 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3913 * since the information is only available to llc. Instead, we let llc save the data
3914 * into the LSDA, and read it from there at runtime.
3916 /* The assembly might be CIL stripped so emit the data ourselves */
3917 if (header->num_clauses)
3918 encode_value (header->num_clauses, p, &p);
3920 for (k = 0; k < header->num_clauses; ++k) {
3921 MonoExceptionClause *clause;
3923 clause = &header->clauses [k];
3925 encode_value (clause->flags, p, &p);
3926 if (clause->data.catch_class) {
3927 encode_value (1, p, &p);
3928 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3930 encode_value (0, p, &p);
3933 /* Emit a list of nesting clauses */
3934 for (i = 0; i < header->num_clauses; ++i) {
3936 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3938 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3940 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3941 encode_value (i, p, &p);
3943 encode_value (-1, p, &p);
3946 if (jinfo->num_clauses)
3947 encode_value (jinfo->num_clauses, p, &p);
3949 for (k = 0; k < jinfo->num_clauses; ++k) {
3950 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3952 encode_value (ei->flags, p, &p);
3953 encode_value (ei->exvar_offset, p, &p);
3955 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3956 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3958 if (ei->data.catch_class) {
3959 encode_value (1, p, &p);
3960 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3962 encode_value (0, p, &p);
3966 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3967 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3968 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3972 if (jinfo->has_generic_jit_info) {
3973 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3975 if (!cfg->compile_llvm) {
3976 encode_value (gi->has_this ? 1 : 0, p, &p);
3977 encode_value (gi->this_reg, p, &p);
3978 encode_value (gi->this_offset, p, &p);
3982 * Need to encode jinfo->method too, since it is not equal to 'method'
3983 * when using generic sharing.
3985 encode_method_ref (acfg, jinfo->method, p, &p);
3988 if (jinfo->has_try_block_holes) {
3989 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3990 for (i = 0; i < table->num_holes; ++i) {
3991 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3992 encode_value (hole->clause, p, &p);
3993 encode_value (hole->length, p, &p);
3994 encode_value (hole->offset, p, &p);
3999 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4001 encode_value (seq_points->len, p, &p);
4002 last_il_offset = last_native_offset = 0;
4003 for (i = 0; i < seq_points->len; ++i) {
4004 SeqPoint *sp = &seq_points->seq_points [i];
4005 il_offset = sp->il_offset;
4006 native_offset = sp->native_offset;
4007 encode_value (il_offset - last_il_offset, p, &p);
4008 encode_value (native_offset - last_native_offset, p, &p);
4009 last_il_offset = il_offset;
4010 last_native_offset = native_offset;
4012 encode_value (sp->next_len, p, &p);
4013 for (j = 0; j < sp->next_len; ++j)
4014 encode_value (sp->next [j], p, &p);
4018 g_assert (debug_info_size < buf_size);
4020 encode_value (debug_info_size, p, &p);
4021 if (debug_info_size) {
4022 memcpy (p, debug_info, debug_info_size);
4023 p += debug_info_size;
4024 g_free (debug_info);
4029 encode_value (cfg->gc_map_size, p, &p);
4030 /* The GC map requires 4 bytes of alignment */
4031 while ((gsize)p % 4)
4033 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4034 p += cfg->gc_map_size;
4037 acfg->stats.ex_info_size += p - buf;
4039 g_assert (p - buf < buf_size);
4042 /* The GC Map requires 4 byte alignment */
4043 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4048 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4050 MonoClass *klass = mono_class_get (acfg->image, token);
4052 int i, buf_size, res;
4053 gboolean no_special_static, cant_encode;
4054 gpointer iter = NULL;
4057 mono_loader_clear_error ();
4061 p = buf = g_malloc (buf_size);
4063 /* Mark as unusable */
4064 encode_value (-1, p, &p);
4066 res = add_to_blob (acfg, buf, p - buf);
4072 buf_size = 10240 + (klass->vtable_size * 16);
4073 p = buf = g_malloc (buf_size);
4077 mono_class_init (klass);
4079 mono_class_get_nested_types (klass, &iter);
4080 g_assert (klass->nested_classes_inited);
4082 mono_class_setup_vtable (klass);
4085 * Emit all the information which is required for creating vtables so
4086 * the runtime does not need to create the MonoMethod structures which
4087 * take up a lot of space.
4090 no_special_static = !mono_class_has_special_static_fields (klass);
4092 /* Check whenever we have enough info to encode the vtable */
4093 cant_encode = FALSE;
4094 for (i = 0; i < klass->vtable_size; ++i) {
4095 MonoMethod *cm = klass->vtable [i];
4097 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4101 if (klass->generic_container || cant_encode) {
4102 encode_value (-1, p, &p);
4104 encode_value (klass->vtable_size, p, &p);
4105 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);
4106 if (klass->has_cctor)
4107 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4108 if (klass->has_finalize)
4109 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4111 encode_value (klass->instance_size, p, &p);
4112 encode_value (mono_class_data_size (klass), p, &p);
4113 encode_value (klass->packing_size, p, &p);
4114 encode_value (klass->min_align, p, &p);
4116 for (i = 0; i < klass->vtable_size; ++i) {
4117 MonoMethod *cm = klass->vtable [i];
4120 encode_method_ref (acfg, cm, p, &p);
4122 encode_value (0, p, &p);
4126 acfg->stats.class_info_size += p - buf;
4128 g_assert (p - buf < buf_size);
4129 res = add_to_blob (acfg, buf, p - buf);
4136 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4138 char *debug_sym = NULL;
4141 case MONO_PATCH_INFO_METHOD:
4142 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4144 case MONO_PATCH_INFO_INTERNAL_METHOD:
4145 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4147 case MONO_PATCH_INFO_CLASS_INIT:
4148 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4149 sanitize_symbol (debug_sym);
4151 case MONO_PATCH_INFO_RGCTX_FETCH:
4152 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4154 case MONO_PATCH_INFO_ICALL_ADDR: {
4155 char *s = get_debug_sym (ji->data.method, "", cache);
4157 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4161 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4162 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4164 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4165 debug_sym = g_strdup_printf ("plt__generic_class_init");
4175 * Calls made from AOTed code are routed through a table of jumps similar to the
4176 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4177 * control to the AOT runtime through a trampoline.
4180 emit_plt (MonoAotCompile *acfg)
4186 cache = g_hash_table_new (g_str_hash, g_str_equal);
4189 sprintf (symbol, "plt");
4191 emit_section_change (acfg, ".text", 0);
4192 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4193 emit_label (acfg, symbol);
4194 emit_label (acfg, acfg->plt_symbol);
4196 for (i = 0; i < acfg->plt_offset; ++i) {
4197 char *debug_sym = NULL;
4198 MonoPltEntry *plt_entry = NULL;
4203 * The first plt entry is unused.
4207 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4212 * If the target is directly callable, alias the plt symbol to point to
4214 * FIXME: Use this to simplify emit_and_reloc_code ().
4215 * FIXME: Avoid the got slot.
4216 * FIXME: Add support to the binary writer.
4218 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4219 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4221 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4222 /* LLVM calls the PLT entries using bl, so emit a stub */
4223 fprintf (acfg->fp, "\n.thumb_func\n");
4224 emit_label (acfg, plt_entry->llvm_symbol);
4225 fprintf (acfg->fp, "bx pc\n");
4226 fprintf (acfg->fp, "nop\n");
4227 fprintf (acfg->fp, ".arm\n");
4228 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4230 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4236 if (acfg->aot_opts.write_symbols)
4237 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4238 debug_sym = plt_entry->debug_sym;
4240 if (acfg->thumb_mixed && !plt_entry->jit_used)
4241 /* Emit only a thumb version */
4244 if (!acfg->thumb_mixed)
4245 emit_label (acfg, plt_entry->llvm_symbol);
4248 if (acfg->need_no_dead_strip)
4249 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4250 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4251 emit_label (acfg, debug_sym);
4254 emit_label (acfg, plt_entry->symbol);
4256 arch_emit_plt_entry (acfg, i);
4259 emit_symbol_size (acfg, debug_sym, ".");
4262 if (acfg->thumb_mixed) {
4263 /* Make sure the ARM symbols don't alias the thumb ones */
4264 emit_zero_bytes (acfg, 16);
4267 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4270 for (i = 0; i < acfg->plt_offset; ++i) {
4271 char *debug_sym = NULL;
4272 MonoPltEntry *plt_entry = NULL;
4278 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4281 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4284 /* Skip plt entries not actually called by LLVM code */
4285 if (!plt_entry->llvm_used)
4288 if (acfg->aot_opts.write_symbols) {
4289 if (plt_entry->debug_sym)
4290 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4294 #if defined(__APPLE__)
4295 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4296 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4298 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4299 emit_label (acfg, debug_sym);
4301 fprintf (acfg->fp, "\n.thumb_func\n");
4303 emit_label (acfg, plt_entry->llvm_symbol);
4305 arch_emit_llvm_plt_entry (acfg, i);
4308 emit_symbol_size (acfg, debug_sym, ".");
4314 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4316 sprintf (symbol, "plt_end");
4317 emit_label (acfg, symbol);
4319 g_hash_table_destroy (cache);
4322 static G_GNUC_UNUSED void
4323 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4325 char start_symbol [256];
4327 guint32 buf_size, info_offset;
4328 MonoJumpInfo *patch_info;
4339 code_size = info->code_size;
4341 unwind_ops = info->unwind_ops;
4343 #ifdef __native_client_codegen__
4344 mono_nacl_fix_patches (code, ji);
4349 sprintf (start_symbol, "%s", name);
4351 emit_section_change (acfg, ".text", 0);
4352 emit_global (acfg, start_symbol, TRUE);
4353 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4354 emit_label (acfg, start_symbol);
4356 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4357 emit_label (acfg, symbol);
4360 * The code should access everything through the GOT, so we pass
4363 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4365 emit_symbol_size (acfg, start_symbol, ".");
4369 /* Sort relocations */
4370 patches = g_ptr_array_new ();
4371 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4372 if (patch_info->type != MONO_PATCH_INFO_NONE)
4373 g_ptr_array_add (patches, patch_info);
4374 g_ptr_array_sort (patches, compare_patches);
4376 buf_size = patches->len * 128 + 128;
4377 buf = g_malloc (buf_size);
4380 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4381 g_assert (p - buf < buf_size);
4383 sprintf (symbol, "%s_p", name);
4385 info_offset = add_to_blob (acfg, buf, p - buf);
4387 emit_section_change (acfg, RODATA_SECT, 0);
4388 emit_global (acfg, symbol, FALSE);
4389 emit_label (acfg, symbol);
4391 emit_int32 (acfg, info_offset);
4393 /* Emit debug info */
4397 sprintf (symbol, "%s", name);
4398 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4401 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4406 emit_trampolines (MonoAotCompile *acfg)
4409 char end_symbol [256];
4410 int i, tramp_got_offset;
4411 MonoAotTrampoline ntype;
4412 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4417 if (!acfg->aot_opts.full_aot)
4420 g_assert (acfg->image->assembly);
4422 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4423 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4424 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4425 MonoTrampInfo *info;
4428 * Emit the generic trampolines.
4430 * We could save some code by treating the generic trampolines as a wrapper
4431 * method, but that approach has its own complexities, so we choose the simpler
4434 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4435 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4436 emit_trampoline (acfg, acfg->got_offset, info);
4439 mono_arch_get_nullified_class_init_trampoline (&info);
4440 emit_trampoline (acfg, acfg->got_offset, info);
4441 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4442 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4443 emit_trampoline (acfg, acfg->got_offset, info);
4444 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4445 emit_trampoline (acfg, acfg->got_offset, info);
4448 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4449 emit_trampoline (acfg, acfg->got_offset, info);
4451 /* Emit the exception related code pieces */
4452 code = mono_arch_get_restore_context (&info, TRUE);
4453 emit_trampoline (acfg, acfg->got_offset, info);
4454 code = mono_arch_get_call_filter (&info, TRUE);
4455 emit_trampoline (acfg, acfg->got_offset, info);
4456 code = mono_arch_get_throw_exception (&info, TRUE);
4457 emit_trampoline (acfg, acfg->got_offset, info);
4458 code = mono_arch_get_rethrow_exception (&info, TRUE);
4459 emit_trampoline (acfg, acfg->got_offset, info);
4460 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4461 emit_trampoline (acfg, acfg->got_offset, info);
4463 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4465 GSList *l = mono_arch_get_trampolines (TRUE);
4468 MonoTrampInfo *info = l->data;
4470 emit_trampoline (acfg, acfg->got_offset, info);
4476 for (i = 0; i < 128; ++i) {
4479 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4480 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4481 emit_trampoline (acfg, acfg->got_offset, info);
4483 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4484 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4485 emit_trampoline (acfg, acfg->got_offset, info);
4491 /* delegate_invoke_impl trampolines */
4492 l = mono_arch_get_delegate_invoke_impls ();
4494 MonoTrampInfo *info = l->data;
4496 emit_trampoline (acfg, acfg->got_offset, info);
4501 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4503 /* Emit trampolines which are numerous */
4506 * These include the following:
4507 * - specific trampolines
4508 * - static rgctx invoke trampolines
4510 * These trampolines have the same code, they are parameterized by GOT
4512 * They are defined in this file, in the arch_... routines instead of
4513 * in tramp-<ARCH>.c, since it is easier to do it this way.
4517 * When running in aot-only mode, we can't create specific trampolines at
4518 * runtime, so we create a few, and save them in the AOT file.
4519 * Normal trampolines embed their argument as a literal inside the
4520 * trampoline code, we can't do that here, so instead we embed an offset
4521 * which needs to be added to the trampoline address to get the address of
4522 * the GOT slot which contains the argument value.
4523 * The generated trampolines jump to the generic trampolines using another
4524 * GOT slot, which will be setup by the AOT loader to point to the
4525 * generic trampoline code of the given type.
4529 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4533 emit_section_change (acfg, ".text", 0);
4535 tramp_got_offset = acfg->got_offset;
4537 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4539 case MONO_AOT_TRAMP_SPECIFIC:
4540 sprintf (symbol, "specific_trampolines");
4542 case MONO_AOT_TRAMP_STATIC_RGCTX:
4543 sprintf (symbol, "static_rgctx_trampolines");
4545 case MONO_AOT_TRAMP_IMT_THUNK:
4546 sprintf (symbol, "imt_thunks");
4549 g_assert_not_reached ();
4552 sprintf (end_symbol, "%s_e", symbol);
4554 if (acfg->aot_opts.write_symbols)
4555 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
4557 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4558 emit_label (acfg, symbol);
4560 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4562 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4566 case MONO_AOT_TRAMP_SPECIFIC:
4567 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4568 tramp_got_offset += 2;
4570 case MONO_AOT_TRAMP_STATIC_RGCTX:
4571 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4572 tramp_got_offset += 2;
4574 case MONO_AOT_TRAMP_IMT_THUNK:
4575 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4576 tramp_got_offset += 1;
4579 g_assert_not_reached ();
4581 #ifdef __native_client_codegen__
4582 /* align to avoid 32-byte boundary crossings */
4583 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4586 if (!acfg->trampoline_size [ntype]) {
4587 g_assert (tramp_size);
4588 acfg->trampoline_size [ntype] = tramp_size;
4592 emit_label (acfg, end_symbol);
4595 /* Reserve some entries at the end of the GOT for our use */
4596 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4599 acfg->got_offset += acfg->num_trampoline_got_entries;
4603 str_begins_with (const char *str1, const char *str2)
4605 int len = strlen (str2);
4606 return strncmp (str1, str2, len) == 0;
4610 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4612 gchar **args, **ptr;
4614 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4615 for (ptr = args; ptr && *ptr; ptr ++) {
4616 const char *arg = *ptr;
4618 if (str_begins_with (arg, "outfile=")) {
4619 opts->outfile = g_strdup (arg + strlen ("outfile="));
4620 } else if (str_begins_with (arg, "save-temps")) {
4621 opts->save_temps = TRUE;
4622 } else if (str_begins_with (arg, "keep-temps")) {
4623 opts->save_temps = TRUE;
4624 } else if (str_begins_with (arg, "write-symbols")) {
4625 opts->write_symbols = TRUE;
4626 } else if (str_begins_with (arg, "no-write-symbols")) {
4627 opts->write_symbols = FALSE;
4628 } else if (str_begins_with (arg, "metadata-only")) {
4629 opts->metadata_only = TRUE;
4630 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4631 opts->bind_to_runtime_version = TRUE;
4632 } else if (str_begins_with (arg, "full")) {
4633 opts->full_aot = TRUE;
4634 } else if (str_begins_with (arg, "threads=")) {
4635 opts->nthreads = atoi (arg + strlen ("threads="));
4636 } else if (str_begins_with (arg, "static")) {
4637 opts->static_link = TRUE;
4638 opts->no_dlsym = TRUE;
4639 } else if (str_begins_with (arg, "asmonly")) {
4640 opts->asm_only = TRUE;
4641 } else if (str_begins_with (arg, "asmwriter")) {
4642 opts->asm_writer = TRUE;
4643 } else if (str_begins_with (arg, "nodebug")) {
4644 opts->nodebug = TRUE;
4645 } else if (str_begins_with (arg, "ntrampolines=")) {
4646 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4647 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4648 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4649 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4650 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4651 } else if (str_begins_with (arg, "autoreg")) {
4652 opts->autoreg = TRUE;
4653 } else if (str_begins_with (arg, "tool-prefix=")) {
4654 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4655 } else if (str_begins_with (arg, "soft-debug")) {
4656 opts->soft_debug = TRUE;
4657 } else if (str_begins_with (arg, "print-skipped")) {
4658 opts->print_skipped_methods = TRUE;
4659 } else if (str_begins_with (arg, "stats")) {
4661 } else if (str_begins_with (arg, "mtriple=")) {
4662 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4663 } else if (str_begins_with (arg, "llvm-path=")) {
4664 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4665 } else if (str_begins_with (arg, "info")) {
4666 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
4668 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
4669 printf ("Supported options for --aot:\n");
4670 printf (" outfile=\n");
4671 printf (" save-temps\n");
4672 printf (" keep-temps\n");
4673 printf (" write-symbols\n");
4674 printf (" metadata-only\n");
4675 printf (" bind-to-runtime-version\n");
4677 printf (" threads=\n");
4678 printf (" static\n");
4679 printf (" asmonly\n");
4680 printf (" asmwriter\n");
4681 printf (" nodebug\n");
4682 printf (" ntrampolines=\n");
4683 printf (" nrgctx-trampolines=\n");
4684 printf (" nimt-trampolines=\n");
4685 printf (" autoreg\n");
4686 printf (" tool-prefix=\n");
4687 printf (" soft-debug\n");
4688 printf (" print-skipped\n");
4689 printf (" stats\n");
4691 printf (" help/?\n");
4694 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4703 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4705 MonoMethod *method = (MonoMethod*)key;
4706 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4707 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4708 MonoAotCompile *acfg = user_data;
4710 new_ji->image = ji->image;
4711 new_ji->token = ji->token;
4712 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4716 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4718 if (klass->type_token)
4720 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4723 return can_encode_class (acfg, klass->element_class);
4728 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4730 switch (patch_info->type) {
4731 case MONO_PATCH_INFO_METHOD:
4732 case MONO_PATCH_INFO_METHODCONST: {
4733 MonoMethod *method = patch_info->data.method;
4735 if (method->wrapper_type) {
4736 switch (method->wrapper_type) {
4737 case MONO_WRAPPER_NONE:
4738 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4739 case MONO_WRAPPER_XDOMAIN_INVOKE:
4740 case MONO_WRAPPER_STFLD:
4741 case MONO_WRAPPER_LDFLD:
4742 case MONO_WRAPPER_LDFLDA:
4743 case MONO_WRAPPER_LDFLD_REMOTE:
4744 case MONO_WRAPPER_STFLD_REMOTE:
4745 case MONO_WRAPPER_STELEMREF:
4746 case MONO_WRAPPER_ISINST:
4747 case MONO_WRAPPER_PROXY_ISINST:
4748 case MONO_WRAPPER_ALLOC:
4749 case MONO_WRAPPER_REMOTING_INVOKE:
4750 case MONO_WRAPPER_UNKNOWN:
4751 case MONO_WRAPPER_WRITE_BARRIER:
4753 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4754 if (!strcmp (method->name, "ElementAddr"))
4758 case MONO_WRAPPER_CASTCLASS:
4759 if (!strcmp (method->name, "__castclass_with_cache"))
4761 else if (!strcmp (method->name, "__isinst_with_cache"))
4766 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4770 if (!method->token) {
4771 /* The method is part of a constructed type like Int[,].Set (). */
4772 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4773 if (method->klass->rank)
4781 case MONO_PATCH_INFO_VTABLE:
4782 case MONO_PATCH_INFO_CLASS_INIT:
4783 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4784 case MONO_PATCH_INFO_CLASS:
4785 case MONO_PATCH_INFO_IID:
4786 case MONO_PATCH_INFO_ADJUSTED_IID:
4787 if (!can_encode_class (acfg, patch_info->data.klass)) {
4788 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4792 case MONO_PATCH_INFO_RGCTX_FETCH: {
4793 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4795 if (!can_encode_patch (acfg, entry->data))
4809 * AOT compile a given method.
4810 * This function might be called by multiple threads, so it must be thread-safe.
4813 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4816 MonoJumpInfo *patch_info;
4819 MonoMethod *wrapped;
4821 if (acfg->aot_opts.metadata_only)
4824 mono_acfg_lock (acfg);
4825 index = get_method_index (acfg, method);
4826 mono_acfg_unlock (acfg);
4828 /* fixme: maybe we can also precompile wrapper methods */
4829 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4830 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4831 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4832 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4836 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4839 wrapped = mono_marshal_method_from_wrapper (method);
4840 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4841 // FIXME: The wrapper should be generic too, but it is not
4844 InterlockedIncrement (&acfg->stats.mcount);
4847 if (method->is_generic || method->klass->generic_container) {
4848 InterlockedIncrement (&acfg->stats.genericcount);
4853 //acfg->aot_opts.print_skipped_methods = TRUE;
4856 * Since these methods are the only ones which are compiled with
4857 * AOT support, and they are not used by runtime startup/shutdown code,
4858 * the runtime will not see AOT methods during AOT compilation,so it
4859 * does not need to support them by creating a fake GOT etc.
4861 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4862 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4863 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4864 InterlockedIncrement (&acfg->stats.genericcount);
4867 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4868 //printf ("E: %s\n", mono_method_full_name (method, TRUE));
4869 /* Let the exception happen at runtime */
4873 if (cfg->disable_aot) {
4874 if (acfg->aot_opts.print_skipped_methods)
4875 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4876 InterlockedIncrement (&acfg->stats.ocount);
4877 mono_destroy_compile (cfg);
4881 /* Nullify patches which need no aot processing */
4882 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4883 switch (patch_info->type) {
4884 case MONO_PATCH_INFO_LABEL:
4885 case MONO_PATCH_INFO_BB:
4886 patch_info->type = MONO_PATCH_INFO_NONE;
4893 /* Collect method->token associations from the cfg */
4894 mono_acfg_lock (acfg);
4895 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4896 mono_acfg_unlock (acfg);
4899 * Check for absolute addresses.
4902 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4903 switch (patch_info->type) {
4904 case MONO_PATCH_INFO_ABS:
4905 /* unable to handle this */
4914 if (acfg->aot_opts.print_skipped_methods)
4915 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4916 InterlockedIncrement (&acfg->stats.abscount);
4917 mono_destroy_compile (cfg);
4921 /* Lock for the rest of the code */
4922 mono_acfg_lock (acfg);
4925 * Check for methods/klasses we can't encode.
4928 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4929 if (!can_encode_patch (acfg, patch_info))
4934 if (acfg->aot_opts.print_skipped_methods)
4935 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4936 acfg->stats.ocount++;
4937 mono_destroy_compile (cfg);
4938 mono_acfg_unlock (acfg);
4942 /* Adds generic instances referenced by this method */
4944 * The depth is used to avoid infinite loops when generic virtual recursion is
4947 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4949 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4950 switch (patch_info->type) {
4951 case MONO_PATCH_INFO_METHOD: {
4952 MonoMethod *m = patch_info->data.method;
4953 if (m->is_inflated) {
4954 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4955 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4956 !method_has_type_vars (m)) {
4957 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4958 if (acfg->aot_opts.full_aot)
4959 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4961 add_extra_method_with_depth (acfg, m, depth + 1);
4964 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4966 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4967 add_extra_method_with_depth (acfg, m, depth + 1);
4970 case MONO_PATCH_INFO_VTABLE: {
4971 MonoClass *klass = patch_info->data.klass;
4973 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4974 add_generic_class_with_depth (acfg, klass, depth + 5);
4983 /* Determine whenever the method has GOT slots */
4984 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4985 switch (patch_info->type) {
4986 case MONO_PATCH_INFO_GOT_OFFSET:
4987 case MONO_PATCH_INFO_NONE:
4988 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4990 case MONO_PATCH_INFO_IMAGE:
4991 /* The assembly is stored in GOT slot 0 */
4992 if (patch_info->data.image != acfg->image)
4993 cfg->has_got_slots = TRUE;
4996 if (!is_plt_patch (patch_info))
4997 cfg->has_got_slots = TRUE;
5002 if (!cfg->has_got_slots)
5003 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5006 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5008 /* Make a copy of the patch info which is in the mempool */
5010 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5012 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5013 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5016 patches = new_patch_info;
5018 patches_end->next = new_patch_info;
5019 patches_end = new_patch_info;
5021 cfg->patch_info = patches;
5023 /* Make a copy of the unwind info */
5025 GSList *l, *unwind_ops;
5029 for (l = cfg->unwind_ops; l; l = l->next) {
5030 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5031 memcpy (op, l->data, sizeof (MonoUnwindOp));
5032 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5034 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5036 /* Make a copy of the argument/local info */
5038 MonoInst **args, **locals;
5039 MonoMethodSignature *sig;
5040 MonoMethodHeader *header;
5043 sig = mono_method_signature (method);
5044 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5045 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5046 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5047 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5051 header = mono_method_get_header (method);
5052 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5053 for (i = 0; i < header->num_locals; ++i) {
5054 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5055 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5057 cfg->locals = locals;
5060 /* Free some fields used by cfg to conserve memory */
5061 mono_mempool_destroy (cfg->mempool);
5062 cfg->mempool = NULL;
5063 g_free (cfg->varinfo);
5064 cfg->varinfo = NULL;
5068 mono_regstate_free (cfg->rs);
5072 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5074 while (index >= acfg->cfgs_size) {
5075 MonoCompile **new_cfgs;
5078 new_size = acfg->cfgs_size * 2;
5079 new_cfgs = g_new0 (MonoCompile*, new_size);
5080 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5081 g_free (acfg->cfgs);
5082 acfg->cfgs = new_cfgs;
5083 acfg->cfgs_size = new_size;
5085 acfg->cfgs [index] = cfg;
5087 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5090 if (cfg->orig_method->wrapper_type)
5091 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5094 mono_acfg_unlock (acfg);
5096 InterlockedIncrement (&acfg->stats.ccount);
5100 compile_thread_main (gpointer *user_data)
5102 MonoDomain *domain = user_data [0];
5103 MonoAotCompile *acfg = user_data [1];
5104 GPtrArray *methods = user_data [2];
5107 mono_thread_attach (domain);
5109 for (i = 0; i < methods->len; ++i)
5110 compile_method (acfg, g_ptr_array_index (methods, i));
5114 load_profile_files (MonoAotCompile *acfg)
5118 int file_index, res, method_index, i;
5121 GList *unordered, *l;
5126 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5128 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5133 infile = fopen (tmp, "r");
5136 printf ("Using profile data file '%s'\n", tmp);
5141 res = fscanf (infile, "%32s\n", ver);
5142 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5143 printf ("Profile file has wrong version or invalid.\n");
5150 MonoMethodDesc *desc;
5153 if (fgets (name, 1023, infile) == NULL)
5156 /* Kill the newline */
5157 if (strlen (name) > 0)
5158 name [strlen (name) - 1] = '\0';
5160 desc = mono_method_desc_new (name, TRUE);
5162 method = mono_method_desc_search_in_image (desc, acfg->image);
5164 if (method && mono_method_get_token (method)) {
5165 token = mono_method_get_token (method);
5166 method_index = mono_metadata_token_index (token) - 1;
5169 for (i = 0; i < acfg->method_order->len; ++i) {
5170 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5176 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5178 //printf ("No method found matching '%s'.\n", name);
5184 /* Add missing methods */
5186 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5188 for (i = 0; i < acfg->method_order->len; ++i) {
5189 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5195 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5197 unordered = g_list_reverse (unordered);
5198 for (l = unordered; l; l = l->next)
5199 g_ptr_array_add (acfg->method_order, l->data);
5202 /* Used by the LLVM backend */
5204 mono_aot_get_got_offset (MonoJumpInfo *ji)
5206 return get_got_offset (llvm_acfg, ji);
5210 mono_aot_get_method_name (MonoCompile *cfg)
5212 if (llvm_acfg->aot_opts.static_link)
5213 /* Include the assembly name too to avoid duplicate symbol errors */
5214 return g_strdup_printf ("%s_%s", llvm_acfg->image->assembly->aname.name, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5216 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5220 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5222 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5223 MonoPltEntry *plt_entry;
5226 ji->data.target = data;
5228 if (!can_encode_patch (llvm_acfg, ji))
5231 plt_entry = get_plt_entry (llvm_acfg, ji);
5232 plt_entry->llvm_used = TRUE;
5234 #if defined(__APPLE__)
5235 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5237 return g_strdup_printf (plt_entry->llvm_symbol);
5242 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5246 mono_acfg_lock (llvm_acfg);
5247 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5248 mono_acfg_unlock (llvm_acfg);
5258 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5262 emit_llvm_file (MonoAotCompile *acfg)
5264 char *command, *opts;
5266 MonoJumpInfo *patch_info;
5269 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5273 /* Compute the final size of the got */
5274 for (i = 0; i < acfg->nmethods; ++i) {
5275 if (acfg->cfgs [i]) {
5276 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5277 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5278 if (!is_plt_patch (patch_info))
5279 get_got_offset (acfg, patch_info);
5281 get_plt_entry (acfg, patch_info);
5287 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5289 if (acfg->aot_opts.full_aot) {
5293 * Need to add the got entries used by the trampolines.
5294 * This is only a conservative approximation.
5296 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5297 /* For the generic + rgctx trampolines */
5298 acfg->final_got_size += 200;
5299 /* For the specific trampolines */
5300 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5301 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5306 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5309 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5310 * a lot of time, and doesn't seem to save much space.
5311 * The following optimizations cannot be enabled:
5313 * - 'jump-threading' changes our blockaddress references to int constants.
5314 * The opt list below was produced by taking the output of:
5315 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5316 * then removing tailcallelim + the global opts, and adding a second gvn.
5318 opts = g_strdup ("-instcombine -simplifycfg");
5319 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");
5321 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5322 printf ("Executing opt: %s\n", command);
5323 if (system (command) != 0) {
5329 if (!acfg->llc_args)
5330 acfg->llc_args = g_string_new ("");
5332 /* Verbose asm slows down llc greatly */
5333 g_string_append (acfg->llc_args, " -asm-verbose=false");
5335 if (acfg->aot_opts.mtriple)
5336 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5338 if (llvm_acfg->aot_opts.static_link)
5339 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5341 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5342 unlink (acfg->tmpfname);
5344 command = g_strdup_printf ("%sllc %s -unwind-tables -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5346 printf ("Executing llc: %s\n", command);
5348 if (system (command) != 0) {
5355 emit_code (MonoAotCompile *acfg)
5359 char end_symbol [256];
5361 #if defined(TARGET_POWERPC64)
5362 sprintf (symbol, ".Lgot_addr");
5363 emit_section_change (acfg, ".text", 0);
5364 emit_alignment (acfg, 8);
5365 emit_label (acfg, symbol);
5366 emit_pointer (acfg, acfg->got_symbol);
5370 * This global symbol is used to compute the address of each method using the
5371 * code_offsets array. It is also used to compute the memory ranges occupied by
5372 * AOT code, so it must be equal to the address of the first emitted method.
5374 sprintf (symbol, "methods");
5375 emit_section_change (acfg, ".text", 0);
5376 emit_alignment (acfg, 8);
5378 for (i = 0; i < acfg->nmethods; ++i) {
5379 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5380 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5384 if (i == acfg->nmethods)
5385 /* No LLVM compiled methods */
5386 emit_label (acfg, symbol);
5388 emit_label (acfg, symbol);
5392 * Emit some padding so the local symbol for the first method doesn't have the
5393 * same address as 'methods'.
5395 #if defined(__default_codegen__)
5396 emit_zero_bytes (acfg, 16);
5397 #elif defined(__native_client_codegen__)
5399 const int kPaddingSize = 16;
5400 guint8 pad_buffer[kPaddingSize];
5401 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5402 emit_bytes (acfg, pad_buffer, kPaddingSize);
5406 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5410 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5412 cfg = acfg->cfgs [i];
5417 method = cfg->orig_method;
5419 /* Emit unbox trampoline */
5420 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5421 if (!method->wrapper_type && !method->is_inflated) {
5422 g_assert (method->token);
5423 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5425 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5428 emit_section_change (acfg, ".text", 0);
5429 #ifdef __native_client_codegen__
5430 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5432 emit_global (acfg, symbol, TRUE);
5434 if (acfg->thumb_mixed && cfg->compile_llvm)
5435 fprintf (acfg->fp, "\n.thumb_func\n");
5437 emit_label (acfg, symbol);
5439 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5442 if (cfg->compile_llvm)
5443 acfg->stats.llvm_count ++;
5445 emit_method_code (acfg, cfg);
5448 sprintf (symbol, "methods_end");
5449 emit_section_change (acfg, ".text", 0);
5450 emit_alignment (acfg, 8);
5451 emit_label (acfg, symbol);
5454 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5455 * from optimizing them away, since it doesn't see that code_offsets references them.
5456 * JITted methods don't need this since they are referenced using assembler local
5458 * FIXME: This is why write-symbols doesn't work on OSX ?
5460 if (acfg->llvm && acfg->need_no_dead_strip) {
5461 fprintf (acfg->fp, "\n");
5462 for (i = 0; i < acfg->nmethods; ++i) {
5463 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5464 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5468 sprintf (symbol, "code_offsets");
5469 emit_section_change (acfg, RODATA_SECT, 1);
5470 emit_alignment (acfg, 8);
5471 emit_label (acfg, symbol);
5473 acfg->stats.offsets_size += acfg->nmethods * 4;
5475 sprintf (end_symbol, "methods");
5476 for (i = 0; i < acfg->nmethods; ++i) {
5477 if (acfg->cfgs [i]) {
5478 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5480 emit_int32 (acfg, 0xffffffff);
5487 emit_info (MonoAotCompile *acfg)
5493 offsets = g_new0 (gint32, acfg->nmethods);
5495 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5496 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5498 if (acfg->cfgs [i]) {
5499 emit_method_info (acfg, acfg->cfgs [i]);
5500 offsets [i] = acfg->cfgs [i]->method_info_offset;
5506 sprintf (symbol, "method_info_offsets");
5507 emit_section_change (acfg, RODATA_SECT, 1);
5508 emit_alignment (acfg, 8);
5509 emit_label (acfg, symbol);
5511 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5516 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5518 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5519 #define mix(a,b,c) { \
5520 a -= c; a ^= rot(c, 4); c += b; \
5521 b -= a; b ^= rot(a, 6); a += c; \
5522 c -= b; c ^= rot(b, 8); b += a; \
5523 a -= c; a ^= rot(c,16); c += b; \
5524 b -= a; b ^= rot(a,19); a += c; \
5525 c -= b; c ^= rot(b, 4); b += a; \
5527 #define final(a,b,c) { \
5528 c ^= b; c -= rot(b,14); \
5529 a ^= c; a -= rot(c,11); \
5530 b ^= a; b -= rot(a,25); \
5531 c ^= b; c -= rot(b,16); \
5532 a ^= c; a -= rot(c,4); \
5533 b ^= a; b -= rot(a,14); \
5534 c ^= b; c -= rot(b,24); \
5538 mono_aot_type_hash (MonoType *t1)
5540 guint hash = t1->type;
5542 hash |= t1->byref << 6; /* do not collide with t1->type values */
5544 case MONO_TYPE_VALUETYPE:
5545 case MONO_TYPE_CLASS:
5546 case MONO_TYPE_SZARRAY:
5547 /* check if the distribution is good enough */
5548 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5550 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5551 case MONO_TYPE_ARRAY:
5552 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5553 case MONO_TYPE_GENERICINST:
5554 return ((hash << 5) - hash) ^ 0;
5561 * mono_aot_method_hash:
5563 * Return a hash code for methods which only depends on metadata.
5566 mono_aot_method_hash (MonoMethod *method)
5568 MonoMethodSignature *sig;
5572 guint32 *hashes_start, *hashes;
5574 MonoGenericInst *ginst = NULL;
5576 /* Similar to the hash in mono_method_get_imt_slot () */
5578 sig = mono_method_signature (method);
5580 if (method->is_inflated)
5581 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5583 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5584 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5585 hashes = hashes_start;
5587 /* Some wrappers are assigned to random classes */
5588 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5589 klass = method->klass;
5591 klass = mono_defaults.object_class;
5593 if (!method->wrapper_type) {
5594 char *full_name = mono_type_full_name (&klass->byval_arg);
5596 hashes [0] = mono_metadata_str_hash (full_name);
5600 hashes [0] = mono_metadata_str_hash (klass->name);
5601 hashes [1] = mono_metadata_str_hash (klass->name_space);
5603 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5604 /* The method name includes a stringified pointer */
5607 hashes [2] = mono_metadata_str_hash (method->name);
5608 hashes [3] = method->wrapper_type;
5609 hashes [4] = mono_aot_type_hash (sig->ret);
5611 for (i = 0; i < sig->param_count; i++) {
5612 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5615 for (i = 0; i < ginst->type_argc; ++i)
5616 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5618 g_assert (hindex == hashes_count);
5620 /* Setup internal state */
5621 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5623 /* Handle most of the hashes */
5624 while (hashes_count > 3) {
5633 /* Handle the last 3 hashes (all the case statements fall through) */
5634 switch (hashes_count) {
5635 case 3 : c += hashes [2];
5636 case 2 : b += hashes [1];
5637 case 1 : a += hashes [0];
5639 case 0: /* nothing left to add */
5643 free (hashes_start);
5652 * mono_aot_wrapper_name:
5654 * Return a string which uniqely identifies the given wrapper method.
5657 mono_aot_wrapper_name (MonoMethod *method)
5659 char *name, *tmpsig, *klass_desc;
5661 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5663 switch (method->wrapper_type) {
5664 case MONO_WRAPPER_RUNTIME_INVOKE:
5665 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5666 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5668 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5671 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5672 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5673 g_free (klass_desc);
5683 * mono_aot_get_array_helper_from_wrapper;
5685 * Get the helper method in Array called by an array wrapper method.
5688 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5692 MonoGenericContext ctx;
5693 MonoType *args [16];
5694 char *mname, *iname, *s, *s2, *helper_name = NULL;
5696 prefix = "System.Collections.Generic";
5697 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5698 s2 = strstr (s, "`1.");
5704 //printf ("X: %s %s\n", iname, mname);
5706 if (!strcmp (iname, "IList"))
5707 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5709 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5710 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5712 g_free (helper_name);
5715 if (m->is_generic) {
5716 memset (&ctx, 0, sizeof (ctx));
5717 args [0] = &method->klass->element_class->byval_arg;
5718 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5719 m = mono_class_inflate_generic_method (m, &ctx);
5725 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5727 typedef struct HashEntry {
5728 guint32 key, value, index;
5729 struct HashEntry *next;
5733 * emit_extra_methods:
5735 * Emit methods which are not in the METHOD table, like wrappers.
5738 emit_extra_methods (MonoAotCompile *acfg)
5740 int i, table_size, buf_size;
5743 guint32 *info_offsets;
5746 HashEntry *entry, *new_entry;
5747 int nmethods, max_chain_length;
5750 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5752 /* Emit method info */
5754 for (i = 0; i < acfg->extra_methods->len; ++i) {
5755 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5756 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5763 p = buf = g_malloc (buf_size);
5767 method = cfg->method_to_register;
5770 if (method->wrapper_type) {
5771 gboolean encode_ref = FALSE;
5774 * We encode some wrappers using their name, since encoding them
5775 * directly would be difficult. This works because at runtime, we only need to
5776 * check whenever a method ref matches an existing MonoMethod. The downside is
5777 * that the method names are large, so we use the binary encoding if possible.
5779 switch (method->wrapper_type) {
5780 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5781 case MONO_WRAPPER_SYNCHRONIZED:
5784 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5785 /* Skip JIT icall wrappers */
5786 if (!strstr (method->name, "__icall_wrapper"))
5789 case MONO_WRAPPER_UNKNOWN:
5790 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5793 case MONO_WRAPPER_RUNTIME_INVOKE:
5794 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5795 /* Direct wrapper, encode normally */
5803 name = mono_aot_wrapper_name (method);
5807 encode_value (1, p, &p);
5808 encode_value (method->wrapper_type, p, &p);
5809 strcpy ((char*)p, name);
5810 p += strlen (name ) + 1;
5813 encode_value (0, p, &p);
5814 encode_method_ref (acfg, method, p, &p);
5817 g_assert ((p - buf) < buf_size);
5819 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5824 * Construct a chained hash table for mapping indexes in extra_method_info to
5827 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5828 table = g_ptr_array_sized_new (table_size);
5829 for (i = 0; i < table_size; ++i)
5830 g_ptr_array_add (table, NULL);
5831 chain_lengths = g_new0 (int, table_size);
5832 max_chain_length = 0;
5833 for (i = 0; i < acfg->extra_methods->len; ++i) {
5834 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5835 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5841 key = info_offsets [i];
5842 value = get_method_index (acfg, method);
5844 hash = mono_aot_method_hash (method) % table_size;
5846 chain_lengths [hash] ++;
5847 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5849 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5850 new_entry->key = key;
5851 new_entry->value = value;
5853 entry = g_ptr_array_index (table, hash);
5854 if (entry == NULL) {
5855 new_entry->index = hash;
5856 g_ptr_array_index (table, hash) = new_entry;
5859 entry = entry->next;
5861 entry->next = new_entry;
5862 new_entry->index = table->len;
5863 g_ptr_array_add (table, new_entry);
5867 //printf ("MAX: %d\n", max_chain_length);
5869 /* Emit the table */
5870 sprintf (symbol, "extra_method_table");
5871 emit_section_change (acfg, RODATA_SECT, 0);
5872 emit_alignment (acfg, 8);
5873 emit_label (acfg, symbol);
5875 emit_int32 (acfg, table_size);
5876 for (i = 0; i < table->len; ++i) {
5877 HashEntry *entry = g_ptr_array_index (table, i);
5879 if (entry == NULL) {
5880 emit_int32 (acfg, 0);
5881 emit_int32 (acfg, 0);
5882 emit_int32 (acfg, 0);
5884 //g_assert (entry->key > 0);
5885 emit_int32 (acfg, entry->key);
5886 emit_int32 (acfg, entry->value);
5888 emit_int32 (acfg, entry->next->index);
5890 emit_int32 (acfg, 0);
5895 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5896 * This is used by mono_aot_find_jit_info ().
5898 sprintf (symbol, "extra_method_info_offsets");
5899 emit_section_change (acfg, RODATA_SECT, 0);
5900 emit_alignment (acfg, 8);
5901 emit_label (acfg, symbol);
5903 emit_int32 (acfg, acfg->extra_methods->len);
5904 for (i = 0; i < acfg->extra_methods->len; ++i) {
5905 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5907 emit_int32 (acfg, get_method_index (acfg, method));
5908 emit_int32 (acfg, info_offsets [i]);
5913 emit_exception_info (MonoAotCompile *acfg)
5919 offsets = g_new0 (gint32, acfg->nmethods);
5920 for (i = 0; i < acfg->nmethods; ++i) {
5921 if (acfg->cfgs [i]) {
5922 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5923 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5929 sprintf (symbol, "ex_info_offsets");
5930 emit_section_change (acfg, RODATA_SECT, 1);
5931 emit_alignment (acfg, 8);
5932 emit_label (acfg, symbol);
5934 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5939 emit_unwind_info (MonoAotCompile *acfg)
5945 * The unwind info contains a lot of duplicates so we emit each unique
5946 * entry once, and only store the offset from the start of the table in the
5950 sprintf (symbol, "unwind_info");
5951 emit_section_change (acfg, RODATA_SECT, 1);
5952 emit_alignment (acfg, 8);
5953 emit_label (acfg, symbol);
5955 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5956 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5957 guint8 *unwind_info;
5958 guint32 unwind_info_len;
5962 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5965 encode_value (unwind_info_len, p, &p);
5966 emit_bytes (acfg, buf, p - buf);
5967 emit_bytes (acfg, unwind_info, unwind_info_len);
5969 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5974 emit_class_info (MonoAotCompile *acfg)
5980 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5981 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5982 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5984 sprintf (symbol, "class_info_offsets");
5985 emit_section_change (acfg, RODATA_SECT, 1);
5986 emit_alignment (acfg, 8);
5987 emit_label (acfg, symbol);
5989 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5993 typedef struct ClassNameTableEntry {
5994 guint32 token, index;
5995 struct ClassNameTableEntry *next;
5996 } ClassNameTableEntry;
5999 emit_class_name_table (MonoAotCompile *acfg)
6002 guint32 token, hash;
6007 ClassNameTableEntry *entry, *new_entry;
6010 * Construct a chained hash table for mapping class names to typedef tokens.
6012 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6013 table = g_ptr_array_sized_new (table_size);
6014 for (i = 0; i < table_size; ++i)
6015 g_ptr_array_add (table, NULL);
6016 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6017 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6018 klass = mono_class_get (acfg->image, token);
6020 mono_loader_clear_error ();
6023 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6024 hash = mono_metadata_str_hash (full_name) % table_size;
6027 /* FIXME: Allocate from the mempool */
6028 new_entry = g_new0 (ClassNameTableEntry, 1);
6029 new_entry->token = token;
6031 entry = g_ptr_array_index (table, hash);
6032 if (entry == NULL) {
6033 new_entry->index = hash;
6034 g_ptr_array_index (table, hash) = new_entry;
6037 entry = entry->next;
6039 entry->next = new_entry;
6040 new_entry->index = table->len;
6041 g_ptr_array_add (table, new_entry);
6045 /* Emit the table */
6046 sprintf (symbol, "class_name_table");
6047 emit_section_change (acfg, RODATA_SECT, 0);
6048 emit_alignment (acfg, 8);
6049 emit_label (acfg, symbol);
6051 /* FIXME: Optimize memory usage */
6052 g_assert (table_size < 65000);
6053 emit_int16 (acfg, table_size);
6054 g_assert (table->len < 65000);
6055 for (i = 0; i < table->len; ++i) {
6056 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6058 if (entry == NULL) {
6059 emit_int16 (acfg, 0);
6060 emit_int16 (acfg, 0);
6062 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6064 emit_int16 (acfg, entry->next->index);
6066 emit_int16 (acfg, 0);
6072 emit_image_table (MonoAotCompile *acfg)
6078 * The image table is small but referenced in a lot of places.
6079 * So we emit it at once, and reference its elements by an index.
6082 sprintf (symbol, "image_table");
6083 emit_section_change (acfg, RODATA_SECT, 1);
6084 emit_alignment (acfg, 8);
6085 emit_label (acfg, symbol);
6087 emit_int32 (acfg, acfg->image_table->len);
6088 for (i = 0; i < acfg->image_table->len; i++) {
6089 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6090 MonoAssemblyName *aname = &image->assembly->aname;
6092 /* FIXME: Support multi-module assemblies */
6093 g_assert (image->assembly->image == image);
6095 emit_string (acfg, image->assembly_name);
6096 emit_string (acfg, image->guid);
6097 emit_string (acfg, aname->culture ? aname->culture : "");
6098 emit_string (acfg, (const char*)aname->public_key_token);
6100 emit_alignment (acfg, 8);
6101 emit_int32 (acfg, aname->flags);
6102 emit_int32 (acfg, aname->major);
6103 emit_int32 (acfg, aname->minor);
6104 emit_int32 (acfg, aname->build);
6105 emit_int32 (acfg, aname->revision);
6110 emit_got_info (MonoAotCompile *acfg)
6113 int i, first_plt_got_patch, buf_size;
6115 guint32 *got_info_offsets;
6117 /* Add the patches needed by the PLT to the GOT */
6118 acfg->plt_got_offset_base = acfg->got_offset;
6119 first_plt_got_patch = acfg->got_patches->len;
6120 for (i = 1; i < acfg->plt_offset; ++i) {
6121 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6123 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6126 acfg->got_offset += acfg->plt_offset;
6130 * - optimize offsets table.
6131 * - reduce number of exported symbols.
6132 * - emit info for a klass only once.
6133 * - determine when a method uses a GOT slot which is guaranteed to be already
6135 * - clean up and document the code.
6136 * - use String.Empty in class libs.
6139 /* Encode info required to decode shared GOT entries */
6140 buf_size = acfg->got_patches->len * 128;
6141 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6142 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6143 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6145 if (acfg->plt_offset)
6146 acfg->plt_got_info_offsets [0] = 0;
6147 for (i = 0; i < acfg->got_patches->len; ++i) {
6148 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6152 encode_value (ji->type, p, &p);
6153 encode_patch (acfg, ji, p, &p);
6155 g_assert (p - buf <= buf_size);
6156 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6158 if (i >= first_plt_got_patch)
6159 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6160 acfg->stats.got_info_size += p - buf;
6163 /* Emit got_info_offsets table */
6164 sprintf (symbol, "got_info_offsets");
6165 emit_section_change (acfg, RODATA_SECT, 1);
6166 emit_alignment (acfg, 8);
6167 emit_label (acfg, symbol);
6169 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6170 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6174 emit_got (MonoAotCompile *acfg)
6179 /* Don't make GOT global so accesses to it don't need relocations */
6180 sprintf (symbol, "%s", acfg->got_symbol);
6181 emit_section_change (acfg, ".bss", 0);
6182 emit_alignment (acfg, 8);
6183 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6184 emit_label (acfg, symbol);
6185 if (acfg->got_offset > 0)
6186 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6188 sprintf (symbol, "got_end");
6189 emit_label (acfg, symbol);
6193 typedef struct GlobalsTableEntry {
6194 guint32 value, index;
6195 struct GlobalsTableEntry *next;
6196 } GlobalsTableEntry;
6199 emit_globals (MonoAotCompile *acfg)
6205 GlobalsTableEntry *entry, *new_entry;
6207 if (!acfg->aot_opts.static_link)
6211 * When static linking, we emit a table containing our globals.
6215 * Construct a chained hash table for mapping global names to their index in
6216 * the globals table.
6218 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6219 table = g_ptr_array_sized_new (table_size);
6220 for (i = 0; i < table_size; ++i)
6221 g_ptr_array_add (table, NULL);
6222 for (i = 0; i < acfg->globals->len; ++i) {
6223 char *name = g_ptr_array_index (acfg->globals, i);
6225 hash = mono_metadata_str_hash (name) % table_size;
6227 /* FIXME: Allocate from the mempool */
6228 new_entry = g_new0 (GlobalsTableEntry, 1);
6229 new_entry->value = i;
6231 entry = g_ptr_array_index (table, hash);
6232 if (entry == NULL) {
6233 new_entry->index = hash;
6234 g_ptr_array_index (table, hash) = new_entry;
6237 entry = entry->next;
6239 entry->next = new_entry;
6240 new_entry->index = table->len;
6241 g_ptr_array_add (table, new_entry);
6245 /* Emit the table */
6246 sprintf (symbol, ".Lglobals_hash");
6247 emit_section_change (acfg, RODATA_SECT, 0);
6248 emit_alignment (acfg, 8);
6249 emit_label (acfg, symbol);
6251 /* FIXME: Optimize memory usage */
6252 g_assert (table_size < 65000);
6253 emit_int16 (acfg, table_size);
6254 for (i = 0; i < table->len; ++i) {
6255 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6257 if (entry == NULL) {
6258 emit_int16 (acfg, 0);
6259 emit_int16 (acfg, 0);
6261 emit_int16 (acfg, entry->value + 1);
6263 emit_int16 (acfg, entry->next->index);
6265 emit_int16 (acfg, 0);
6269 /* Emit the names */
6270 for (i = 0; i < acfg->globals->len; ++i) {
6271 char *name = g_ptr_array_index (acfg->globals, i);
6273 sprintf (symbol, "name_%d", i);
6274 emit_section_change (acfg, RODATA_SECT, 1);
6276 emit_alignment (acfg, 4);
6278 emit_label (acfg, symbol);
6279 emit_string (acfg, name);
6282 /* Emit the globals table */
6283 sprintf (symbol, "globals");
6284 emit_section_change (acfg, ".data", 0);
6285 /* This is not a global, since it is accessed by the init function */
6286 emit_alignment (acfg, 8);
6287 emit_label (acfg, symbol);
6289 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6290 emit_pointer (acfg, symbol);
6292 for (i = 0; i < acfg->globals->len; ++i) {
6293 char *name = g_ptr_array_index (acfg->globals, i);
6295 sprintf (symbol, "name_%d", i);
6296 emit_pointer (acfg, symbol);
6298 sprintf (symbol, "%s", name);
6299 emit_pointer (acfg, symbol);
6301 /* Null terminate the table */
6302 emit_int32 (acfg, 0);
6303 emit_int32 (acfg, 0);
6307 emit_autoreg (MonoAotCompile *acfg)
6312 * Emit a function into the .ctor section which will be called by the ELF
6313 * loader to register this module with the runtime.
6315 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6318 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6320 arch_emit_autoreg (acfg, symbol);
6326 emit_mem_end (MonoAotCompile *acfg)
6330 sprintf (symbol, "mem_end");
6331 emit_section_change (acfg, ".text", 1);
6332 emit_alignment (acfg, 8);
6333 emit_label (acfg, symbol);
6337 * Emit a structure containing all the information not stored elsewhere.
6340 emit_file_info (MonoAotCompile *acfg)
6345 const char *gc_name;
6348 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6350 if (acfg->aot_opts.bind_to_runtime_version) {
6351 build_info = mono_get_runtime_build_info ();
6352 emit_string_symbol (acfg, "runtime_version", build_info);
6353 g_free (build_info);
6355 emit_string_symbol (acfg, "runtime_version", "");
6358 /* Emit a string holding the assembly name */
6359 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6362 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6365 gc_name = mono_gc_get_gc_name ();
6366 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6368 sprintf (symbol, "mono_aot_file_info");
6369 emit_section_change (acfg, ".data", 0);
6370 emit_alignment (acfg, 8);
6371 emit_label (acfg, symbol);
6372 if (!acfg->aot_opts.static_link)
6373 emit_global (acfg, symbol, FALSE);
6375 /* The data emitted here must match MonoAotFileInfo. */
6377 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6378 emit_int32 (acfg, 0);
6381 * We emit pointers to our data structures instead of emitting global symbols which
6382 * point to them, to reduce the number of globals, and because using globals leads to
6383 * various problems (i.e. arm/thumb).
6385 emit_pointer (acfg, acfg->got_symbol);
6386 emit_pointer (acfg, "methods");
6389 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6391 emit_pointer (acfg, "mono_eh_frame");
6393 emit_pointer (acfg, NULL);
6395 emit_pointer (acfg, "blob");
6396 emit_pointer (acfg, "class_name_table");
6397 emit_pointer (acfg, "class_info_offsets");
6398 emit_pointer (acfg, "method_info_offsets");
6399 emit_pointer (acfg, "ex_info_offsets");
6400 emit_pointer (acfg, "code_offsets");
6401 emit_pointer (acfg, "extra_method_info_offsets");
6402 emit_pointer (acfg, "extra_method_table");
6403 emit_pointer (acfg, "got_info_offsets");
6404 emit_pointer (acfg, "methods_end");
6405 emit_pointer (acfg, "unwind_info");
6406 emit_pointer (acfg, "mem_end");
6407 emit_pointer (acfg, "image_table");
6408 emit_pointer (acfg, "plt");
6409 emit_pointer (acfg, "plt_end");
6410 emit_pointer (acfg, "assembly_guid");
6411 emit_pointer (acfg, "runtime_version");
6412 if (acfg->num_trampoline_got_entries) {
6413 emit_pointer (acfg, "specific_trampolines");
6414 emit_pointer (acfg, "static_rgctx_trampolines");
6415 emit_pointer (acfg, "imt_thunks");
6417 emit_pointer (acfg, NULL);
6418 emit_pointer (acfg, NULL);
6419 emit_pointer (acfg, NULL);
6421 if (acfg->thumb_mixed) {
6422 emit_pointer (acfg, "thumb_end");
6424 emit_pointer (acfg, NULL);
6426 if (acfg->aot_opts.static_link) {
6427 emit_pointer (acfg, "globals");
6429 emit_pointer (acfg, NULL);
6431 emit_pointer (acfg, "assembly_name");
6433 emit_int32 (acfg, acfg->plt_got_offset_base);
6434 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6435 emit_int32 (acfg, acfg->plt_offset);
6436 emit_int32 (acfg, acfg->nmethods);
6437 emit_int32 (acfg, acfg->flags);
6438 emit_int32 (acfg, acfg->opts);
6439 emit_int32 (acfg, gc_name_offset);
6441 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6442 emit_int32 (acfg, acfg->num_trampolines [i]);
6443 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6444 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6445 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6446 emit_int32 (acfg, acfg->trampoline_size [i]);
6448 #if defined (TARGET_ARM) && defined (__APPLE__)
6453 t.type = MONO_TYPE_R8;
6454 mono_type_size (&t, &align);
6456 emit_int32 (acfg, align);
6458 t.type = MONO_TYPE_I8;
6459 mono_type_size (&t, &align);
6461 emit_int32 (acfg, align);
6464 emit_int32 (acfg, __alignof__ (double));
6465 emit_int32 (acfg, __alignof__ (gint64));
6468 if (acfg->aot_opts.static_link) {
6472 * Emit a global symbol which can be passed by an embedding app to
6473 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6476 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6477 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6479 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6482 /* Get rid of characters which cannot occur in symbols */
6484 for (p = symbol; *p; ++p) {
6485 if (!(isalnum (*p) || *p == '_'))
6488 acfg->static_linking_symbol = g_strdup (symbol);
6489 emit_global_inner (acfg, symbol, FALSE);
6490 emit_label (acfg, symbol);
6491 emit_pointer (acfg, "mono_aot_file_info");
6496 emit_blob (MonoAotCompile *acfg)
6500 sprintf (symbol, "blob");
6501 emit_section_change (acfg, RODATA_SECT, 1);
6502 emit_alignment (acfg, 8);
6503 emit_label (acfg, symbol);
6505 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6509 emit_dwarf_info (MonoAotCompile *acfg)
6511 #ifdef EMIT_DWARF_INFO
6513 char symbol [128], symbol2 [128];
6515 /* DIEs for methods */
6516 for (i = 0; i < acfg->nmethods; ++i) {
6517 MonoCompile *cfg = acfg->cfgs [i];
6522 // FIXME: LLVM doesn't define .Lme_...
6523 if (cfg->compile_llvm)
6526 sprintf (symbol, "%s", cfg->asm_symbol);
6527 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6529 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 ()));
6535 collect_methods (MonoAotCompile *acfg)
6538 MonoImage *image = acfg->image;
6540 /* Collect methods */
6541 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6543 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6545 method = mono_get_method (acfg->image, token, NULL);
6548 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6552 /* Load all methods eagerly to skip the slower lazy loading code */
6553 mono_class_setup_methods (method->klass);
6555 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6556 /* Compile the wrapper instead */
6557 /* We do this here instead of add_wrappers () because it is easy to do it here */
6558 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6562 /* FIXME: Some mscorlib methods don't have debug info */
6564 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6565 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6566 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6567 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6568 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6569 if (!mono_debug_lookup_method (method)) {
6570 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6577 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6578 add_method_with_index (acfg, method, i, FALSE);
6579 acfg->method_index ++;
6582 add_generic_instances (acfg);
6584 if (acfg->aot_opts.full_aot)
6585 add_wrappers (acfg);
6589 compile_methods (MonoAotCompile *acfg)
6593 if (acfg->aot_opts.nthreads > 0) {
6598 gpointer *user_data;
6599 MonoMethod **methods;
6601 methods_len = acfg->methods->len;
6603 len = acfg->methods->len / acfg->aot_opts.nthreads;
6606 * Partition the list of methods into fragments, and hand it to threads to
6609 threads = g_ptr_array_new ();
6610 /* Make a copy since acfg->methods is modified by compile_method () */
6611 methods = g_new0 (MonoMethod*, methods_len);
6612 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6613 for (i = 0; i < methods_len; ++i)
6614 methods [i] = g_ptr_array_index (acfg->methods, i);
6616 while (i < methods_len) {
6617 frag = g_ptr_array_new ();
6618 for (j = 0; j < len; ++j) {
6619 if (i < methods_len) {
6620 g_ptr_array_add (frag, methods [i]);
6625 user_data = g_new0 (gpointer, 3);
6626 user_data [0] = mono_domain_get ();
6627 user_data [1] = acfg;
6628 user_data [2] = frag;
6630 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6631 g_ptr_array_add (threads, handle);
6635 for (i = 0; i < threads->len; ++i) {
6636 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6642 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6643 for (i = methods_len; i < acfg->methods->len; ++i) {
6644 /* This can new methods to acfg->methods */
6645 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6650 compile_asm (MonoAotCompile *acfg)
6652 char *command, *objfile;
6653 char *outfile_name, *tmp_outfile_name;
6654 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6656 #if defined(TARGET_AMD64)
6657 #define AS_OPTIONS "--64"
6658 #elif defined(TARGET_POWERPC64)
6659 #define AS_OPTIONS "-a64 -mppc64"
6660 #define LD_OPTIONS "-m elf64ppc"
6661 #elif defined(sparc) && SIZEOF_VOID_P == 8
6662 #define AS_OPTIONS "-xarch=v9"
6663 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6664 #define AS_OPTIONS "-arch i386 -W"
6666 #define AS_OPTIONS ""
6669 #ifdef __native_client_codegen__
6670 #if defined(TARGET_AMD64)
6671 #define AS_NAME "nacl64-as"
6673 #define AS_NAME "nacl-as"
6676 #define AS_NAME "as"
6680 #define LD_OPTIONS ""
6683 #define EH_LD_OPTIONS ""
6685 if (acfg->aot_opts.asm_only) {
6686 printf ("Output file: '%s'.\n", acfg->tmpfname);
6687 if (acfg->aot_opts.static_link)
6688 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6692 if (acfg->aot_opts.static_link) {
6693 if (acfg->aot_opts.outfile)
6694 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6696 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6698 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6700 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);
6701 printf ("Executing the native assembler: %s\n", command);
6702 if (system (command) != 0) {
6710 if (acfg->aot_opts.static_link) {
6711 printf ("Output file: '%s'.\n", objfile);
6712 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6717 if (acfg->aot_opts.outfile)
6718 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6720 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6722 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6725 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6726 #elif defined(__ppc__) && defined(__APPLE__)
6727 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6728 #elif defined(HOST_WIN32)
6729 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6730 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6731 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6733 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6735 printf ("Executing the native linker: %s\n", command);
6736 if (system (command) != 0) {
6737 g_free (tmp_outfile_name);
6738 g_free (outfile_name);
6746 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6747 printf ("Stripping the binary: %s\n", com);
6751 #if defined(TARGET_ARM) && !defined(__APPLE__)
6753 * gas generates 'mapping symbols' each time code and data is mixed, which
6754 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6756 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6757 printf ("Stripping the binary: %s\n", command);
6758 if (system (command) != 0) {
6759 g_free (tmp_outfile_name);
6760 g_free (outfile_name);
6767 rename (tmp_outfile_name, outfile_name);
6769 g_free (tmp_outfile_name);
6770 g_free (outfile_name);
6773 if (acfg->aot_opts.save_temps)
6774 printf ("Retained input file.\n");
6776 unlink (acfg->tmpfname);
6781 static MonoAotCompile*
6782 acfg_create (MonoAssembly *ass, guint32 opts)
6784 MonoImage *image = ass->image;
6785 MonoAotCompile *acfg;
6788 acfg = g_new0 (MonoAotCompile, 1);
6789 acfg->methods = g_ptr_array_new ();
6790 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6791 acfg->method_depth = g_hash_table_new (NULL, NULL);
6792 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6793 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6794 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6795 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6796 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6797 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6798 acfg->got_patches = g_ptr_array_new ();
6799 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6800 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6801 acfg->image_hash = g_hash_table_new (NULL, NULL);
6802 acfg->image_table = g_ptr_array_new ();
6803 acfg->globals = g_ptr_array_new ();
6804 acfg->image = image;
6806 acfg->mempool = mono_mempool_new ();
6807 acfg->extra_methods = g_ptr_array_new ();
6808 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6809 acfg->unwind_ops = g_ptr_array_new ();
6810 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6811 acfg->method_order = g_ptr_array_new ();
6812 InitializeCriticalSection (&acfg->mutex);
6818 acfg_free (MonoAotCompile *acfg)
6822 img_writer_destroy (acfg->w);
6823 for (i = 0; i < acfg->nmethods; ++i)
6825 g_free (acfg->cfgs [i]);
6826 g_free (acfg->cfgs);
6827 g_free (acfg->static_linking_symbol);
6828 g_free (acfg->got_symbol);
6829 g_free (acfg->plt_symbol);
6830 g_ptr_array_free (acfg->methods, TRUE);
6831 g_ptr_array_free (acfg->got_patches, TRUE);
6832 g_ptr_array_free (acfg->image_table, TRUE);
6833 g_ptr_array_free (acfg->globals, TRUE);
6834 g_ptr_array_free (acfg->unwind_ops, TRUE);
6835 g_hash_table_destroy (acfg->method_indexes);
6836 g_hash_table_destroy (acfg->method_depth);
6837 g_hash_table_destroy (acfg->plt_offset_to_entry);
6838 g_hash_table_destroy (acfg->patch_to_plt_entry);
6839 g_hash_table_destroy (acfg->patch_to_got_offset);
6840 g_hash_table_destroy (acfg->method_to_cfg);
6841 g_hash_table_destroy (acfg->token_info_hash);
6842 g_hash_table_destroy (acfg->image_hash);
6843 g_hash_table_destroy (acfg->unwind_info_offsets);
6844 g_hash_table_destroy (acfg->method_label_hash);
6845 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6846 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6847 g_free (acfg->patch_to_got_offset_by_type);
6848 mono_mempool_destroy (acfg->mempool);
6853 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6855 MonoImage *image = ass->image;
6857 MonoAotCompile *acfg;
6858 char *outfile_name, *tmp_outfile_name, *p;
6862 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6864 acfg = acfg_create (ass, opts);
6866 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6867 acfg->aot_opts.write_symbols = TRUE;
6868 acfg->aot_opts.ntrampolines = 1024;
6869 acfg->aot_opts.nrgctx_trampolines = 1024;
6870 acfg->aot_opts.nimt_trampolines = 128;
6871 acfg->aot_opts.llvm_path = g_strdup ("");
6873 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6875 if (acfg->aot_opts.static_link)
6876 acfg->aot_opts.autoreg = TRUE;
6878 //acfg->aot_opts.print_skipped_methods = TRUE;
6880 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6881 if (acfg->aot_opts.full_aot) {
6882 printf ("--aot=full is not supported on this platform.\n");
6887 if (acfg->aot_opts.static_link)
6888 acfg->aot_opts.asm_writer = TRUE;
6890 if (acfg->aot_opts.soft_debug) {
6891 MonoDebugOptions *opt = mini_get_debug_options ();
6893 opt->mdb_optimizations = TRUE;
6894 opt->gen_seq_points = TRUE;
6896 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6897 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6900 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6903 if (mono_use_llvm) {
6905 acfg->aot_opts.asm_writer = TRUE;
6906 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6908 if (acfg->aot_opts.soft_debug) {
6909 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6914 if (acfg->aot_opts.full_aot)
6915 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6917 load_profile_files (acfg);
6919 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6920 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6921 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6923 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6925 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6929 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6930 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6932 /* Get rid of characters which cannot occur in symbols */
6933 for (p = acfg->got_symbol_base; *p; ++p) {
6934 if (!(isalnum (*p) || *p == '_'))
6937 for (p = acfg->plt_symbol; *p; ++p) {
6938 if (!(isalnum (*p) || *p == '_'))
6942 acfg->method_index = 1;
6944 collect_methods (acfg);
6946 acfg->cfgs_size = acfg->methods->len + 32;
6947 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6949 /* PLT offset 0 is reserved for the PLT trampoline */
6950 acfg->plt_offset = 1;
6955 mono_llvm_create_aot_module (acfg->got_symbol_base);
6959 /* GOT offset 0 is reserved for the address of the current assembly */
6963 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6964 ji->type = MONO_PATCH_INFO_IMAGE;
6965 ji->data.image = acfg->image;
6967 get_got_offset (acfg, ji);
6969 /* Slot 1 is reserved for the mscorlib got addr */
6970 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6971 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6972 get_got_offset (acfg, ji);
6974 /* This is very common */
6975 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6976 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6977 get_got_offset (acfg, ji);
6982 compile_methods (acfg);
6986 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6992 if (acfg->aot_opts.asm_only) {
6993 if (acfg->aot_opts.outfile)
6994 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6996 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6998 acfg->tmpfname = g_strdup ("temp.s");
7001 emit_llvm_file (acfg);
7005 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7006 if (acfg->aot_opts.outfile)
7007 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7009 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7012 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7013 * it might be in another file system so the rename () won't work.
7015 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7017 acfg->fp = fopen (tmp_outfile_name, "w");
7019 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7023 acfg->w = img_writer_create (acfg->fp, TRUE);
7024 acfg->use_bin_writer = TRUE;
7027 /* Append to the .s file created by llvm */
7028 /* FIXME: Use multiple files instead */
7029 acfg->fp = fopen (acfg->tmpfname, "a+");
7031 if (acfg->aot_opts.asm_only) {
7032 if (acfg->aot_opts.outfile)
7033 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7035 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7036 acfg->fp = fopen (acfg->tmpfname, "w+");
7038 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7039 acfg->fp = fdopen (i, "w+");
7041 g_assert (acfg->fp);
7043 acfg->w = img_writer_create (acfg->fp, FALSE);
7045 tmp_outfile_name = NULL;
7046 outfile_name = NULL;
7049 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7051 /* Compute symbols for methods */
7052 for (i = 0; i < acfg->nmethods; ++i) {
7053 if (acfg->cfgs [i]) {
7054 MonoCompile *cfg = acfg->cfgs [i];
7055 int method_index = get_method_index (acfg, cfg->orig_method);
7057 if (COMPILE_LLVM (cfg))
7058 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7060 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7064 if (!acfg->aot_opts.nodebug)
7065 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7067 img_writer_emit_start (acfg->w);
7070 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7072 if (acfg->thumb_mixed) {
7075 * This global symbol marks the end of THUMB code, and the beginning of ARM
7076 * code generated by our JIT.
7078 sprintf (symbol, "thumb_end");
7079 emit_section_change (acfg, ".text", 0);
7080 emit_label (acfg, symbol);
7081 emit_zero_bytes (acfg, 16);
7083 fprintf (acfg->fp, ".arm\n");
7090 emit_extra_methods (acfg);
7092 emit_trampolines (acfg);
7094 emit_class_name_table (acfg);
7096 emit_got_info (acfg);
7098 emit_exception_info (acfg);
7100 emit_unwind_info (acfg);
7102 emit_class_info (acfg);
7106 emit_image_table (acfg);
7110 emit_file_info (acfg);
7114 emit_globals (acfg);
7116 emit_autoreg (acfg);
7119 emit_dwarf_info (acfg);
7120 mono_dwarf_writer_close (acfg->dwarf);
7123 emit_mem_end (acfg);
7125 if (acfg->need_pt_gnu_stack) {
7126 /* This is required so the .so doesn't have an executable stack */
7127 /* The bin writer already emits this */
7128 if (!acfg->use_bin_writer)
7129 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7134 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7137 g_assert (acfg->got_offset <= acfg->final_got_size);
7139 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);
7142 res = img_writer_emit_writeout (acfg->w);
7147 if (acfg->use_bin_writer) {
7148 int err = rename (tmp_outfile_name, outfile_name);
7151 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7155 res = compile_asm (acfg);
7162 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7164 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);
7165 if (acfg->stats.genericcount)
7166 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7167 if (acfg->stats.abscount)
7168 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7169 if (acfg->stats.lmfcount)
7170 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7171 if (acfg->stats.ocount)
7172 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7174 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7175 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);
7176 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7178 if (acfg->aot_opts.stats) {
7181 printf ("GOT slot distribution:\n");
7182 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7183 if (acfg->stats.got_slot_types [i])
7184 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7187 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);
7199 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)