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;
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);
2091 g_assert_not_reached ();
2095 g_assert_not_reached ();
2097 } else if (mono_method_signature (method)->is_inflated) {
2099 * This is a generic method, find the original token which referenced it and
2101 * Obtain the token from information recorded by the JIT.
2103 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2105 image_index = get_image_index (acfg, ji->image);
2106 g_assert (image_index < MAX_IMAGE_INDEX);
2109 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2110 encode_value (image_index, p, &p);
2111 encode_value (token, p, &p);
2113 MonoMethod *declaring;
2114 MonoGenericContext *context = mono_method_get_context (method);
2116 g_assert (method->is_inflated);
2117 declaring = ((MonoMethodInflated*)method)->declaring;
2120 * This might be a non-generic method of a generic instance, which
2121 * doesn't have a token since the reference is generated by the JIT
2122 * like Nullable:Box/Unbox, or by generic sharing.
2125 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2126 /* Encode the klass */
2127 encode_klass_ref (acfg, method->klass, p, &p);
2128 /* Encode the method */
2129 image_index = get_image_index (acfg, method->klass->image);
2130 g_assert (image_index < MAX_IMAGE_INDEX);
2131 g_assert (declaring->token);
2132 token = declaring->token;
2133 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2134 encode_value (image_index, p, &p);
2135 encode_value (token, p, &p);
2136 encode_generic_context (acfg, context, p, &p);
2138 } else if (token == 0) {
2139 /* This might be a method of a constructed type like int[,].Set */
2140 /* Obtain the token from information recorded by the JIT */
2141 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2143 image_index = get_image_index (acfg, ji->image);
2144 g_assert (image_index < MAX_IMAGE_INDEX);
2147 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2148 encode_value (image_index, p, &p);
2149 encode_value (token, p, &p);
2152 g_assert (method->klass->rank);
2154 /* Encode directly */
2155 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2156 encode_klass_ref (acfg, method->klass, p, &p);
2157 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2158 encode_value (0, p, &p);
2159 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2160 encode_value (1, p, &p);
2161 else if (!strcmp (method->name, "Get"))
2162 encode_value (2, p, &p);
2163 else if (!strcmp (method->name, "Address"))
2164 encode_value (3, p, &p);
2165 else if (!strcmp (method->name, "Set"))
2166 encode_value (4, p, &p);
2168 g_assert_not_reached ();
2171 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2172 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2178 compare_patches (gconstpointer a, gconstpointer b)
2182 i = (*(MonoJumpInfo**)a)->ip.i;
2183 j = (*(MonoJumpInfo**)b)->ip.i;
2194 static G_GNUC_UNUSED char*
2195 patch_to_string (MonoJumpInfo *patch_info)
2199 str = g_string_new ("");
2201 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2203 switch (patch_info->type) {
2204 case MONO_PATCH_INFO_VTABLE:
2205 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2210 g_string_append_printf (str, ")");
2211 return g_string_free (str, FALSE);
2217 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2220 static inline gboolean
2221 is_plt_patch (MonoJumpInfo *patch_info)
2223 switch (patch_info->type) {
2224 case MONO_PATCH_INFO_METHOD:
2225 case MONO_PATCH_INFO_INTERNAL_METHOD:
2226 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2227 case MONO_PATCH_INFO_ICALL_ADDR:
2228 case MONO_PATCH_INFO_CLASS_INIT:
2229 case MONO_PATCH_INFO_RGCTX_FETCH:
2230 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2231 case MONO_PATCH_INFO_MONITOR_ENTER:
2232 case MONO_PATCH_INFO_MONITOR_EXIT:
2233 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2243 * Return the symbol identifying the plt entry PLT_OFFSET.
2246 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2250 * The Apple linker reorganizes object files, so it doesn't like branches to local
2251 * labels, since those have no relocations.
2253 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2255 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2262 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2264 static MonoPltEntry*
2265 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2269 if (!is_plt_patch (patch_info))
2272 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2274 // FIXME: This breaks the calculation of final_got_size
2275 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2277 * Allocate a separate PLT slot for each such patch, since some plt
2278 * entries will refer to the method itself, and some will refer to the
2285 MonoJumpInfo *new_ji;
2287 g_assert (!acfg->final_got_size);
2289 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2291 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2292 res->plt_offset = acfg->plt_offset;
2294 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2295 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2297 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2299 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2301 acfg->plt_offset ++;
2310 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2311 * JI could be found if it exists, otherwise allocates a new one.
2314 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2318 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2320 return got_offset - 1;
2322 got_offset = acfg->got_offset;
2323 acfg->got_offset ++;
2325 if (acfg->final_got_size)
2326 g_assert (got_offset < acfg->final_got_size);
2328 acfg->stats.got_slots ++;
2329 acfg->stats.got_slot_types [ji->type] ++;
2331 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2332 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2333 g_ptr_array_add (acfg->got_patches, ji);
2338 /* Add a method to the list of methods which need to be emitted */
2340 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2343 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2344 g_ptr_array_add (acfg->methods, method);
2345 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2346 acfg->nmethods = acfg->methods->len + 1;
2349 if (method->wrapper_type || extra)
2350 g_ptr_array_add (acfg->extra_methods, method);
2354 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2356 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2364 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2368 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2372 index = acfg->method_index;
2373 add_method_with_index (acfg, method, index, extra);
2375 /* FIXME: Fix quadratic behavior */
2376 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2378 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2380 acfg->method_index ++;
2386 add_method (MonoAotCompile *acfg, MonoMethod *method)
2388 return add_method_full (acfg, method, FALSE, 0);
2392 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2394 add_method_full (acfg, method, TRUE, 0);
2398 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2400 add_method_full (acfg, method, TRUE, depth);
2404 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2406 MonoAotCompile *acfg = user_data;
2407 MonoJitICallInfo *callinfo = value;
2408 MonoMethod *wrapper;
2414 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2415 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2418 add_method (acfg, wrapper);
2422 get_runtime_invoke_sig (MonoMethodSignature *sig)
2424 MonoMethodBuilder *mb;
2427 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2428 m = mono_mb_create_method (mb, sig, 16);
2429 return mono_marshal_get_runtime_invoke (m, FALSE);
2433 can_marshal_struct (MonoClass *klass)
2435 MonoClassField *field;
2436 gboolean can_marshal = TRUE;
2437 gpointer iter = NULL;
2439 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2442 /* Only allow a few field types to avoid asserts in the marshalling code */
2443 while ((field = mono_class_get_fields (klass, &iter))) {
2444 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2447 switch (field->type->type) {
2452 case MONO_TYPE_BOOLEAN:
2455 case MONO_TYPE_CHAR:
2463 case MONO_TYPE_STRING:
2465 case MONO_TYPE_VALUETYPE:
2466 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2467 can_marshal = FALSE;
2470 can_marshal = FALSE;
2476 /* Its hard to compute whenever these can be marshalled or not */
2477 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2484 add_wrappers (MonoAotCompile *acfg)
2486 MonoMethod *method, *m;
2488 MonoMethodSignature *sig, *csig;
2492 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2493 * so there is only one wrapper of a given type, or inlining their contents into their
2498 * FIXME: This depends on the fact that different wrappers have different
2502 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2504 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2505 gboolean skip = FALSE;
2507 method = mono_get_method (acfg->image, token, NULL);
2509 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2510 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2511 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2514 if (method->is_generic || method->klass->generic_container)
2517 /* Skip methods which can not be handled by get_runtime_invoke () */
2518 sig = mono_method_signature (method);
2521 if ((sig->ret->type == MONO_TYPE_PTR) ||
2522 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2525 for (j = 0; j < sig->param_count; j++) {
2526 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2530 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2531 if (!method->klass->contextbound) {
2532 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2533 gboolean has_nullable = FALSE;
2535 for (j = 0; j < sig->param_count; j++) {
2536 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2537 has_nullable = TRUE;
2540 if (info && !has_nullable) {
2541 /* Supported by the dynamic runtime-invoke wrapper */
2549 //printf ("%s\n", mono_method_full_name (method, TRUE));
2550 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2554 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2555 #ifdef MONO_ARCH_HAVE_TLS_GET
2556 MonoMethodDesc *desc;
2557 MonoMethod *orig_method;
2561 /* Runtime invoke wrappers */
2563 /* void runtime-invoke () [.cctor] */
2564 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2565 csig->ret = &mono_defaults.void_class->byval_arg;
2566 add_method (acfg, get_runtime_invoke_sig (csig));
2568 /* void runtime-invoke () [Finalize] */
2569 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2571 csig->ret = &mono_defaults.void_class->byval_arg;
2572 add_method (acfg, get_runtime_invoke_sig (csig));
2574 /* void runtime-invoke (string) [exception ctor] */
2575 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2577 csig->ret = &mono_defaults.void_class->byval_arg;
2578 csig->params [0] = &mono_defaults.string_class->byval_arg;
2579 add_method (acfg, get_runtime_invoke_sig (csig));
2581 /* void runtime-invoke (string, string) [exception ctor] */
2582 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2584 csig->ret = &mono_defaults.void_class->byval_arg;
2585 csig->params [0] = &mono_defaults.string_class->byval_arg;
2586 csig->params [1] = &mono_defaults.string_class->byval_arg;
2587 add_method (acfg, get_runtime_invoke_sig (csig));
2589 /* string runtime-invoke () [Exception.ToString ()] */
2590 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2592 csig->ret = &mono_defaults.string_class->byval_arg;
2593 add_method (acfg, get_runtime_invoke_sig (csig));
2595 /* void runtime-invoke (string, Exception) [exception ctor] */
2596 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2598 csig->ret = &mono_defaults.void_class->byval_arg;
2599 csig->params [0] = &mono_defaults.string_class->byval_arg;
2600 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2601 add_method (acfg, get_runtime_invoke_sig (csig));
2603 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2604 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2606 csig->ret = &(mono_class_from_name (
2607 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2608 csig->params [0] = &mono_defaults.string_class->byval_arg;
2609 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2610 add_method (acfg, get_runtime_invoke_sig (csig));
2612 /* runtime-invoke used by finalizers */
2613 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2615 /* This is used by mono_runtime_capture_context () */
2616 method = mono_get_context_capture_method ();
2618 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2620 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2621 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2624 /* JIT icall wrappers */
2625 /* FIXME: locking */
2626 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2629 add_method (acfg, mono_marshal_get_stelemref ());
2631 #ifdef MONO_ARCH_HAVE_TLS_GET
2632 /* Managed Allocators */
2633 nallocators = mono_gc_get_managed_allocator_types ();
2634 for (i = 0; i < nallocators; ++i) {
2635 m = mono_gc_get_managed_allocator_by_type (i);
2637 add_method (acfg, m);
2640 /* Monitor Enter/Exit */
2641 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2642 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2643 g_assert (orig_method);
2644 mono_method_desc_free (desc);
2645 method = mono_monitor_get_fast_path (orig_method);
2647 add_method (acfg, method);
2649 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2650 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2651 g_assert (orig_method);
2652 mono_method_desc_free (desc);
2653 method = mono_monitor_get_fast_path (orig_method);
2655 add_method (acfg, method);
2658 /* Stelemref wrappers */
2659 /* There is only a constant number of these, iterating over all types should handle them all */
2660 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2663 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2664 klass = mono_class_get (acfg->image, token);
2666 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2669 /* castclass_with_check wrapper */
2670 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2674 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2675 * we use the original method instead at runtime.
2676 * Since full-aot doesn't support remoting, this is not a problem.
2679 /* remoting-invoke wrappers */
2680 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2681 MonoMethodSignature *sig;
2683 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2684 method = mono_get_method (acfg->image, token, NULL);
2686 sig = mono_method_signature (method);
2688 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2689 m = mono_marshal_get_remoting_invoke_with_check (method);
2691 add_method (acfg, m);
2696 /* delegate-invoke wrappers */
2697 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2700 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2701 klass = mono_class_get (acfg->image, token);
2703 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2704 method = mono_get_delegate_invoke (klass);
2706 m = mono_marshal_get_delegate_invoke (method, NULL);
2708 add_method (acfg, m);
2710 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2711 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2713 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2714 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2718 /* Synchronized wrappers */
2719 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2720 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2721 method = mono_get_method (acfg->image, token, NULL);
2723 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2724 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2727 /* pinvoke wrappers */
2728 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2730 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2732 method = mono_get_method (acfg->image, token, NULL);
2734 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2735 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2736 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2740 /* native-to-managed wrappers */
2741 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2743 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2744 MonoCustomAttrInfo *cattr;
2747 method = mono_get_method (acfg->image, token, NULL);
2750 * Only generate native-to-managed wrappers for methods which have an
2751 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2752 * name to avoid defining a new assembly to contain it.
2754 cattr = mono_custom_attrs_from_method (method);
2757 for (j = 0; j < cattr->num_attrs; ++j)
2758 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2760 if (j < cattr->num_attrs) {
2761 MonoCustomAttrEntry *e = &cattr->attrs [j];
2762 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2763 const char *p = (const char*)e->data;
2769 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2771 g_assert (sig->param_count == 1);
2772 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2775 * Decode the cattr manually since we can't create objects
2776 * during aot compilation.
2782 /* From load_cattr_value () in reflection.c */
2783 slen = mono_metadata_decode_value (p, &p);
2784 n = g_memdup (p, slen + 1);
2786 t = mono_reflection_type_from_name (n, acfg->image);
2790 klass = mono_class_from_mono_type (t);
2791 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2793 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2797 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2798 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2799 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2803 /* StructureToPtr/PtrToStructure wrappers */
2804 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2807 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2808 klass = mono_class_get (acfg->image, token);
2810 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2811 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2812 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2818 has_type_vars (MonoClass *klass)
2820 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2823 return has_type_vars (klass->element_class);
2824 if (klass->generic_class) {
2825 MonoGenericContext *context = &klass->generic_class->context;
2826 if (context->class_inst) {
2829 for (i = 0; i < context->class_inst->type_argc; ++i)
2830 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2838 method_has_type_vars (MonoMethod *method)
2840 if (has_type_vars (method->klass))
2843 if (method->is_inflated) {
2844 MonoGenericContext *context = mono_method_get_context (method);
2845 if (context->method_inst) {
2848 for (i = 0; i < context->method_inst->type_argc; ++i)
2849 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2856 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2859 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2861 /* This might lead to a huge code blowup so only do it if neccesary */
2862 if (!acfg->aot_opts.full_aot && !force)
2865 add_generic_class_with_depth (acfg, klass, 0);
2869 check_type_depth (MonoType *t, int depth)
2877 case MONO_TYPE_GENERICINST: {
2878 MonoGenericClass *gklass = t->data.generic_class;
2879 MonoGenericInst *ginst = gklass->context.class_inst;
2882 for (i = 0; i < ginst->type_argc; ++i) {
2883 if (check_type_depth (ginst->type_argv [i], depth + 1))
2897 * add_generic_class:
2899 * Add all methods of a generic class.
2902 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2907 mono_class_init (klass);
2909 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2912 if (has_type_vars (klass))
2915 if (!klass->generic_class && !klass->rank)
2918 if (check_type_depth (&klass->byval_arg, 0))
2922 while ((method = mono_class_get_methods (klass, &iter))) {
2923 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2927 if (method->is_generic)
2932 * FIXME: Instances which are referenced by these methods are not added,
2933 * for example Array.Resize<int> for List<int>.Add ().
2935 add_extra_method_with_depth (acfg, method, depth + 1);
2938 if (klass->delegate) {
2939 method = mono_get_delegate_invoke (klass);
2941 method = mono_marshal_get_delegate_invoke (method, NULL);
2943 add_method (acfg, method);
2947 * For ICollection<T>, add instances of the helper methods
2948 * in Array, since a T[] could be cast to ICollection<T>.
2950 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2951 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2952 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2953 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2957 if (!strcmp (klass->name, "IEnumerator`1"))
2958 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2960 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2962 /* Add the T[]/InternalEnumerator class */
2963 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2967 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2968 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2972 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2973 add_generic_class (acfg, nclass, FALSE);
2977 while ((method = mono_class_get_methods (array_class, &iter))) {
2978 if (strstr (method->name, name_prefix)) {
2979 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2980 add_extra_method_with_depth (acfg, m, depth);
2984 g_free (name_prefix);
2987 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2988 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2989 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2990 MonoClass *icomparable, *gcomparer;
2991 MonoGenericContext ctx;
2992 MonoType *args [16];
2994 memset (&ctx, 0, sizeof (ctx));
2996 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2997 g_assert (icomparable);
2998 args [0] = &tclass->byval_arg;
2999 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3001 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3002 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3003 g_assert (gcomparer);
3004 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3008 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3009 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3010 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3011 MonoClass *iface, *gcomparer;
3012 MonoGenericContext ctx;
3013 MonoType *args [16];
3015 memset (&ctx, 0, sizeof (ctx));
3017 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3019 args [0] = &tclass->byval_arg;
3020 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3022 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3023 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3024 g_assert (gcomparer);
3025 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3031 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3034 MonoGenericContext ctx;
3035 MonoType *args [16];
3037 memset (&ctx, 0, sizeof (ctx));
3039 for (i = 0; i < ninsts; ++i) {
3040 args [0] = insts [i];
3041 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3042 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3047 * add_generic_instances:
3049 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3052 add_generic_instances (MonoAotCompile *acfg)
3057 MonoMethodHeader *header;
3058 MonoMethodSignature *sig;
3059 MonoGenericContext *context;
3061 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3062 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3063 method = mono_get_method (acfg->image, token, NULL);
3068 if (method->klass->image != acfg->image)
3071 context = mono_method_get_context (method);
3073 if (context && ((context->class_inst && context->class_inst->is_open)))
3077 * For open methods, create an instantiation which can be passed to the JIT.
3078 * FIXME: Handle class_inst as well.
3080 if (context && context->method_inst && context->method_inst->is_open) {
3081 MonoGenericContext shared_context;
3082 MonoGenericInst *inst;
3083 MonoType **type_argv;
3085 MonoMethod *declaring_method;
3086 gboolean supported = TRUE;
3088 /* Check that the context doesn't contain open constructed types */
3089 if (context->class_inst) {
3090 inst = context->class_inst;
3091 for (i = 0; i < inst->type_argc; ++i) {
3092 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)
3094 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3098 if (context->method_inst) {
3099 inst = context->method_inst;
3100 for (i = 0; i < inst->type_argc; ++i) {
3101 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)
3103 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3111 memset (&shared_context, 0, sizeof (MonoGenericContext));
3113 inst = context->class_inst;
3115 type_argv = g_new0 (MonoType*, inst->type_argc);
3116 for (i = 0; i < inst->type_argc; ++i) {
3117 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 type_argv [i] = &mono_defaults.object_class->byval_arg;
3120 type_argv [i] = inst->type_argv [i];
3123 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3127 inst = context->method_inst;
3129 type_argv = g_new0 (MonoType*, inst->type_argc);
3130 for (i = 0; i < inst->type_argc; ++i) {
3131 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)
3132 type_argv [i] = &mono_defaults.object_class->byval_arg;
3134 type_argv [i] = inst->type_argv [i];
3137 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3141 if (method->is_generic || method->klass->generic_container)
3142 declaring_method = method;
3144 declaring_method = mono_method_get_declaring_generic_method (method);
3146 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3150 * If the method is fully sharable, it was already added in place of its
3151 * generic definition.
3153 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3157 * FIXME: Partially shared methods are not shared here, so we end up with
3158 * many identical methods.
3160 add_extra_method (acfg, method);
3163 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3166 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3168 klass = mono_class_get (acfg->image, token);
3169 if (!klass || klass->rank)
3172 add_generic_class (acfg, klass, FALSE);
3175 /* Add types of args/locals */
3176 for (i = 0; i < acfg->methods->len; ++i) {
3179 method = g_ptr_array_index (acfg->methods, i);
3181 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3183 sig = mono_method_signature (method);
3186 for (j = 0; j < sig->param_count; ++j)
3187 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3188 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3191 header = mono_method_get_header (method);
3194 for (j = 0; j < header->num_locals; ++j)
3195 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3196 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3200 if (acfg->image == mono_defaults.corlib) {
3202 MonoType *insts [256];
3205 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3206 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3207 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3208 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3209 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3210 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3211 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3212 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3213 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3214 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3215 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3216 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3218 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3219 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3221 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3222 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3224 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3226 /* Add instances of the array generic interfaces for primitive types */
3227 /* This will add instances of the InternalArray_ helper methods in Array too */
3228 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3230 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3231 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3233 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3234 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3236 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3239 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3240 * used for all instances of GetGenericValueImpl by the AOT runtime.
3243 MonoGenericContext ctx;
3244 MonoType *args [16];
3245 MonoMethod *get_method;
3246 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3248 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3251 memset (&ctx, 0, sizeof (ctx));
3252 args [0] = &mono_defaults.object_class->byval_arg;
3253 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3254 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3258 /* Same for CompareExchange<T> */
3260 MonoGenericContext ctx;
3261 MonoType *args [16];
3262 MonoMethod *cas_method;
3263 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3264 gpointer iter = NULL;
3266 while ((cas_method = mono_class_get_methods (interlocked_klass, &iter))) {
3267 if (!strcmp (cas_method->name, "CompareExchange") && cas_method->is_generic) {
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 (cas_method, &ctx), TRUE, TRUE));
3279 * is_direct_callable:
3281 * Return whenever the method identified by JI is directly callable without
3282 * going through the PLT.
3285 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3287 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3288 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3290 gboolean direct_callable = TRUE;
3292 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3293 direct_callable = FALSE;
3294 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3295 // FIXME: Maybe call the wrapper directly ?
3296 direct_callable = FALSE;
3298 if (direct_callable)
3307 * emit_and_reloc_code:
3309 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3310 * is true, calls are made through the GOT too. This is used for emitting trampolines
3311 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3312 * since trampolines are needed to make PTL work.
3315 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3317 int i, pindex, start_index, method_index;
3319 MonoJumpInfo *patch_info;
3320 MonoMethodHeader *header;
3321 gboolean skip, direct_call;
3323 char direct_call_target [1024];
3326 header = mono_method_get_header (method);
3328 method_index = get_method_index (acfg, method);
3331 /* Collect and sort relocations */
3332 patches = g_ptr_array_new ();
3333 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3334 g_ptr_array_add (patches, patch_info);
3335 g_ptr_array_sort (patches, compare_patches);
3338 for (i = 0; i < code_len; i++) {
3340 for (pindex = start_index; pindex < patches->len; ++pindex) {
3341 patch_info = g_ptr_array_index (patches, pindex);
3342 if (patch_info->ip.i >= i)
3346 #ifdef MONO_ARCH_AOT_SUPPORTED
3348 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3349 start_index = pindex;
3351 switch (patch_info->type) {
3352 case MONO_PATCH_INFO_NONE:
3354 case MONO_PATCH_INFO_GOT_OFFSET: {
3357 arch_emit_got_offset (acfg, code + i, &code_size);
3360 patch_info->type = MONO_PATCH_INFO_NONE;
3365 * If this patch is a call, try emitting a direct call instead of
3366 * through a PLT entry. This is possible if the called method is in
3367 * the same assembly and requires no initialization.
3369 direct_call = FALSE;
3370 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3371 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3372 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3373 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3375 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3376 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3377 patch_info->type = MONO_PATCH_INFO_NONE;
3378 acfg->stats.direct_calls ++;
3381 acfg->stats.all_calls ++;
3384 if (!got_only && !direct_call) {
3385 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3387 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3389 sprintf (direct_call_target, "%s", plt_entry->symbol);
3391 /* Nullify the patch */
3392 patch_info->type = MONO_PATCH_INFO_NONE;
3393 plt_entry->jit_used = TRUE;
3400 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3405 got_slot = get_got_offset (acfg, patch_info);
3407 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3414 #endif /* MONO_ARCH_AOT_SUPPORTED */
3417 /* Find next patch */
3419 for (pindex = start_index; pindex < patches->len; ++pindex) {
3420 patch_info = g_ptr_array_index (patches, pindex);
3421 if (patch_info->ip.i >= i)
3425 /* Try to emit multiple bytes at once */
3426 if (pindex < patches->len && patch_info->ip.i > i) {
3427 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3428 i = patch_info->ip.i - 1;
3430 emit_bytes (acfg, code + i, 1);
3439 * Modify SYMBOL so it only includes characters permissible in symbols.
3442 sanitize_symbol (char *symbol)
3444 int i, len = strlen (symbol);
3446 for (i = 0; i < len; ++i)
3447 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3452 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3454 char *name1, *name2, *cached;
3455 int i, j, len, count;
3457 name1 = mono_method_full_name (method, TRUE);
3458 len = strlen (name1);
3459 name2 = malloc (strlen (prefix) + len + 16);
3460 memcpy (name2, prefix, strlen (prefix));
3461 j = strlen (prefix);
3462 for (i = 0; i < len; ++i) {
3463 if (isalnum (name1 [i])) {
3464 name2 [j ++] = name1 [i];
3465 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3467 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3470 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3479 while (g_hash_table_lookup (cache, name2)) {
3480 sprintf (name2 + j, "_%d", count);
3484 cached = g_strdup (name2);
3485 g_hash_table_insert (cache, cached, cached);
3491 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3496 char *debug_sym = NULL;
3498 int func_alignment = AOT_FUNC_ALIGNMENT;
3499 MonoMethodHeader *header;
3501 method = cfg->orig_method;
3502 code = cfg->native_code;
3503 header = cfg->header;
3505 method_index = get_method_index (acfg, method);
3507 /* Make the labels local */
3508 sprintf (symbol, "%s", cfg->asm_symbol);
3510 emit_section_change (acfg, ".text", 0);
3511 emit_alignment (acfg, func_alignment);
3512 emit_label (acfg, symbol);
3514 if (acfg->aot_opts.write_symbols) {
3516 * Write a C style symbol for every method, this has two uses:
3517 * - it works on platforms where the dwarf debugging info is not
3519 * - it allows the setting of breakpoints of aot-ed methods.
3521 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3523 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3524 if (acfg->need_no_dead_strip)
3525 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3526 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3527 emit_label (acfg, debug_sym);
3530 if (cfg->verbose_level > 0)
3531 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3533 acfg->stats.code_size += cfg->code_len;
3535 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3537 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3541 if (acfg->aot_opts.write_symbols) {
3542 emit_symbol_size (acfg, debug_sym, ".");
3546 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3547 emit_label (acfg, symbol);
3553 * Encode PATCH_INFO into its disk representation.
3556 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3560 switch (patch_info->type) {
3561 case MONO_PATCH_INFO_NONE:
3563 case MONO_PATCH_INFO_IMAGE:
3564 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3566 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3567 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3568 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3570 case MONO_PATCH_INFO_METHOD_REL:
3571 encode_value ((gint)patch_info->data.offset, p, &p);
3573 case MONO_PATCH_INFO_SWITCH: {
3574 gpointer *table = (gpointer *)patch_info->data.table->table;
3577 encode_value (patch_info->data.table->table_size, p, &p);
3578 for (k = 0; k < patch_info->data.table->table_size; k++)
3579 encode_value ((int)(gssize)table [k], p, &p);
3582 case MONO_PATCH_INFO_METHODCONST:
3583 case MONO_PATCH_INFO_METHOD:
3584 case MONO_PATCH_INFO_METHOD_JUMP:
3585 case MONO_PATCH_INFO_ICALL_ADDR:
3586 case MONO_PATCH_INFO_METHOD_RGCTX:
3587 encode_method_ref (acfg, patch_info->data.method, p, &p);
3589 case MONO_PATCH_INFO_INTERNAL_METHOD:
3590 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3591 guint32 len = strlen (patch_info->data.name);
3593 encode_value (len, p, &p);
3595 memcpy (p, patch_info->data.name, len);
3600 case MONO_PATCH_INFO_LDSTR: {
3601 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3602 guint32 token = patch_info->data.token->token;
3603 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3604 encode_value (image_index, p, &p);
3605 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3608 case MONO_PATCH_INFO_RVA:
3609 case MONO_PATCH_INFO_DECLSEC:
3610 case MONO_PATCH_INFO_LDTOKEN:
3611 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3612 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3613 encode_value (patch_info->data.token->token, p, &p);
3614 encode_value (patch_info->data.token->has_context, p, &p);
3615 if (patch_info->data.token->has_context)
3616 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3618 case MONO_PATCH_INFO_EXC_NAME: {
3619 MonoClass *ex_class;
3622 mono_class_from_name (mono_defaults.exception_class->image,
3623 "System", patch_info->data.target);
3624 g_assert (ex_class);
3625 encode_klass_ref (acfg, ex_class, p, &p);
3628 case MONO_PATCH_INFO_R4:
3629 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3631 case MONO_PATCH_INFO_R8:
3632 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3633 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3635 case MONO_PATCH_INFO_VTABLE:
3636 case MONO_PATCH_INFO_CLASS:
3637 case MONO_PATCH_INFO_IID:
3638 case MONO_PATCH_INFO_ADJUSTED_IID:
3639 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3641 case MONO_PATCH_INFO_CLASS_INIT:
3642 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3643 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3645 case MONO_PATCH_INFO_FIELD:
3646 case MONO_PATCH_INFO_SFLDA:
3647 encode_field_info (acfg, patch_info->data.field, p, &p);
3649 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3651 case MONO_PATCH_INFO_RGCTX_FETCH: {
3652 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3654 encode_method_ref (acfg, entry->method, p, &p);
3655 encode_value (entry->in_mrgctx, p, &p);
3656 encode_value (entry->info_type, p, &p);
3657 encode_value (entry->data->type, p, &p);
3658 encode_patch (acfg, entry->data, p, &p);
3661 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3662 case MONO_PATCH_INFO_MONITOR_ENTER:
3663 case MONO_PATCH_INFO_MONITOR_EXIT:
3664 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3666 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3667 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3668 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3671 g_warning ("unable to handle jump info %d", patch_info->type);
3672 g_assert_not_reached ();
3679 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3682 guint32 pindex, offset;
3683 MonoJumpInfo *patch_info;
3685 encode_value (n_patches, p, &p);
3687 for (pindex = 0; pindex < patches->len; ++pindex) {
3688 patch_info = g_ptr_array_index (patches, pindex);
3690 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3694 offset = get_got_offset (acfg, patch_info);
3695 encode_value (offset, p, &p);
3702 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3706 int pindex, buf_size, n_patches;
3709 MonoJumpInfo *patch_info;
3710 MonoMethodHeader *header;
3711 guint32 method_index;
3713 guint32 first_got_offset;
3715 method = cfg->orig_method;
3716 code = cfg->native_code;
3717 header = mono_method_get_header (method);
3719 method_index = get_method_index (acfg, method);
3721 /* Sort relocations */
3722 patches = g_ptr_array_new ();
3723 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3724 g_ptr_array_add (patches, patch_info);
3725 g_ptr_array_sort (patches, compare_patches);
3727 first_got_offset = acfg->cfgs [method_index]->got_offset;
3729 /**********************/
3730 /* Encode method info */
3731 /**********************/
3733 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3734 p = buf = g_malloc (buf_size);
3736 if (mono_class_get_cctor (method->klass))
3737 encode_klass_ref (acfg, method->klass, p, &p);
3739 /* Not needed when loading the method */
3740 encode_value (0, p, &p);
3743 if (cfg->opt & MONO_OPT_SHARED) {
3744 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3745 for (l = cfg->ldstr_list; l; l = l->next) {
3746 encode_value ((long)l->data, p, &p);
3750 /* Used only in shared mode */
3751 g_assert (!cfg->ldstr_list);
3754 for (pindex = 0; pindex < patches->len; ++pindex) {
3755 patch_info = g_ptr_array_index (patches, pindex);
3757 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3758 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3759 patch_info->type = MONO_PATCH_INFO_NONE;
3764 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3765 /* Stored in a GOT slot initialized at module load time */
3766 patch_info->type = MONO_PATCH_INFO_NONE;
3770 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3771 /* Stored in a GOT slot initialized at module load time */
3772 patch_info->type = MONO_PATCH_INFO_NONE;
3776 if (is_plt_patch (patch_info)) {
3777 /* Calls are made through the PLT */
3778 patch_info->type = MONO_PATCH_INFO_NONE;
3786 g_assert (cfg->has_got_slots);
3788 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3790 acfg->stats.info_size += p - buf;
3792 g_assert (p - buf < buf_size);
3794 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3799 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3801 guint32 cache_index;
3804 /* Reuse the unwind module to canonize and store unwind info entries */
3805 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3807 /* Use +/- 1 to distinguish 0s from missing entries */
3808 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3816 * It would be easier to use assembler symbols, but the caller needs an
3819 offset = acfg->unwind_info_offset;
3820 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3821 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3824 encode_value (encoded_len, p, &p);
3826 acfg->unwind_info_offset += encoded_len + (p - buf);
3832 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3835 int i, k, buf_size, method_index;
3836 guint32 debug_info_size;
3838 MonoMethodHeader *header;
3839 guint8 *p, *buf, *debug_info;
3840 MonoJitInfo *jinfo = cfg->jit_info;
3842 gboolean use_unwind_ops = FALSE;
3843 MonoSeqPointInfo *seq_points;
3845 method = cfg->orig_method;
3846 code = cfg->native_code;
3847 header = cfg->header;
3849 method_index = get_method_index (acfg, method);
3851 if (!acfg->aot_opts.nodebug) {
3852 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3855 debug_info_size = 0;
3858 seq_points = cfg->seq_point_info;
3860 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3861 p = buf = g_malloc (buf_size);
3863 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3864 use_unwind_ops = cfg->unwind_ops != NULL;
3867 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);
3869 encode_value (flags, p, &p);
3871 if (use_unwind_ops) {
3872 guint32 encoded_len;
3876 * This is a duplicate of the data in the .debug_frame section, but that
3877 * section cannot be accessed using the dl interface.
3879 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3880 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3883 encode_value (jinfo->used_regs, p, &p);
3886 /*Encode the number of holes before the number of clauses to make decoding easier*/
3887 if (jinfo->has_try_block_holes) {
3888 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3889 encode_value (table->num_holes, p, &p);
3892 /* Exception table */
3893 if (cfg->compile_llvm) {
3895 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3896 * since the information is only available to llc. Instead, we let llc save the data
3897 * into the LSDA, and read it from there at runtime.
3899 /* The assembly might be CIL stripped so emit the data ourselves */
3900 if (header->num_clauses)
3901 encode_value (header->num_clauses, p, &p);
3903 for (k = 0; k < header->num_clauses; ++k) {
3904 MonoExceptionClause *clause;
3906 clause = &header->clauses [k];
3908 encode_value (clause->flags, p, &p);
3909 if (clause->data.catch_class) {
3910 encode_value (1, p, &p);
3911 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3913 encode_value (0, p, &p);
3916 /* Emit a list of nesting clauses */
3917 for (i = 0; i < header->num_clauses; ++i) {
3919 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3921 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3923 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3924 encode_value (i, p, &p);
3926 encode_value (-1, p, &p);
3929 if (jinfo->num_clauses)
3930 encode_value (jinfo->num_clauses, p, &p);
3932 for (k = 0; k < jinfo->num_clauses; ++k) {
3933 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3935 encode_value (ei->flags, p, &p);
3936 encode_value (ei->exvar_offset, p, &p);
3938 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3939 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3941 if (ei->data.catch_class) {
3942 encode_value (1, p, &p);
3943 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3945 encode_value (0, p, &p);
3949 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3950 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3951 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3955 if (jinfo->has_generic_jit_info) {
3956 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3958 if (!cfg->compile_llvm) {
3959 encode_value (gi->has_this ? 1 : 0, p, &p);
3960 encode_value (gi->this_reg, p, &p);
3961 encode_value (gi->this_offset, p, &p);
3965 * Need to encode jinfo->method too, since it is not equal to 'method'
3966 * when using generic sharing.
3968 encode_method_ref (acfg, jinfo->method, p, &p);
3971 if (jinfo->has_try_block_holes) {
3972 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3973 for (i = 0; i < table->num_holes; ++i) {
3974 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3975 encode_value (hole->clause, p, &p);
3976 encode_value (hole->length, p, &p);
3977 encode_value (hole->offset, p, &p);
3982 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3984 encode_value (seq_points->len, p, &p);
3985 last_il_offset = last_native_offset = 0;
3986 for (i = 0; i < seq_points->len; ++i) {
3987 SeqPoint *sp = &seq_points->seq_points [i];
3988 il_offset = sp->il_offset;
3989 native_offset = sp->native_offset;
3990 encode_value (il_offset - last_il_offset, p, &p);
3991 encode_value (native_offset - last_native_offset, p, &p);
3992 last_il_offset = il_offset;
3993 last_native_offset = native_offset;
3995 encode_value (sp->next_len, p, &p);
3996 for (j = 0; j < sp->next_len; ++j)
3997 encode_value (sp->next [j], p, &p);
4001 g_assert (debug_info_size < buf_size);
4003 encode_value (debug_info_size, p, &p);
4004 if (debug_info_size) {
4005 memcpy (p, debug_info, debug_info_size);
4006 p += debug_info_size;
4007 g_free (debug_info);
4012 encode_value (cfg->gc_map_size, p, &p);
4013 /* The GC map requires 4 bytes of alignment */
4014 while ((gsize)p % 4)
4016 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4017 p += cfg->gc_map_size;
4020 acfg->stats.ex_info_size += p - buf;
4022 g_assert (p - buf < buf_size);
4025 /* The GC Map requires 4 byte alignment */
4026 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4031 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4033 MonoClass *klass = mono_class_get (acfg->image, token);
4035 int i, buf_size, res;
4036 gboolean no_special_static, cant_encode;
4037 gpointer iter = NULL;
4042 p = buf = g_malloc (buf_size);
4044 /* Mark as unusable */
4045 encode_value (-1, p, &p);
4047 res = add_to_blob (acfg, buf, p - buf);
4053 buf_size = 10240 + (klass->vtable_size * 16);
4054 p = buf = g_malloc (buf_size);
4058 mono_class_init (klass);
4060 mono_class_get_nested_types (klass, &iter);
4061 g_assert (klass->nested_classes_inited);
4063 mono_class_setup_vtable (klass);
4066 * Emit all the information which is required for creating vtables so
4067 * the runtime does not need to create the MonoMethod structures which
4068 * take up a lot of space.
4071 no_special_static = !mono_class_has_special_static_fields (klass);
4073 /* Check whenever we have enough info to encode the vtable */
4074 cant_encode = FALSE;
4075 for (i = 0; i < klass->vtable_size; ++i) {
4076 MonoMethod *cm = klass->vtable [i];
4078 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4082 if (klass->generic_container || cant_encode) {
4083 encode_value (-1, p, &p);
4085 encode_value (klass->vtable_size, p, &p);
4086 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);
4087 if (klass->has_cctor)
4088 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4089 if (klass->has_finalize)
4090 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4092 encode_value (klass->instance_size, p, &p);
4093 encode_value (mono_class_data_size (klass), p, &p);
4094 encode_value (klass->packing_size, p, &p);
4095 encode_value (klass->min_align, p, &p);
4097 for (i = 0; i < klass->vtable_size; ++i) {
4098 MonoMethod *cm = klass->vtable [i];
4101 encode_method_ref (acfg, cm, p, &p);
4103 encode_value (0, p, &p);
4107 acfg->stats.class_info_size += p - buf;
4109 g_assert (p - buf < buf_size);
4110 res = add_to_blob (acfg, buf, p - buf);
4117 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4119 char *debug_sym = NULL;
4122 case MONO_PATCH_INFO_METHOD:
4123 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4125 case MONO_PATCH_INFO_INTERNAL_METHOD:
4126 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4128 case MONO_PATCH_INFO_CLASS_INIT:
4129 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4130 sanitize_symbol (debug_sym);
4132 case MONO_PATCH_INFO_RGCTX_FETCH:
4133 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4135 case MONO_PATCH_INFO_ICALL_ADDR: {
4136 char *s = get_debug_sym (ji->data.method, "", cache);
4138 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4142 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4143 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4145 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4146 debug_sym = g_strdup_printf ("plt__generic_class_init");
4156 * Calls made from AOTed code are routed through a table of jumps similar to the
4157 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4158 * control to the AOT runtime through a trampoline.
4161 emit_plt (MonoAotCompile *acfg)
4167 cache = g_hash_table_new (g_str_hash, g_str_equal);
4170 sprintf (symbol, "plt");
4172 emit_section_change (acfg, ".text", 0);
4173 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4174 emit_label (acfg, symbol);
4175 emit_label (acfg, acfg->plt_symbol);
4177 for (i = 0; i < acfg->plt_offset; ++i) {
4178 char *debug_sym = NULL;
4179 MonoPltEntry *plt_entry = NULL;
4184 * The first plt entry is unused.
4188 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4193 * If the target is directly callable, alias the plt symbol to point to
4195 * FIXME: Use this to simplify emit_and_reloc_code ().
4196 * FIXME: Avoid the got slot.
4197 * FIXME: Add support to the binary writer.
4199 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4200 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4202 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4203 /* LLVM calls the PLT entries using bl, so emit a stub */
4204 fprintf (acfg->fp, "\n.thumb_func\n");
4205 emit_label (acfg, plt_entry->llvm_symbol);
4206 fprintf (acfg->fp, "bx pc\n");
4207 fprintf (acfg->fp, "nop\n");
4208 fprintf (acfg->fp, ".arm\n");
4209 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4211 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4217 if (acfg->aot_opts.write_symbols)
4218 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4219 debug_sym = plt_entry->debug_sym;
4221 if (acfg->thumb_mixed && !plt_entry->jit_used)
4222 /* Emit only a thumb version */
4225 if (!acfg->thumb_mixed)
4226 emit_label (acfg, plt_entry->llvm_symbol);
4229 if (acfg->need_no_dead_strip)
4230 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4231 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4232 emit_label (acfg, debug_sym);
4235 emit_label (acfg, plt_entry->symbol);
4237 arch_emit_plt_entry (acfg, i);
4240 emit_symbol_size (acfg, debug_sym, ".");
4243 if (acfg->thumb_mixed) {
4244 /* Make sure the ARM symbols don't alias the thumb ones */
4245 emit_zero_bytes (acfg, 16);
4248 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4251 for (i = 0; i < acfg->plt_offset; ++i) {
4252 char *debug_sym = NULL;
4253 MonoPltEntry *plt_entry = NULL;
4259 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4262 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4265 /* Skip plt entries not actually called by LLVM code */
4266 if (!plt_entry->llvm_used)
4269 if (acfg->aot_opts.write_symbols) {
4270 if (plt_entry->debug_sym)
4271 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4275 #if defined(__APPLE__)
4276 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4277 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4279 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4280 emit_label (acfg, debug_sym);
4282 fprintf (acfg->fp, "\n.thumb_func\n");
4284 emit_label (acfg, plt_entry->llvm_symbol);
4286 arch_emit_llvm_plt_entry (acfg, i);
4289 emit_symbol_size (acfg, debug_sym, ".");
4295 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4297 sprintf (symbol, "plt_end");
4298 emit_label (acfg, symbol);
4300 g_hash_table_destroy (cache);
4303 static G_GNUC_UNUSED void
4304 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4306 char start_symbol [256];
4308 guint32 buf_size, info_offset;
4309 MonoJumpInfo *patch_info;
4320 code_size = info->code_size;
4322 unwind_ops = info->unwind_ops;
4324 #ifdef __native_client_codegen__
4325 mono_nacl_fix_patches (code, ji);
4330 sprintf (start_symbol, "%s", name);
4332 emit_section_change (acfg, ".text", 0);
4333 emit_global (acfg, start_symbol, TRUE);
4334 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4335 emit_label (acfg, start_symbol);
4337 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4338 emit_label (acfg, symbol);
4341 * The code should access everything through the GOT, so we pass
4344 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4346 emit_symbol_size (acfg, start_symbol, ".");
4350 /* Sort relocations */
4351 patches = g_ptr_array_new ();
4352 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4353 if (patch_info->type != MONO_PATCH_INFO_NONE)
4354 g_ptr_array_add (patches, patch_info);
4355 g_ptr_array_sort (patches, compare_patches);
4357 buf_size = patches->len * 128 + 128;
4358 buf = g_malloc (buf_size);
4361 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4362 g_assert (p - buf < buf_size);
4364 sprintf (symbol, "%s_p", name);
4366 info_offset = add_to_blob (acfg, buf, p - buf);
4368 emit_section_change (acfg, RODATA_SECT, 0);
4369 emit_global (acfg, symbol, FALSE);
4370 emit_label (acfg, symbol);
4372 emit_int32 (acfg, info_offset);
4374 /* Emit debug info */
4378 sprintf (symbol, "%s", name);
4379 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4382 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4387 emit_trampolines (MonoAotCompile *acfg)
4390 int i, tramp_got_offset;
4391 MonoAotTrampoline ntype;
4392 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4397 if (!acfg->aot_opts.full_aot)
4400 g_assert (acfg->image->assembly);
4402 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4403 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4404 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4405 MonoTrampInfo *info;
4408 * Emit the generic trampolines.
4410 * We could save some code by treating the generic trampolines as a wrapper
4411 * method, but that approach has its own complexities, so we choose the simpler
4414 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4415 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4416 emit_trampoline (acfg, acfg->got_offset, info);
4419 mono_arch_get_nullified_class_init_trampoline (&info);
4420 emit_trampoline (acfg, acfg->got_offset, info);
4421 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4422 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4423 emit_trampoline (acfg, acfg->got_offset, info);
4424 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4425 emit_trampoline (acfg, acfg->got_offset, info);
4428 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4429 emit_trampoline (acfg, acfg->got_offset, info);
4431 /* Emit the exception related code pieces */
4432 code = mono_arch_get_restore_context (&info, TRUE);
4433 emit_trampoline (acfg, acfg->got_offset, info);
4434 code = mono_arch_get_call_filter (&info, TRUE);
4435 emit_trampoline (acfg, acfg->got_offset, info);
4436 code = mono_arch_get_throw_exception (&info, TRUE);
4437 emit_trampoline (acfg, acfg->got_offset, info);
4438 code = mono_arch_get_rethrow_exception (&info, TRUE);
4439 emit_trampoline (acfg, acfg->got_offset, info);
4440 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4441 emit_trampoline (acfg, acfg->got_offset, info);
4443 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4445 GSList *l = mono_arch_get_trampolines (TRUE);
4448 MonoTrampInfo *info = l->data;
4450 emit_trampoline (acfg, acfg->got_offset, info);
4456 for (i = 0; i < 128; ++i) {
4459 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4460 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4461 emit_trampoline (acfg, acfg->got_offset, info);
4463 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4464 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4465 emit_trampoline (acfg, acfg->got_offset, info);
4471 /* delegate_invoke_impl trampolines */
4472 l = mono_arch_get_delegate_invoke_impls ();
4474 MonoTrampInfo *info = l->data;
4476 emit_trampoline (acfg, acfg->got_offset, info);
4481 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4483 /* Emit trampolines which are numerous */
4486 * These include the following:
4487 * - specific trampolines
4488 * - static rgctx invoke trampolines
4490 * These trampolines have the same code, they are parameterized by GOT
4492 * They are defined in this file, in the arch_... routines instead of
4493 * in tramp-<ARCH>.c, since it is easier to do it this way.
4497 * When running in aot-only mode, we can't create specific trampolines at
4498 * runtime, so we create a few, and save them in the AOT file.
4499 * Normal trampolines embed their argument as a literal inside the
4500 * trampoline code, we can't do that here, so instead we embed an offset
4501 * which needs to be added to the trampoline address to get the address of
4502 * the GOT slot which contains the argument value.
4503 * The generated trampolines jump to the generic trampolines using another
4504 * GOT slot, which will be setup by the AOT loader to point to the
4505 * generic trampoline code of the given type.
4509 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4513 emit_section_change (acfg, ".text", 0);
4515 tramp_got_offset = acfg->got_offset;
4517 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4519 case MONO_AOT_TRAMP_SPECIFIC:
4520 sprintf (symbol, "specific_trampolines");
4522 case MONO_AOT_TRAMP_STATIC_RGCTX:
4523 sprintf (symbol, "static_rgctx_trampolines");
4525 case MONO_AOT_TRAMP_IMT_THUNK:
4526 sprintf (symbol, "imt_thunks");
4529 g_assert_not_reached ();
4532 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4533 emit_label (acfg, symbol);
4535 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4537 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4541 case MONO_AOT_TRAMP_SPECIFIC:
4542 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4543 tramp_got_offset += 2;
4545 case MONO_AOT_TRAMP_STATIC_RGCTX:
4546 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4547 tramp_got_offset += 2;
4549 case MONO_AOT_TRAMP_IMT_THUNK:
4550 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4551 tramp_got_offset += 1;
4554 g_assert_not_reached ();
4556 #ifdef __native_client_codegen__
4557 /* align to avoid 32-byte boundary crossings */
4558 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4561 if (!acfg->trampoline_size [ntype]) {
4562 g_assert (tramp_size);
4563 acfg->trampoline_size [ntype] = tramp_size;
4568 /* Reserve some entries at the end of the GOT for our use */
4569 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4572 acfg->got_offset += acfg->num_trampoline_got_entries;
4576 str_begins_with (const char *str1, const char *str2)
4578 int len = strlen (str2);
4579 return strncmp (str1, str2, len) == 0;
4583 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4585 gchar **args, **ptr;
4587 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4588 for (ptr = args; ptr && *ptr; ptr ++) {
4589 const char *arg = *ptr;
4591 if (str_begins_with (arg, "outfile=")) {
4592 opts->outfile = g_strdup (arg + strlen ("outfile="));
4593 } else if (str_begins_with (arg, "save-temps")) {
4594 opts->save_temps = TRUE;
4595 } else if (str_begins_with (arg, "keep-temps")) {
4596 opts->save_temps = TRUE;
4597 } else if (str_begins_with (arg, "write-symbols")) {
4598 opts->write_symbols = TRUE;
4599 } else if (str_begins_with (arg, "no-write-symbols")) {
4600 opts->write_symbols = FALSE;
4601 } else if (str_begins_with (arg, "metadata-only")) {
4602 opts->metadata_only = TRUE;
4603 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4604 opts->bind_to_runtime_version = TRUE;
4605 } else if (str_begins_with (arg, "full")) {
4606 opts->full_aot = TRUE;
4607 } else if (str_begins_with (arg, "threads=")) {
4608 opts->nthreads = atoi (arg + strlen ("threads="));
4609 } else if (str_begins_with (arg, "static")) {
4610 opts->static_link = TRUE;
4611 opts->no_dlsym = TRUE;
4612 } else if (str_begins_with (arg, "asmonly")) {
4613 opts->asm_only = TRUE;
4614 } else if (str_begins_with (arg, "asmwriter")) {
4615 opts->asm_writer = TRUE;
4616 } else if (str_begins_with (arg, "nodebug")) {
4617 opts->nodebug = TRUE;
4618 } else if (str_begins_with (arg, "ntrampolines=")) {
4619 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4620 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4621 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4622 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4623 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4624 } else if (str_begins_with (arg, "autoreg")) {
4625 opts->autoreg = TRUE;
4626 } else if (str_begins_with (arg, "tool-prefix=")) {
4627 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4628 } else if (str_begins_with (arg, "soft-debug")) {
4629 opts->soft_debug = TRUE;
4630 } else if (str_begins_with (arg, "print-skipped")) {
4631 opts->print_skipped_methods = TRUE;
4632 } else if (str_begins_with (arg, "stats")) {
4634 } else if (str_begins_with (arg, "mtriple=")) {
4635 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4636 } else if (str_begins_with (arg, "llvm-path=")) {
4637 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4638 } else if (str_begins_with (arg, "info")) {
4639 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
4641 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
4642 printf ("Supported options for --aot:\n");
4643 printf (" outfile=\n");
4644 printf (" save-temps\n");
4645 printf (" keep-temps\n");
4646 printf (" write-symbols\n");
4647 printf (" metadata-only\n");
4648 printf (" bind-to-runtime-version\n");
4650 printf (" threads=\n");
4651 printf (" static\n");
4652 printf (" asmonly\n");
4653 printf (" asmwriter\n");
4654 printf (" nodebug\n");
4655 printf (" ntrampolines=\n");
4656 printf (" nrgctx-trampolines=\n");
4657 printf (" nimt-trampolines=\n");
4658 printf (" autoreg\n");
4659 printf (" tool-prefix=\n");
4660 printf (" soft-debug\n");
4661 printf (" print-skipped\n");
4662 printf (" stats\n");
4664 printf (" help/?\n");
4667 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4676 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4678 MonoMethod *method = (MonoMethod*)key;
4679 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4680 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4681 MonoAotCompile *acfg = user_data;
4683 new_ji->image = ji->image;
4684 new_ji->token = ji->token;
4685 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4689 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4691 if (klass->type_token)
4693 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4696 return can_encode_class (acfg, klass->element_class);
4701 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4703 switch (patch_info->type) {
4704 case MONO_PATCH_INFO_METHOD:
4705 case MONO_PATCH_INFO_METHODCONST: {
4706 MonoMethod *method = patch_info->data.method;
4708 if (method->wrapper_type) {
4709 switch (method->wrapper_type) {
4710 case MONO_WRAPPER_NONE:
4711 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4712 case MONO_WRAPPER_XDOMAIN_INVOKE:
4713 case MONO_WRAPPER_STFLD:
4714 case MONO_WRAPPER_LDFLD:
4715 case MONO_WRAPPER_LDFLDA:
4716 case MONO_WRAPPER_LDFLD_REMOTE:
4717 case MONO_WRAPPER_STFLD_REMOTE:
4718 case MONO_WRAPPER_STELEMREF:
4719 case MONO_WRAPPER_ISINST:
4720 case MONO_WRAPPER_PROXY_ISINST:
4721 case MONO_WRAPPER_ALLOC:
4722 case MONO_WRAPPER_REMOTING_INVOKE:
4723 case MONO_WRAPPER_UNKNOWN:
4724 case MONO_WRAPPER_WRITE_BARRIER:
4726 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4727 if (!strcmp (method->name, "ElementAddr"))
4731 case MONO_WRAPPER_CASTCLASS:
4732 if (!strcmp (method->name, "__castclass_with_cache"))
4737 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4741 if (!method->token) {
4742 /* The method is part of a constructed type like Int[,].Set (). */
4743 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4744 if (method->klass->rank)
4752 case MONO_PATCH_INFO_VTABLE:
4753 case MONO_PATCH_INFO_CLASS_INIT:
4754 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4755 case MONO_PATCH_INFO_CLASS:
4756 case MONO_PATCH_INFO_IID:
4757 case MONO_PATCH_INFO_ADJUSTED_IID:
4758 if (!can_encode_class (acfg, patch_info->data.klass)) {
4759 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4763 case MONO_PATCH_INFO_RGCTX_FETCH: {
4764 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4766 if (!can_encode_patch (acfg, entry->data))
4780 * AOT compile a given method.
4781 * This function might be called by multiple threads, so it must be thread-safe.
4784 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4787 MonoJumpInfo *patch_info;
4790 MonoMethod *wrapped;
4792 if (acfg->aot_opts.metadata_only)
4795 mono_acfg_lock (acfg);
4796 index = get_method_index (acfg, method);
4797 mono_acfg_unlock (acfg);
4799 /* fixme: maybe we can also precompile wrapper methods */
4800 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4801 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4802 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4803 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4807 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4810 wrapped = mono_marshal_method_from_wrapper (method);
4811 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4812 // FIXME: The wrapper should be generic too, but it is not
4815 InterlockedIncrement (&acfg->stats.mcount);
4818 if (method->is_generic || method->klass->generic_container) {
4819 InterlockedIncrement (&acfg->stats.genericcount);
4824 //acfg->aot_opts.print_skipped_methods = TRUE;
4827 * Since these methods are the only ones which are compiled with
4828 * AOT support, and they are not used by runtime startup/shutdown code,
4829 * the runtime will not see AOT methods during AOT compilation,so it
4830 * does not need to support them by creating a fake GOT etc.
4832 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4833 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4834 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4835 InterlockedIncrement (&acfg->stats.genericcount);
4838 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4839 /* Let the exception happen at runtime */
4843 if (cfg->disable_aot) {
4844 if (acfg->aot_opts.print_skipped_methods)
4845 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4846 InterlockedIncrement (&acfg->stats.ocount);
4847 mono_destroy_compile (cfg);
4851 /* Nullify patches which need no aot processing */
4852 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4853 switch (patch_info->type) {
4854 case MONO_PATCH_INFO_LABEL:
4855 case MONO_PATCH_INFO_BB:
4856 patch_info->type = MONO_PATCH_INFO_NONE;
4863 /* Collect method->token associations from the cfg */
4864 mono_acfg_lock (acfg);
4865 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4866 mono_acfg_unlock (acfg);
4869 * Check for absolute addresses.
4872 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4873 switch (patch_info->type) {
4874 case MONO_PATCH_INFO_ABS:
4875 /* unable to handle this */
4884 if (acfg->aot_opts.print_skipped_methods)
4885 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4886 InterlockedIncrement (&acfg->stats.abscount);
4887 mono_destroy_compile (cfg);
4891 /* Lock for the rest of the code */
4892 mono_acfg_lock (acfg);
4895 * Check for methods/klasses we can't encode.
4898 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4899 if (!can_encode_patch (acfg, patch_info))
4904 if (acfg->aot_opts.print_skipped_methods)
4905 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4906 acfg->stats.ocount++;
4907 mono_destroy_compile (cfg);
4908 mono_acfg_unlock (acfg);
4912 /* Adds generic instances referenced by this method */
4914 * The depth is used to avoid infinite loops when generic virtual recursion is
4917 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4919 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4920 switch (patch_info->type) {
4921 case MONO_PATCH_INFO_METHOD: {
4922 MonoMethod *m = patch_info->data.method;
4923 if (m->is_inflated) {
4924 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4925 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4926 !method_has_type_vars (m)) {
4927 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4928 if (acfg->aot_opts.full_aot)
4929 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4931 add_extra_method_with_depth (acfg, m, depth + 1);
4934 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4936 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4937 add_extra_method_with_depth (acfg, m, depth + 1);
4940 case MONO_PATCH_INFO_VTABLE: {
4941 MonoClass *klass = patch_info->data.klass;
4943 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4944 add_generic_class_with_depth (acfg, klass, depth + 5);
4953 /* Determine whenever the method has GOT slots */
4954 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4955 switch (patch_info->type) {
4956 case MONO_PATCH_INFO_GOT_OFFSET:
4957 case MONO_PATCH_INFO_NONE:
4958 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4960 case MONO_PATCH_INFO_IMAGE:
4961 /* The assembly is stored in GOT slot 0 */
4962 if (patch_info->data.image != acfg->image)
4963 cfg->has_got_slots = TRUE;
4966 if (!is_plt_patch (patch_info))
4967 cfg->has_got_slots = TRUE;
4972 if (!cfg->has_got_slots)
4973 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4976 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4978 /* Make a copy of the patch info which is in the mempool */
4980 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4982 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4983 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4986 patches = new_patch_info;
4988 patches_end->next = new_patch_info;
4989 patches_end = new_patch_info;
4991 cfg->patch_info = patches;
4993 /* Make a copy of the unwind info */
4995 GSList *l, *unwind_ops;
4999 for (l = cfg->unwind_ops; l; l = l->next) {
5000 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5001 memcpy (op, l->data, sizeof (MonoUnwindOp));
5002 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5004 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5006 /* Make a copy of the argument/local info */
5008 MonoInst **args, **locals;
5009 MonoMethodSignature *sig;
5010 MonoMethodHeader *header;
5013 sig = mono_method_signature (method);
5014 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5015 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5016 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5017 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5021 header = mono_method_get_header (method);
5022 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5023 for (i = 0; i < header->num_locals; ++i) {
5024 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5025 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5027 cfg->locals = locals;
5030 /* Free some fields used by cfg to conserve memory */
5031 mono_mempool_destroy (cfg->mempool);
5032 cfg->mempool = NULL;
5033 g_free (cfg->varinfo);
5034 cfg->varinfo = NULL;
5038 mono_regstate_free (cfg->rs);
5042 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5044 while (index >= acfg->cfgs_size) {
5045 MonoCompile **new_cfgs;
5048 new_size = acfg->cfgs_size * 2;
5049 new_cfgs = g_new0 (MonoCompile*, new_size);
5050 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5051 g_free (acfg->cfgs);
5052 acfg->cfgs = new_cfgs;
5053 acfg->cfgs_size = new_size;
5055 acfg->cfgs [index] = cfg;
5057 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5060 if (cfg->orig_method->wrapper_type)
5061 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5064 mono_acfg_unlock (acfg);
5066 InterlockedIncrement (&acfg->stats.ccount);
5070 compile_thread_main (gpointer *user_data)
5072 MonoDomain *domain = user_data [0];
5073 MonoAotCompile *acfg = user_data [1];
5074 GPtrArray *methods = user_data [2];
5077 mono_thread_attach (domain);
5079 for (i = 0; i < methods->len; ++i)
5080 compile_method (acfg, g_ptr_array_index (methods, i));
5084 load_profile_files (MonoAotCompile *acfg)
5088 int file_index, res, method_index, i;
5095 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5097 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5102 infile = fopen (tmp, "r");
5105 printf ("Using profile data file '%s'\n", tmp);
5110 res = fscanf (infile, "%32s\n", ver);
5111 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5112 printf ("Profile file has wrong version or invalid.\n");
5119 MonoMethodDesc *desc;
5122 if (fgets (name, 1023, infile) == NULL)
5125 /* Kill the newline */
5126 if (strlen (name) > 0)
5127 name [strlen (name) - 1] = '\0';
5129 desc = mono_method_desc_new (name, TRUE);
5131 method = mono_method_desc_search_in_image (desc, acfg->image);
5133 if (method && mono_method_get_token (method)) {
5134 token = mono_method_get_token (method);
5135 method_index = mono_metadata_token_index (token) - 1;
5137 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
5138 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
5141 //printf ("No method found matching '%s'.\n", name);
5147 /* Add missing methods */
5149 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
5150 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
5151 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
5153 unordered = g_list_reverse (unordered);
5154 if (acfg->method_order)
5155 g_list_last (acfg->method_order)->next = unordered;
5157 acfg->method_order = unordered;
5160 /* Used by the LLVM backend */
5162 mono_aot_get_got_offset (MonoJumpInfo *ji)
5164 return get_got_offset (llvm_acfg, ji);
5168 mono_aot_get_method_name (MonoCompile *cfg)
5170 if (llvm_acfg->aot_opts.static_link)
5171 /* Include the assembly name too to avoid duplicate symbol errors */
5172 return g_strdup_printf ("%s_%s", llvm_acfg->image->assembly->aname.name, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5174 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5178 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5180 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5181 MonoPltEntry *plt_entry;
5184 ji->data.target = data;
5186 if (!can_encode_patch (llvm_acfg, ji))
5189 plt_entry = get_plt_entry (llvm_acfg, ji);
5190 plt_entry->llvm_used = TRUE;
5192 #if defined(__APPLE__)
5193 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5195 return g_strdup_printf (plt_entry->llvm_symbol);
5200 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5204 mono_acfg_lock (llvm_acfg);
5205 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5206 mono_acfg_unlock (llvm_acfg);
5216 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5220 emit_llvm_file (MonoAotCompile *acfg)
5222 char *command, *opts;
5224 MonoJumpInfo *patch_info;
5227 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5231 /* Compute the final size of the got */
5232 for (i = 0; i < acfg->nmethods; ++i) {
5233 if (acfg->cfgs [i]) {
5234 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5235 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5236 if (!is_plt_patch (patch_info))
5237 get_got_offset (acfg, patch_info);
5239 get_plt_entry (acfg, patch_info);
5245 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5247 if (acfg->aot_opts.full_aot) {
5251 * Need to add the got entries used by the trampolines.
5252 * This is only a conservative approximation.
5254 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5255 /* For the generic + rgctx trampolines */
5256 acfg->final_got_size += 200;
5257 /* For the specific trampolines */
5258 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5259 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5264 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5267 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5268 * a lot of time, and doesn't seem to save much space.
5269 * The following optimizations cannot be enabled:
5271 * - 'jump-threading' changes our blockaddress references to int constants.
5272 * The opt list below was produced by taking the output of:
5273 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5274 * then removing tailcallelim + the global opts, and adding a second gvn.
5276 opts = g_strdup ("-instcombine -simplifycfg");
5277 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5279 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5280 printf ("Executing opt: %s\n", command);
5281 if (system (command) != 0) {
5287 if (!acfg->llc_args)
5288 acfg->llc_args = g_string_new ("");
5290 /* Verbose asm slows down llc greatly */
5291 g_string_append (acfg->llc_args, " -asm-verbose=false");
5293 if (acfg->aot_opts.mtriple)
5294 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5296 if (llvm_acfg->aot_opts.static_link)
5297 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5299 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5300 unlink (acfg->tmpfname);
5302 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);
5304 printf ("Executing llc: %s\n", command);
5306 if (system (command) != 0) {
5313 emit_code (MonoAotCompile *acfg)
5317 char end_symbol [256];
5320 #if defined(TARGET_POWERPC64)
5321 sprintf (symbol, ".Lgot_addr");
5322 emit_section_change (acfg, ".text", 0);
5323 emit_alignment (acfg, 8);
5324 emit_label (acfg, symbol);
5325 emit_pointer (acfg, acfg->got_symbol);
5329 * This global symbol is used to compute the address of each method using the
5330 * code_offsets array. It is also used to compute the memory ranges occupied by
5331 * AOT code, so it must be equal to the address of the first emitted method.
5333 sprintf (symbol, "methods");
5334 emit_section_change (acfg, ".text", 0);
5335 emit_alignment (acfg, 8);
5337 for (i = 0; i < acfg->nmethods; ++i) {
5338 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5339 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5343 if (i == acfg->nmethods)
5344 /* No LLVM compiled methods */
5345 emit_label (acfg, symbol);
5347 emit_label (acfg, symbol);
5351 * Emit some padding so the local symbol for the first method doesn't have the
5352 * same address as 'methods'.
5354 #if defined(__default_codegen__)
5355 emit_zero_bytes (acfg, 16);
5356 #elif defined(__native_client_codegen__)
5358 const int kPaddingSize = 16;
5359 guint8 pad_buffer[kPaddingSize];
5360 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5361 emit_bytes (acfg, pad_buffer, kPaddingSize);
5366 for (l = acfg->method_order; l != NULL; l = l->next) {
5370 i = GPOINTER_TO_UINT (l->data);
5372 cfg = acfg->cfgs [i];
5377 method = cfg->orig_method;
5379 /* Emit unbox trampoline */
5380 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5381 char call_target [256];
5383 if (!method->wrapper_type && !method->is_inflated) {
5384 g_assert (method->token);
5385 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5387 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5390 emit_section_change (acfg, ".text", 0);
5391 #ifdef __native_client_codegen__
5392 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5394 emit_global (acfg, symbol, TRUE);
5396 if (acfg->thumb_mixed && cfg->compile_llvm)
5397 fprintf (acfg->fp, "\n.thumb_func\n");
5399 emit_label (acfg, symbol);
5401 sprintf (call_target, "%s", cfg->asm_symbol);
5403 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, call_target);
5406 if (cfg->compile_llvm)
5407 acfg->stats.llvm_count ++;
5409 emit_method_code (acfg, cfg);
5412 sprintf (symbol, "methods_end");
5413 emit_section_change (acfg, ".text", 0);
5414 emit_alignment (acfg, 8);
5415 emit_label (acfg, symbol);
5418 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5419 * from optimizing them away, since it doesn't see that code_offsets references them.
5420 * JITted methods don't need this since they are referenced using assembler local
5422 * FIXME: This is why write-symbols doesn't work on OSX ?
5424 if (acfg->llvm && acfg->need_no_dead_strip) {
5425 fprintf (acfg->fp, "\n");
5426 for (i = 0; i < acfg->nmethods; ++i) {
5427 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5428 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5432 sprintf (symbol, "code_offsets");
5433 emit_section_change (acfg, RODATA_SECT, 1);
5434 emit_alignment (acfg, 8);
5435 emit_label (acfg, symbol);
5437 acfg->stats.offsets_size += acfg->nmethods * 4;
5439 sprintf (end_symbol, "methods");
5440 for (i = 0; i < acfg->nmethods; ++i) {
5441 if (acfg->cfgs [i]) {
5442 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5444 emit_int32 (acfg, 0xffffffff);
5451 emit_info (MonoAotCompile *acfg)
5458 offsets = g_new0 (gint32, acfg->nmethods);
5460 for (l = acfg->method_order; l != NULL; l = l->next) {
5461 i = GPOINTER_TO_UINT (l->data);
5463 if (acfg->cfgs [i]) {
5464 emit_method_info (acfg, acfg->cfgs [i]);
5465 offsets [i] = acfg->cfgs [i]->method_info_offset;
5471 sprintf (symbol, "method_info_offsets");
5472 emit_section_change (acfg, RODATA_SECT, 1);
5473 emit_alignment (acfg, 8);
5474 emit_label (acfg, symbol);
5476 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5481 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5483 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5484 #define mix(a,b,c) { \
5485 a -= c; a ^= rot(c, 4); c += b; \
5486 b -= a; b ^= rot(a, 6); a += c; \
5487 c -= b; c ^= rot(b, 8); b += a; \
5488 a -= c; a ^= rot(c,16); c += b; \
5489 b -= a; b ^= rot(a,19); a += c; \
5490 c -= b; c ^= rot(b, 4); b += a; \
5492 #define final(a,b,c) { \
5493 c ^= b; c -= rot(b,14); \
5494 a ^= c; a -= rot(c,11); \
5495 b ^= a; b -= rot(a,25); \
5496 c ^= b; c -= rot(b,16); \
5497 a ^= c; a -= rot(c,4); \
5498 b ^= a; b -= rot(a,14); \
5499 c ^= b; c -= rot(b,24); \
5503 mono_aot_type_hash (MonoType *t1)
5505 guint hash = t1->type;
5507 hash |= t1->byref << 6; /* do not collide with t1->type values */
5509 case MONO_TYPE_VALUETYPE:
5510 case MONO_TYPE_CLASS:
5511 case MONO_TYPE_SZARRAY:
5512 /* check if the distribution is good enough */
5513 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5515 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5516 case MONO_TYPE_ARRAY:
5517 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5518 case MONO_TYPE_GENERICINST:
5519 return ((hash << 5) - hash) ^ 0;
5525 * mono_aot_method_hash:
5527 * Return a hash code for methods which only depends on metadata.
5530 mono_aot_method_hash (MonoMethod *method)
5532 MonoMethodSignature *sig;
5536 guint32 *hashes_start, *hashes;
5538 MonoGenericInst *ginst = NULL;
5540 /* Similar to the hash in mono_method_get_imt_slot () */
5542 sig = mono_method_signature (method);
5544 if (method->is_inflated)
5545 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5547 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5548 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5549 hashes = hashes_start;
5551 /* Some wrappers are assigned to random classes */
5552 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5553 klass = method->klass;
5555 klass = mono_defaults.object_class;
5557 if (!method->wrapper_type) {
5558 char *full_name = mono_type_full_name (&klass->byval_arg);
5560 hashes [0] = mono_metadata_str_hash (full_name);
5564 hashes [0] = mono_metadata_str_hash (klass->name);
5565 hashes [1] = mono_metadata_str_hash (klass->name_space);
5567 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5568 /* The method name includes a stringified pointer */
5571 hashes [2] = mono_metadata_str_hash (method->name);
5572 hashes [3] = method->wrapper_type;
5573 hashes [4] = mono_aot_type_hash (sig->ret);
5575 for (i = 0; i < sig->param_count; i++) {
5576 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5579 for (i = 0; i < ginst->type_argc; ++i)
5580 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5582 g_assert (hindex == hashes_count);
5584 /* Setup internal state */
5585 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5587 /* Handle most of the hashes */
5588 while (hashes_count > 3) {
5597 /* Handle the last 3 hashes (all the case statements fall through) */
5598 switch (hashes_count) {
5599 case 3 : c += hashes [2];
5600 case 2 : b += hashes [1];
5601 case 1 : a += hashes [0];
5603 case 0: /* nothing left to add */
5607 free (hashes_start);
5616 * mono_aot_wrapper_name:
5618 * Return a string which uniqely identifies the given wrapper method.
5621 mono_aot_wrapper_name (MonoMethod *method)
5623 char *name, *tmpsig, *klass_desc;
5625 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5627 switch (method->wrapper_type) {
5628 case MONO_WRAPPER_RUNTIME_INVOKE:
5629 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5630 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5632 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5635 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5636 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5637 g_free (klass_desc);
5647 * mono_aot_get_array_helper_from_wrapper;
5649 * Get the helper method in Array called by an array wrapper method.
5652 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5656 MonoGenericContext ctx;
5657 MonoType *args [16];
5658 char *mname, *iname, *s, *s2, *helper_name = NULL;
5660 prefix = "System.Collections.Generic";
5661 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5662 s2 = strstr (s, "`1.");
5668 //printf ("X: %s %s\n", iname, mname);
5670 if (!strcmp (iname, "IList"))
5671 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5673 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5674 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5676 g_free (helper_name);
5679 if (m->is_generic) {
5680 memset (&ctx, 0, sizeof (ctx));
5681 args [0] = &method->klass->element_class->byval_arg;
5682 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5683 m = mono_class_inflate_generic_method (m, &ctx);
5689 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5691 typedef struct HashEntry {
5692 guint32 key, value, index;
5693 struct HashEntry *next;
5697 * emit_extra_methods:
5699 * Emit methods which are not in the METHOD table, like wrappers.
5702 emit_extra_methods (MonoAotCompile *acfg)
5704 int i, table_size, buf_size;
5707 guint32 *info_offsets;
5710 HashEntry *entry, *new_entry;
5711 int nmethods, max_chain_length;
5714 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5716 /* Emit method info */
5718 for (i = 0; i < acfg->extra_methods->len; ++i) {
5719 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5720 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5727 p = buf = g_malloc (buf_size);
5731 method = cfg->method_to_register;
5734 if (method->wrapper_type) {
5735 gboolean encode_ref = FALSE;
5738 * We encode some wrappers using their name, since encoding them
5739 * directly would be difficult. This works because at runtime, we only need to
5740 * check whenever a method ref matches an existing MonoMethod. The downside is
5741 * that the method names are large, so we use the binary encoding if possible.
5743 switch (method->wrapper_type) {
5744 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5745 case MONO_WRAPPER_SYNCHRONIZED:
5748 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5749 /* Skip JIT icall wrappers */
5750 if (!strstr (method->name, "__icall_wrapper"))
5753 case MONO_WRAPPER_UNKNOWN:
5754 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5757 case MONO_WRAPPER_RUNTIME_INVOKE:
5758 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5759 /* Direct wrapper, encode normally */
5767 name = mono_aot_wrapper_name (method);
5771 encode_value (1, p, &p);
5772 encode_value (method->wrapper_type, p, &p);
5773 strcpy ((char*)p, name);
5774 p += strlen (name ) + 1;
5777 encode_value (0, p, &p);
5778 encode_method_ref (acfg, method, p, &p);
5781 g_assert ((p - buf) < buf_size);
5783 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5788 * Construct a chained hash table for mapping indexes in extra_method_info to
5791 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5792 table = g_ptr_array_sized_new (table_size);
5793 for (i = 0; i < table_size; ++i)
5794 g_ptr_array_add (table, NULL);
5795 chain_lengths = g_new0 (int, table_size);
5796 max_chain_length = 0;
5797 for (i = 0; i < acfg->extra_methods->len; ++i) {
5798 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5799 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5805 key = info_offsets [i];
5806 value = get_method_index (acfg, method);
5808 hash = mono_aot_method_hash (method) % table_size;
5810 chain_lengths [hash] ++;
5811 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5813 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5814 new_entry->key = key;
5815 new_entry->value = value;
5817 entry = g_ptr_array_index (table, hash);
5818 if (entry == NULL) {
5819 new_entry->index = hash;
5820 g_ptr_array_index (table, hash) = new_entry;
5823 entry = entry->next;
5825 entry->next = new_entry;
5826 new_entry->index = table->len;
5827 g_ptr_array_add (table, new_entry);
5831 //printf ("MAX: %d\n", max_chain_length);
5833 /* Emit the table */
5834 sprintf (symbol, "extra_method_table");
5835 emit_section_change (acfg, RODATA_SECT, 0);
5836 emit_alignment (acfg, 8);
5837 emit_label (acfg, symbol);
5839 emit_int32 (acfg, table_size);
5840 for (i = 0; i < table->len; ++i) {
5841 HashEntry *entry = g_ptr_array_index (table, i);
5843 if (entry == NULL) {
5844 emit_int32 (acfg, 0);
5845 emit_int32 (acfg, 0);
5846 emit_int32 (acfg, 0);
5848 //g_assert (entry->key > 0);
5849 emit_int32 (acfg, entry->key);
5850 emit_int32 (acfg, entry->value);
5852 emit_int32 (acfg, entry->next->index);
5854 emit_int32 (acfg, 0);
5859 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5860 * This is used by mono_aot_find_jit_info ().
5862 sprintf (symbol, "extra_method_info_offsets");
5863 emit_section_change (acfg, RODATA_SECT, 0);
5864 emit_alignment (acfg, 8);
5865 emit_label (acfg, symbol);
5867 emit_int32 (acfg, acfg->extra_methods->len);
5868 for (i = 0; i < acfg->extra_methods->len; ++i) {
5869 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5871 emit_int32 (acfg, get_method_index (acfg, method));
5872 emit_int32 (acfg, info_offsets [i]);
5877 emit_exception_info (MonoAotCompile *acfg)
5883 offsets = g_new0 (gint32, acfg->nmethods);
5884 for (i = 0; i < acfg->nmethods; ++i) {
5885 if (acfg->cfgs [i]) {
5886 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5887 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5893 sprintf (symbol, "ex_info_offsets");
5894 emit_section_change (acfg, RODATA_SECT, 1);
5895 emit_alignment (acfg, 8);
5896 emit_label (acfg, symbol);
5898 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5903 emit_unwind_info (MonoAotCompile *acfg)
5909 * The unwind info contains a lot of duplicates so we emit each unique
5910 * entry once, and only store the offset from the start of the table in the
5914 sprintf (symbol, "unwind_info");
5915 emit_section_change (acfg, RODATA_SECT, 1);
5916 emit_alignment (acfg, 8);
5917 emit_label (acfg, symbol);
5919 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5920 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5921 guint8 *unwind_info;
5922 guint32 unwind_info_len;
5926 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5929 encode_value (unwind_info_len, p, &p);
5930 emit_bytes (acfg, buf, p - buf);
5931 emit_bytes (acfg, unwind_info, unwind_info_len);
5933 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5938 emit_class_info (MonoAotCompile *acfg)
5944 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5945 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5946 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5948 sprintf (symbol, "class_info_offsets");
5949 emit_section_change (acfg, RODATA_SECT, 1);
5950 emit_alignment (acfg, 8);
5951 emit_label (acfg, symbol);
5953 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5957 typedef struct ClassNameTableEntry {
5958 guint32 token, index;
5959 struct ClassNameTableEntry *next;
5960 } ClassNameTableEntry;
5963 emit_class_name_table (MonoAotCompile *acfg)
5966 guint32 token, hash;
5971 ClassNameTableEntry *entry, *new_entry;
5974 * Construct a chained hash table for mapping class names to typedef tokens.
5976 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5977 table = g_ptr_array_sized_new (table_size);
5978 for (i = 0; i < table_size; ++i)
5979 g_ptr_array_add (table, NULL);
5980 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5981 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5982 klass = mono_class_get (acfg->image, token);
5985 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5986 hash = mono_metadata_str_hash (full_name) % table_size;
5989 /* FIXME: Allocate from the mempool */
5990 new_entry = g_new0 (ClassNameTableEntry, 1);
5991 new_entry->token = token;
5993 entry = g_ptr_array_index (table, hash);
5994 if (entry == NULL) {
5995 new_entry->index = hash;
5996 g_ptr_array_index (table, hash) = new_entry;
5999 entry = entry->next;
6001 entry->next = new_entry;
6002 new_entry->index = table->len;
6003 g_ptr_array_add (table, new_entry);
6007 /* Emit the table */
6008 sprintf (symbol, "class_name_table");
6009 emit_section_change (acfg, RODATA_SECT, 0);
6010 emit_alignment (acfg, 8);
6011 emit_label (acfg, symbol);
6013 /* FIXME: Optimize memory usage */
6014 g_assert (table_size < 65000);
6015 emit_int16 (acfg, table_size);
6016 g_assert (table->len < 65000);
6017 for (i = 0; i < table->len; ++i) {
6018 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6020 if (entry == NULL) {
6021 emit_int16 (acfg, 0);
6022 emit_int16 (acfg, 0);
6024 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6026 emit_int16 (acfg, entry->next->index);
6028 emit_int16 (acfg, 0);
6034 emit_image_table (MonoAotCompile *acfg)
6040 * The image table is small but referenced in a lot of places.
6041 * So we emit it at once, and reference its elements by an index.
6044 sprintf (symbol, "image_table");
6045 emit_section_change (acfg, RODATA_SECT, 1);
6046 emit_alignment (acfg, 8);
6047 emit_label (acfg, symbol);
6049 emit_int32 (acfg, acfg->image_table->len);
6050 for (i = 0; i < acfg->image_table->len; i++) {
6051 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6052 MonoAssemblyName *aname = &image->assembly->aname;
6054 /* FIXME: Support multi-module assemblies */
6055 g_assert (image->assembly->image == image);
6057 emit_string (acfg, image->assembly_name);
6058 emit_string (acfg, image->guid);
6059 emit_string (acfg, aname->culture ? aname->culture : "");
6060 emit_string (acfg, (const char*)aname->public_key_token);
6062 emit_alignment (acfg, 8);
6063 emit_int32 (acfg, aname->flags);
6064 emit_int32 (acfg, aname->major);
6065 emit_int32 (acfg, aname->minor);
6066 emit_int32 (acfg, aname->build);
6067 emit_int32 (acfg, aname->revision);
6072 emit_got_info (MonoAotCompile *acfg)
6075 int i, first_plt_got_patch, buf_size;
6077 guint32 *got_info_offsets;
6079 /* Add the patches needed by the PLT to the GOT */
6080 acfg->plt_got_offset_base = acfg->got_offset;
6081 first_plt_got_patch = acfg->got_patches->len;
6082 for (i = 1; i < acfg->plt_offset; ++i) {
6083 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6085 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6088 acfg->got_offset += acfg->plt_offset;
6092 * - optimize offsets table.
6093 * - reduce number of exported symbols.
6094 * - emit info for a klass only once.
6095 * - determine when a method uses a GOT slot which is guaranteed to be already
6097 * - clean up and document the code.
6098 * - use String.Empty in class libs.
6101 /* Encode info required to decode shared GOT entries */
6102 buf_size = acfg->got_patches->len * 128;
6103 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6104 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6105 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6107 if (acfg->plt_offset)
6108 acfg->plt_got_info_offsets [0] = 0;
6109 for (i = 0; i < acfg->got_patches->len; ++i) {
6110 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6114 encode_value (ji->type, p, &p);
6115 encode_patch (acfg, ji, p, &p);
6117 g_assert (p - buf <= buf_size);
6118 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6120 if (i >= first_plt_got_patch)
6121 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6122 acfg->stats.got_info_size += p - buf;
6125 /* Emit got_info_offsets table */
6126 sprintf (symbol, "got_info_offsets");
6127 emit_section_change (acfg, RODATA_SECT, 1);
6128 emit_alignment (acfg, 8);
6129 emit_label (acfg, symbol);
6131 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6132 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6136 emit_got (MonoAotCompile *acfg)
6141 /* Don't make GOT global so accesses to it don't need relocations */
6142 sprintf (symbol, "%s", acfg->got_symbol);
6143 emit_section_change (acfg, ".bss", 0);
6144 emit_alignment (acfg, 8);
6145 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6146 emit_label (acfg, symbol);
6147 if (acfg->got_offset > 0)
6148 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6150 sprintf (symbol, "got_end");
6151 emit_label (acfg, symbol);
6155 typedef struct GlobalsTableEntry {
6156 guint32 value, index;
6157 struct GlobalsTableEntry *next;
6158 } GlobalsTableEntry;
6161 emit_globals (MonoAotCompile *acfg)
6167 GlobalsTableEntry *entry, *new_entry;
6169 if (!acfg->aot_opts.static_link)
6173 * When static linking, we emit a table containing our globals.
6177 * Construct a chained hash table for mapping global names to their index in
6178 * the globals table.
6180 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6181 table = g_ptr_array_sized_new (table_size);
6182 for (i = 0; i < table_size; ++i)
6183 g_ptr_array_add (table, NULL);
6184 for (i = 0; i < acfg->globals->len; ++i) {
6185 char *name = g_ptr_array_index (acfg->globals, i);
6187 hash = mono_metadata_str_hash (name) % table_size;
6189 /* FIXME: Allocate from the mempool */
6190 new_entry = g_new0 (GlobalsTableEntry, 1);
6191 new_entry->value = i;
6193 entry = g_ptr_array_index (table, hash);
6194 if (entry == NULL) {
6195 new_entry->index = hash;
6196 g_ptr_array_index (table, hash) = new_entry;
6199 entry = entry->next;
6201 entry->next = new_entry;
6202 new_entry->index = table->len;
6203 g_ptr_array_add (table, new_entry);
6207 /* Emit the table */
6208 sprintf (symbol, ".Lglobals_hash");
6209 emit_section_change (acfg, RODATA_SECT, 0);
6210 emit_alignment (acfg, 8);
6211 emit_label (acfg, symbol);
6213 /* FIXME: Optimize memory usage */
6214 g_assert (table_size < 65000);
6215 emit_int16 (acfg, table_size);
6216 for (i = 0; i < table->len; ++i) {
6217 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6219 if (entry == NULL) {
6220 emit_int16 (acfg, 0);
6221 emit_int16 (acfg, 0);
6223 emit_int16 (acfg, entry->value + 1);
6225 emit_int16 (acfg, entry->next->index);
6227 emit_int16 (acfg, 0);
6231 /* Emit the names */
6232 for (i = 0; i < acfg->globals->len; ++i) {
6233 char *name = g_ptr_array_index (acfg->globals, i);
6235 sprintf (symbol, "name_%d", i);
6236 emit_section_change (acfg, RODATA_SECT, 1);
6238 emit_alignment (acfg, 4);
6240 emit_label (acfg, symbol);
6241 emit_string (acfg, name);
6244 /* Emit the globals table */
6245 sprintf (symbol, "globals");
6246 emit_section_change (acfg, ".data", 0);
6247 /* This is not a global, since it is accessed by the init function */
6248 emit_alignment (acfg, 8);
6249 emit_label (acfg, symbol);
6251 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6252 emit_pointer (acfg, symbol);
6254 for (i = 0; i < acfg->globals->len; ++i) {
6255 char *name = g_ptr_array_index (acfg->globals, i);
6257 sprintf (symbol, "name_%d", i);
6258 emit_pointer (acfg, symbol);
6260 sprintf (symbol, "%s", name);
6261 emit_pointer (acfg, symbol);
6263 /* Null terminate the table */
6264 emit_int32 (acfg, 0);
6265 emit_int32 (acfg, 0);
6269 emit_autoreg (MonoAotCompile *acfg)
6274 * Emit a function into the .ctor section which will be called by the ELF
6275 * loader to register this module with the runtime.
6277 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6280 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6282 arch_emit_autoreg (acfg, symbol);
6288 emit_mem_end (MonoAotCompile *acfg)
6292 sprintf (symbol, "mem_end");
6293 emit_section_change (acfg, ".text", 1);
6294 emit_alignment (acfg, 8);
6295 emit_label (acfg, symbol);
6299 * Emit a structure containing all the information not stored elsewhere.
6302 emit_file_info (MonoAotCompile *acfg)
6307 const char *gc_name;
6310 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6312 if (acfg->aot_opts.bind_to_runtime_version) {
6313 build_info = mono_get_runtime_build_info ();
6314 emit_string_symbol (acfg, "runtime_version", build_info);
6315 g_free (build_info);
6317 emit_string_symbol (acfg, "runtime_version", "");
6320 /* Emit a string holding the assembly name */
6321 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6324 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6327 gc_name = mono_gc_get_gc_name ();
6328 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6330 sprintf (symbol, "mono_aot_file_info");
6331 emit_section_change (acfg, ".data", 0);
6332 emit_alignment (acfg, 8);
6333 emit_label (acfg, symbol);
6334 if (!acfg->aot_opts.static_link)
6335 emit_global (acfg, symbol, FALSE);
6337 /* The data emitted here must match MonoAotFileInfo. */
6339 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6340 emit_int32 (acfg, 0);
6343 * We emit pointers to our data structures instead of emitting global symbols which
6344 * point to them, to reduce the number of globals, and because using globals leads to
6345 * various problems (i.e. arm/thumb).
6347 emit_pointer (acfg, acfg->got_symbol);
6348 emit_pointer (acfg, "methods");
6351 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6353 emit_pointer (acfg, "mono_eh_frame");
6355 emit_pointer (acfg, NULL);
6357 emit_pointer (acfg, "blob");
6358 emit_pointer (acfg, "class_name_table");
6359 emit_pointer (acfg, "class_info_offsets");
6360 emit_pointer (acfg, "method_info_offsets");
6361 emit_pointer (acfg, "ex_info_offsets");
6362 emit_pointer (acfg, "code_offsets");
6363 emit_pointer (acfg, "extra_method_info_offsets");
6364 emit_pointer (acfg, "extra_method_table");
6365 emit_pointer (acfg, "got_info_offsets");
6366 emit_pointer (acfg, "methods_end");
6367 emit_pointer (acfg, "unwind_info");
6368 emit_pointer (acfg, "mem_end");
6369 emit_pointer (acfg, "image_table");
6370 emit_pointer (acfg, "plt");
6371 emit_pointer (acfg, "plt_end");
6372 emit_pointer (acfg, "assembly_guid");
6373 emit_pointer (acfg, "runtime_version");
6374 if (acfg->num_trampoline_got_entries) {
6375 emit_pointer (acfg, "specific_trampolines");
6376 emit_pointer (acfg, "static_rgctx_trampolines");
6377 emit_pointer (acfg, "imt_thunks");
6379 emit_pointer (acfg, NULL);
6380 emit_pointer (acfg, NULL);
6381 emit_pointer (acfg, NULL);
6383 if (acfg->thumb_mixed) {
6384 emit_pointer (acfg, "thumb_end");
6386 emit_pointer (acfg, NULL);
6388 if (acfg->aot_opts.static_link) {
6389 emit_pointer (acfg, "globals");
6391 emit_pointer (acfg, NULL);
6393 emit_pointer (acfg, "assembly_name");
6395 emit_int32 (acfg, acfg->plt_got_offset_base);
6396 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6397 emit_int32 (acfg, acfg->plt_offset);
6398 emit_int32 (acfg, acfg->nmethods);
6399 emit_int32 (acfg, acfg->flags);
6400 emit_int32 (acfg, acfg->opts);
6401 emit_int32 (acfg, gc_name_offset);
6403 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6404 emit_int32 (acfg, acfg->num_trampolines [i]);
6405 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6406 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6407 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6408 emit_int32 (acfg, acfg->trampoline_size [i]);
6410 #if defined (TARGET_ARM) && defined (__APPLE__)
6415 t.type = MONO_TYPE_R8;
6416 mono_type_size (&t, &align);
6418 emit_int32 (acfg, align);
6420 t.type = MONO_TYPE_I8;
6421 mono_type_size (&t, &align);
6423 emit_int32 (acfg, align);
6426 emit_int32 (acfg, __alignof__ (double));
6427 emit_int32 (acfg, __alignof__ (gint64));
6430 if (acfg->aot_opts.static_link) {
6434 * Emit a global symbol which can be passed by an embedding app to
6435 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6438 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6439 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6441 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6444 /* Get rid of characters which cannot occur in symbols */
6446 for (p = symbol; *p; ++p) {
6447 if (!(isalnum (*p) || *p == '_'))
6450 acfg->static_linking_symbol = g_strdup (symbol);
6451 emit_global_inner (acfg, symbol, FALSE);
6452 emit_label (acfg, symbol);
6453 emit_pointer (acfg, "mono_aot_file_info");
6458 emit_blob (MonoAotCompile *acfg)
6462 sprintf (symbol, "blob");
6463 emit_section_change (acfg, RODATA_SECT, 1);
6464 emit_alignment (acfg, 8);
6465 emit_label (acfg, symbol);
6467 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6471 emit_dwarf_info (MonoAotCompile *acfg)
6473 #ifdef EMIT_DWARF_INFO
6475 char symbol [128], symbol2 [128];
6477 /* DIEs for methods */
6478 for (i = 0; i < acfg->nmethods; ++i) {
6479 MonoCompile *cfg = acfg->cfgs [i];
6484 // FIXME: LLVM doesn't define .Lme_...
6485 if (cfg->compile_llvm)
6488 sprintf (symbol, "%s", cfg->asm_symbol);
6489 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6491 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 ()));
6497 collect_methods (MonoAotCompile *acfg)
6500 MonoImage *image = acfg->image;
6502 /* Collect methods */
6503 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6505 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6507 method = mono_get_method (acfg->image, token, NULL);
6510 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6514 /* Load all methods eagerly to skip the slower lazy loading code */
6515 mono_class_setup_methods (method->klass);
6517 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6518 /* Compile the wrapper instead */
6519 /* We do this here instead of add_wrappers () because it is easy to do it here */
6520 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6524 /* FIXME: Some mscorlib methods don't have debug info */
6526 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6527 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6528 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6529 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6530 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6531 if (!mono_debug_lookup_method (method)) {
6532 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6539 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6540 add_method_with_index (acfg, method, i, FALSE);
6541 acfg->method_index ++;
6544 add_generic_instances (acfg);
6546 if (acfg->aot_opts.full_aot)
6547 add_wrappers (acfg);
6551 compile_methods (MonoAotCompile *acfg)
6555 if (acfg->aot_opts.nthreads > 0) {
6560 gpointer *user_data;
6561 MonoMethod **methods;
6563 methods_len = acfg->methods->len;
6565 len = acfg->methods->len / acfg->aot_opts.nthreads;
6568 * Partition the list of methods into fragments, and hand it to threads to
6571 threads = g_ptr_array_new ();
6572 /* Make a copy since acfg->methods is modified by compile_method () */
6573 methods = g_new0 (MonoMethod*, methods_len);
6574 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6575 for (i = 0; i < methods_len; ++i)
6576 methods [i] = g_ptr_array_index (acfg->methods, i);
6578 while (i < methods_len) {
6579 frag = g_ptr_array_new ();
6580 for (j = 0; j < len; ++j) {
6581 if (i < methods_len) {
6582 g_ptr_array_add (frag, methods [i]);
6587 user_data = g_new0 (gpointer, 3);
6588 user_data [0] = mono_domain_get ();
6589 user_data [1] = acfg;
6590 user_data [2] = frag;
6592 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6593 g_ptr_array_add (threads, handle);
6597 for (i = 0; i < threads->len; ++i) {
6598 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6604 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6605 for (i = methods_len; i < acfg->methods->len; ++i) {
6606 /* This can new methods to acfg->methods */
6607 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6612 compile_asm (MonoAotCompile *acfg)
6614 char *command, *objfile;
6615 char *outfile_name, *tmp_outfile_name;
6616 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6618 #if defined(TARGET_AMD64)
6619 #define AS_OPTIONS "--64"
6620 #elif defined(TARGET_POWERPC64)
6621 #define AS_OPTIONS "-a64 -mppc64"
6622 #define LD_OPTIONS "-m elf64ppc"
6623 #elif defined(sparc) && SIZEOF_VOID_P == 8
6624 #define AS_OPTIONS "-xarch=v9"
6625 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6626 #define AS_OPTIONS "-arch i386 -W"
6628 #define AS_OPTIONS ""
6631 #ifdef __native_client_codegen__
6632 #if defined(TARGET_AMD64)
6633 #define AS_NAME "nacl64-as"
6635 #define AS_NAME "nacl-as"
6638 #define AS_NAME "as"
6642 #define LD_OPTIONS ""
6645 #define EH_LD_OPTIONS ""
6647 if (acfg->aot_opts.asm_only) {
6648 printf ("Output file: '%s'.\n", acfg->tmpfname);
6649 if (acfg->aot_opts.static_link)
6650 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6654 if (acfg->aot_opts.static_link) {
6655 if (acfg->aot_opts.outfile)
6656 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6658 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6660 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6662 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);
6663 printf ("Executing the native assembler: %s\n", command);
6664 if (system (command) != 0) {
6672 if (acfg->aot_opts.static_link) {
6673 printf ("Output file: '%s'.\n", objfile);
6674 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6679 if (acfg->aot_opts.outfile)
6680 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6682 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6684 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6687 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6688 #elif defined(__ppc__) && defined(__APPLE__)
6689 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6690 #elif defined(HOST_WIN32)
6691 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6692 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6693 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6695 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6697 printf ("Executing the native linker: %s\n", command);
6698 if (system (command) != 0) {
6699 g_free (tmp_outfile_name);
6700 g_free (outfile_name);
6708 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6709 printf ("Stripping the binary: %s\n", com);
6713 #if defined(TARGET_ARM) && !defined(__APPLE__)
6715 * gas generates 'mapping symbols' each time code and data is mixed, which
6716 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6718 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6719 printf ("Stripping the binary: %s\n", command);
6720 if (system (command) != 0) {
6721 g_free (tmp_outfile_name);
6722 g_free (outfile_name);
6729 rename (tmp_outfile_name, outfile_name);
6731 g_free (tmp_outfile_name);
6732 g_free (outfile_name);
6735 if (acfg->aot_opts.save_temps)
6736 printf ("Retained input file.\n");
6738 unlink (acfg->tmpfname);
6743 static MonoAotCompile*
6744 acfg_create (MonoAssembly *ass, guint32 opts)
6746 MonoImage *image = ass->image;
6747 MonoAotCompile *acfg;
6750 acfg = g_new0 (MonoAotCompile, 1);
6751 acfg->methods = g_ptr_array_new ();
6752 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6753 acfg->method_depth = g_hash_table_new (NULL, NULL);
6754 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6755 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6756 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6757 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6758 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6759 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6760 acfg->got_patches = g_ptr_array_new ();
6761 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6762 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6763 acfg->image_hash = g_hash_table_new (NULL, NULL);
6764 acfg->image_table = g_ptr_array_new ();
6765 acfg->globals = g_ptr_array_new ();
6766 acfg->image = image;
6768 acfg->mempool = mono_mempool_new ();
6769 acfg->extra_methods = g_ptr_array_new ();
6770 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6771 acfg->unwind_ops = g_ptr_array_new ();
6772 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6773 InitializeCriticalSection (&acfg->mutex);
6779 acfg_free (MonoAotCompile *acfg)
6783 img_writer_destroy (acfg->w);
6784 for (i = 0; i < acfg->nmethods; ++i)
6786 g_free (acfg->cfgs [i]);
6787 g_free (acfg->cfgs);
6788 g_free (acfg->static_linking_symbol);
6789 g_free (acfg->got_symbol);
6790 g_free (acfg->plt_symbol);
6791 g_ptr_array_free (acfg->methods, TRUE);
6792 g_ptr_array_free (acfg->got_patches, TRUE);
6793 g_ptr_array_free (acfg->image_table, TRUE);
6794 g_ptr_array_free (acfg->globals, TRUE);
6795 g_ptr_array_free (acfg->unwind_ops, TRUE);
6796 g_hash_table_destroy (acfg->method_indexes);
6797 g_hash_table_destroy (acfg->method_depth);
6798 g_hash_table_destroy (acfg->plt_offset_to_entry);
6799 g_hash_table_destroy (acfg->patch_to_plt_entry);
6800 g_hash_table_destroy (acfg->patch_to_got_offset);
6801 g_hash_table_destroy (acfg->method_to_cfg);
6802 g_hash_table_destroy (acfg->token_info_hash);
6803 g_hash_table_destroy (acfg->image_hash);
6804 g_hash_table_destroy (acfg->unwind_info_offsets);
6805 g_hash_table_destroy (acfg->method_label_hash);
6806 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6807 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6808 g_free (acfg->patch_to_got_offset_by_type);
6809 mono_mempool_destroy (acfg->mempool);
6814 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6816 MonoImage *image = ass->image;
6818 MonoAotCompile *acfg;
6819 char *outfile_name, *tmp_outfile_name, *p;
6823 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6825 acfg = acfg_create (ass, opts);
6827 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6828 acfg->aot_opts.write_symbols = TRUE;
6829 acfg->aot_opts.ntrampolines = 1024;
6830 acfg->aot_opts.nrgctx_trampolines = 1024;
6831 acfg->aot_opts.nimt_trampolines = 128;
6832 acfg->aot_opts.llvm_path = g_strdup ("");
6834 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6836 if (acfg->aot_opts.static_link)
6837 acfg->aot_opts.autoreg = TRUE;
6839 //acfg->aot_opts.print_skipped_methods = TRUE;
6841 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6842 if (acfg->aot_opts.full_aot) {
6843 printf ("--aot=full is not supported on this platform.\n");
6848 if (acfg->aot_opts.static_link)
6849 acfg->aot_opts.asm_writer = TRUE;
6851 if (acfg->aot_opts.soft_debug) {
6852 MonoDebugOptions *opt = mini_get_debug_options ();
6854 opt->mdb_optimizations = TRUE;
6855 opt->gen_seq_points = TRUE;
6857 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6858 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6861 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6864 if (mono_use_llvm) {
6866 acfg->aot_opts.asm_writer = TRUE;
6867 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6869 if (acfg->aot_opts.soft_debug) {
6870 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6875 if (acfg->aot_opts.full_aot)
6876 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6878 load_profile_files (acfg);
6880 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6881 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6882 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6884 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6886 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6890 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6891 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6893 /* Get rid of characters which cannot occur in symbols */
6894 for (p = acfg->got_symbol_base; *p; ++p) {
6895 if (!(isalnum (*p) || *p == '_'))
6898 for (p = acfg->plt_symbol; *p; ++p) {
6899 if (!(isalnum (*p) || *p == '_'))
6903 acfg->method_index = 1;
6905 collect_methods (acfg);
6907 acfg->cfgs_size = acfg->methods->len + 32;
6908 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6910 /* PLT offset 0 is reserved for the PLT trampoline */
6911 acfg->plt_offset = 1;
6916 mono_llvm_create_aot_module (acfg->got_symbol_base);
6920 /* GOT offset 0 is reserved for the address of the current assembly */
6924 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6925 ji->type = MONO_PATCH_INFO_IMAGE;
6926 ji->data.image = acfg->image;
6928 get_got_offset (acfg, ji);
6930 /* Slot 1 is reserved for the mscorlib got addr */
6931 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6932 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6933 get_got_offset (acfg, ji);
6935 /* This is very common */
6936 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6937 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6938 get_got_offset (acfg, ji);
6943 compile_methods (acfg);
6947 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6953 if (acfg->aot_opts.asm_only) {
6954 if (acfg->aot_opts.outfile)
6955 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6957 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6959 acfg->tmpfname = g_strdup ("temp.s");
6962 emit_llvm_file (acfg);
6966 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6967 if (acfg->aot_opts.outfile)
6968 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6970 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6973 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6974 * it might be in another file system so the rename () won't work.
6976 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6978 acfg->fp = fopen (tmp_outfile_name, "w");
6980 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6984 acfg->w = img_writer_create (acfg->fp, TRUE);
6985 acfg->use_bin_writer = TRUE;
6988 /* Append to the .s file created by llvm */
6989 /* FIXME: Use multiple files instead */
6990 acfg->fp = fopen (acfg->tmpfname, "a+");
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);
6997 acfg->fp = fopen (acfg->tmpfname, "w+");
6999 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7000 acfg->fp = fdopen (i, "w+");
7002 g_assert (acfg->fp);
7004 acfg->w = img_writer_create (acfg->fp, FALSE);
7006 tmp_outfile_name = NULL;
7007 outfile_name = NULL;
7010 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7012 /* Compute symbols for methods */
7013 for (i = 0; i < acfg->nmethods; ++i) {
7014 if (acfg->cfgs [i]) {
7015 MonoCompile *cfg = acfg->cfgs [i];
7016 int method_index = get_method_index (acfg, cfg->orig_method);
7018 if (COMPILE_LLVM (cfg))
7019 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7021 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7025 if (!acfg->aot_opts.nodebug)
7026 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7028 img_writer_emit_start (acfg->w);
7031 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7033 if (acfg->thumb_mixed) {
7036 * This global symbol marks the end of THUMB code, and the beginning of ARM
7037 * code generated by our JIT.
7039 sprintf (symbol, "thumb_end");
7040 emit_section_change (acfg, ".text", 0);
7041 emit_label (acfg, symbol);
7042 emit_zero_bytes (acfg, 16);
7044 fprintf (acfg->fp, ".arm\n");
7051 emit_extra_methods (acfg);
7053 emit_trampolines (acfg);
7055 emit_class_name_table (acfg);
7057 emit_got_info (acfg);
7059 emit_exception_info (acfg);
7061 emit_unwind_info (acfg);
7063 emit_class_info (acfg);
7067 emit_image_table (acfg);
7071 emit_file_info (acfg);
7075 emit_globals (acfg);
7077 emit_autoreg (acfg);
7080 emit_dwarf_info (acfg);
7081 mono_dwarf_writer_close (acfg->dwarf);
7084 emit_mem_end (acfg);
7086 if (acfg->need_pt_gnu_stack) {
7087 /* This is required so the .so doesn't have an executable stack */
7088 /* The bin writer already emits this */
7089 if (!acfg->use_bin_writer)
7090 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7095 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7098 g_assert (acfg->got_offset <= acfg->final_got_size);
7100 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);
7103 res = img_writer_emit_writeout (acfg->w);
7108 if (acfg->use_bin_writer) {
7109 int err = rename (tmp_outfile_name, outfile_name);
7112 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7116 res = compile_asm (acfg);
7123 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7125 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);
7126 if (acfg->stats.genericcount)
7127 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7128 if (acfg->stats.abscount)
7129 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7130 if (acfg->stats.lmfcount)
7131 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7132 if (acfg->stats.ocount)
7133 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7135 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7136 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);
7137 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7139 if (acfg->aot_opts.stats) {
7142 printf ("GOT slot distribution:\n");
7143 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7144 if (acfg->stats.got_slot_types [i])
7145 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7148 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);
7160 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)