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;
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;
579 * arch_emit_direct_call:
581 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
585 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
587 #if defined(TARGET_X86) || defined(TARGET_AMD64)
588 /* Need to make sure this is exactly 5 bytes long */
589 emit_byte (acfg, '\xe8');
590 emit_symbol_diff (acfg, target, ".", -4);
592 #elif defined(TARGET_ARM)
593 if (acfg->use_bin_writer) {
600 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
601 emit_bytes (acfg, buf, 4);
603 img_writer_emit_unset_mode (acfg->w);
604 fprintf (acfg->fp, "bl %s\n", target);
607 #elif defined(TARGET_POWERPC)
608 if (acfg->use_bin_writer) {
609 g_assert_not_reached ();
611 img_writer_emit_unset_mode (acfg->w);
612 fprintf (acfg->fp, "bl %s\n", target);
616 g_assert_not_reached ();
622 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
624 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
625 * in in the 2. slot of every GOT, and require every method to place the GOT
626 * address in r30, even when it doesn't access the GOT otherwise. This way,
627 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
632 * PPC64 uses function descriptors which greatly complicate all code, since
633 * these are used very inconsistently in the runtime. Some functions like
634 * mono_compile_method () return ftn descriptors, while others like the
635 * trampoline creation functions do not.
636 * We assume that all GOT slots contain function descriptors, and create
637 * descriptors in aot-runtime.c when needed.
638 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
639 * from function descriptors, we could do the same, but it would require
640 * rewriting all the ppc/aot code to handle function descriptors properly.
641 * So instead, we use the same approach as on PPC32.
642 * This is a horrible mess, but fixing it would probably lead to an even bigger
648 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
651 #ifdef MONO_ARCH_AOT_SUPPORTED
653 * arch_emit_got_offset:
655 * The memory pointed to by CODE should hold native code for computing the GOT
656 * address. Emit this code while patching it with the offset between code and
657 * the GOT. CODE_SIZE is set to the number of bytes emitted.
660 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
662 #if defined(TARGET_POWERPC64)
663 g_assert (!acfg->use_bin_writer);
664 img_writer_emit_unset_mode (acfg->w);
666 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
667 * unsupported relocations. So we store the got address into the .Lgot_addr
668 * symbol which is in the text segment, compute its address, and load it.
670 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
671 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
672 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
673 fprintf (acfg->fp, "add 30, 30, 0\n");
674 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
675 acfg->label_generator ++;
677 #elif defined(TARGET_POWERPC)
678 g_assert (!acfg->use_bin_writer);
679 img_writer_emit_unset_mode (acfg->w);
680 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
681 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
682 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
683 acfg->label_generator ++;
686 guint32 offset = mono_arch_get_patch_offset (code);
687 emit_bytes (acfg, code, offset);
688 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
690 *code_size = offset + 4;
695 * arch_emit_got_access:
697 * The memory pointed to by CODE should hold native code for loading a GOT
698 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
699 * CODE_SIZE is set to the number of bytes emitted.
702 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
704 /* Emit beginning of instruction */
705 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
707 /* Emit the offset */
709 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
710 *code_size = mono_arch_get_patch_offset (code) + 4;
711 #elif defined(TARGET_X86)
712 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
713 *code_size = mono_arch_get_patch_offset (code) + 4;
714 #elif defined(TARGET_ARM)
715 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
716 *code_size = mono_arch_get_patch_offset (code) + 4;
717 #elif defined(TARGET_POWERPC)
723 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
724 g_assert (code - buf == 8);
725 emit_bytes (acfg, buf, code - buf);
726 *code_size = code - buf;
729 g_assert_not_reached ();
736 * arch_emit_plt_entry:
738 * Emit code for the PLT entry with index INDEX.
741 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
743 #if defined(TARGET_X86)
744 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
745 #if defined(__default_codegen__)
746 /* jmp *<offset>(%ebx) */
747 emit_byte (acfg, 0xff);
748 emit_byte (acfg, 0xa3);
749 emit_int32 (acfg, offset);
750 /* Used by mono_aot_get_plt_info_offset */
751 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
752 #elif defined(__native_client_codegen__)
753 const guint8 kSizeOfNaClJmp = 11;
754 guint8 bytes[kSizeOfNaClJmp];
755 guint8 *pbytes = &bytes[0];
757 x86_jump_membase32 (pbytes, X86_EBX, offset);
758 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
759 /* four bytes of data, used by mono_arch_patch_plt_entry */
760 /* For Native Client, make this work with data embedded in push. */
761 emit_byte (acfg, 0x68); /* hide data in a push */
762 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
763 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
764 #endif /*__native_client_codegen__*/
765 #elif defined(TARGET_AMD64)
766 #if defined(__default_codegen__)
768 * We can't emit jumps because they are 32 bits only so they can't be patched.
769 * So we make indirect calls through GOT entries which are patched by the AOT
770 * loader to point to .Lpd entries.
772 /* jmpq *<offset>(%rip) */
773 emit_byte (acfg, '\xff');
774 emit_byte (acfg, '\x25');
775 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
776 /* Used by mono_aot_get_plt_info_offset */
777 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
778 #elif defined(__native_client_codegen__)
780 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
781 guint8 *code = buf_aligned;
783 /* mov <OFFSET>(%rip), %r11d */
784 emit_byte (acfg, '\x45');
785 emit_byte (acfg, '\x8b');
786 emit_byte (acfg, '\x1d');
787 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
789 amd64_jump_reg (code, AMD64_R11);
790 /* This should be constant for the plt patch */
791 g_assert ((size_t)(code-buf_aligned) == 10);
792 emit_bytes (acfg, buf_aligned, code - buf_aligned);
794 /* Hide data in a push imm32 so it passes validation */
795 emit_byte (acfg, 0x68); /* push */
796 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
797 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
798 #endif /*__native_client_codegen__*/
799 #elif defined(TARGET_ARM)
804 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
805 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
806 emit_bytes (acfg, buf, code - buf);
807 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
808 /* Used by mono_aot_get_plt_info_offset */
809 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
810 #elif defined(TARGET_POWERPC)
811 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
813 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
814 g_assert (!acfg->use_bin_writer);
815 img_writer_emit_unset_mode (acfg->w);
816 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
817 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
818 fprintf (acfg->fp, "add 11, 11, 30\n");
819 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
820 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
821 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
822 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
824 fprintf (acfg->fp, "mtctr 11\n");
825 fprintf (acfg->fp, "bctr\n");
826 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
828 g_assert_not_reached ();
833 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
835 #if defined(TARGET_ARM)
837 /* LLVM calls the PLT entries using bl, so emit a stub */
838 /* FIXME: Too much overhead on every call */
839 fprintf (acfg->fp, ".thumb_func\n");
840 fprintf (acfg->fp, "bx pc\n");
841 fprintf (acfg->fp, "nop\n");
842 fprintf (acfg->fp, ".arm\n");
844 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
845 /* The caller already transitioned to thumb */
846 /* The code below should be 12 bytes long */
847 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
848 /* thumb can't encode ld pc, [pc, ip] */
849 fprintf (acfg->fp, "add ip, pc, ip\n");
850 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
851 fprintf (acfg->fp, "bx ip\n");
852 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
853 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
855 g_assert_not_reached ();
860 * arch_emit_specific_trampoline:
862 * Emit code for a specific trampoline. OFFSET is the offset of the first of
863 * two GOT slots which contain the generic trampoline address and the trampoline
864 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
867 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
870 * The trampolines created here are variations of the specific
871 * trampolines created in mono_arch_create_specific_trampoline (). The
873 * - the generic trampoline address is taken from a got slot.
874 * - the offset of the got slot where the trampoline argument is stored
875 * is embedded in the instruction stream, and the generic trampoline
876 * can load the argument by loading the offset, adding it to the
877 * address of the trampoline to get the address of the got slot, and
878 * loading the argument from there.
879 * - all the trampolines should be of the same length.
881 #if defined(TARGET_AMD64)
882 #if defined(__default_codegen__)
883 /* This should be exactly 16 bytes long */
885 /* call *<offset>(%rip) */
886 emit_byte (acfg, '\x41');
887 emit_byte (acfg, '\xff');
888 emit_byte (acfg, '\x15');
889 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
890 /* This should be relative to the start of the trampoline */
891 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
892 emit_zero_bytes (acfg, 5);
893 #elif defined(__native_client_codegen__)
895 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
896 guint8 *code = buf_aligned;
901 /* Emit this call in 'code' so we can find out how long it is. */
902 amd64_call_reg (code, AMD64_R11);
903 call_start = mono_arch_nacl_skip_nops (buf_aligned);
904 call_len = code - call_start;
906 /* The tramp_size is twice the NaCl alignment because it starts with */
907 /* a call which needs to be aligned to the end of the boundary. */
908 *tramp_size = kNaClAlignment*2;
910 /* Emit nops to align call site below which is 7 bytes plus */
911 /* the length of the call sequence emitted above. */
912 /* Note: this requires the specific trampoline starts on a */
913 /* kNaclAlignedment aligned address, which it does because */
914 /* it's its own function that is aligned. */
916 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
917 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
918 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
920 /* The trampoline is stored at the offset'th pointer, the -4 is */
921 /* present because RIP relative addressing starts at the end of */
922 /* the current instruction, while the label "." is relative to */
923 /* the beginning of the current asm location, which in this case */
924 /* is not the mov instruction, but the offset itself, due to the */
925 /* way the bytes and ints are emitted here. */
926 got_offset = (offset * sizeof(gpointer)) - 4;
928 /* mov <OFFSET>(%rip), %r11d */
929 emit_byte (acfg, '\x45');
930 emit_byte (acfg, '\x8b');
931 emit_byte (acfg, '\x1d');
932 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
935 emit_bytes (acfg, call_start, call_len);
937 /* The arg is stored at the offset+1 pointer, relative to beginning */
938 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
939 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
941 /* We can't emit this data directly, hide in a "push imm32" */
942 emit_byte (acfg, '\x68'); /* push */
943 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
944 emit_alignment (acfg, kNaClAlignment);
945 #endif /*__native_client_codegen__*/
946 #elif defined(TARGET_ARM)
950 /* This should be exactly 20 bytes long */
953 ARM_PUSH (code, 0x5fff);
954 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
955 /* Load the value from the GOT */
956 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
958 ARM_BLX_REG (code, ARMREG_R1);
960 g_assert (code - buf == 16);
963 emit_bytes (acfg, buf, code - buf);
965 * Only one offset is needed, since the second one would be equal to the
968 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
969 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
970 #elif defined(TARGET_POWERPC)
977 g_assert (!acfg->use_bin_writer);
980 * PPC has no ip relative addressing, so we need to compute the address
981 * of the mscorlib got. That is slow and complex, so instead, we store it
982 * in the second got slot of every aot image. The caller already computed
983 * the address of its got and placed it into r30.
985 img_writer_emit_unset_mode (acfg->w);
986 /* Load mscorlib got address */
987 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
988 /* Load generic trampoline address */
989 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
990 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
991 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
992 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
993 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
995 fprintf (acfg->fp, "mtctr 11\n");
996 /* Load trampoline argument */
997 /* On ppc, we pass it normally to the generic trampoline */
998 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
999 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1000 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1001 /* Branch to generic trampoline */
1002 fprintf (acfg->fp, "bctr\n");
1004 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1005 *tramp_size = 10 * 4;
1007 *tramp_size = 9 * 4;
1009 #elif defined(TARGET_X86)
1013 /* Similar to the PPC code above */
1015 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1017 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1018 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1019 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1023 /* Load mscorlib got address */
1024 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1025 /* Push trampoline argument */
1026 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1027 /* Load generic trampoline address */
1028 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1029 /* Branch to generic trampoline */
1030 x86_jump_reg (code, X86_ECX);
1032 #ifdef __native_client_codegen__
1034 /* emit nops to next 32 byte alignment */
1035 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1036 while (code < (buf + a)) x86_nop(code);
1039 emit_bytes (acfg, buf, code - buf);
1041 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1042 g_assert (code - buf == *tramp_size);
1044 g_assert_not_reached ();
1049 * arch_emit_unbox_trampoline:
1051 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1052 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1055 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1057 #if defined(TARGET_AMD64)
1062 this_reg = mono_arch_get_this_arg_reg (NULL);
1064 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1066 emit_bytes (acfg, buf, code - buf);
1068 emit_byte (acfg, '\xe9');
1069 emit_symbol_diff (acfg, call_target, ".", -4);
1070 #elif defined(TARGET_X86)
1077 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1079 emit_bytes (acfg, buf, code - buf);
1082 emit_byte (acfg, '\xe9');
1083 emit_symbol_diff (acfg, call_target, ".", -4);
1084 #elif defined(TARGET_ARM)
1088 if (acfg->thumb_mixed && cfg->compile_llvm) {
1089 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1090 fprintf (acfg->fp, "b %s\n", call_target);
1091 fprintf (acfg->fp, ".arm\n");
1097 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1099 emit_bytes (acfg, buf, code - buf);
1100 /* jump to method */
1101 if (acfg->use_bin_writer) {
1108 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1109 emit_bytes (acfg, buf, 4);
1111 if (acfg->thumb_mixed && cfg->compile_llvm)
1112 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1114 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1116 #elif defined(TARGET_POWERPC)
1119 g_assert (!acfg->use_bin_writer);
1121 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1122 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1124 g_assert_not_reached ();
1129 * arch_emit_static_rgctx_trampoline:
1131 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1132 * two GOT slots which contain the rgctx argument, and the method to jump to.
1133 * TRAMP_SIZE is set to the size of the emitted trampoline.
1134 * These kinds of trampolines cannot be enumerated statically, since there could
1135 * be one trampoline per method instantiation, so we emit the same code for all
1136 * trampolines, and parameterize them using two GOT slots.
1139 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1141 #if defined(TARGET_AMD64)
1142 #if defined(__default_codegen__)
1143 /* This should be exactly 13 bytes long */
1146 /* mov <OFFSET>(%rip), %r10 */
1147 emit_byte (acfg, '\x4d');
1148 emit_byte (acfg, '\x8b');
1149 emit_byte (acfg, '\x15');
1150 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1152 /* jmp *<offset>(%rip) */
1153 emit_byte (acfg, '\xff');
1154 emit_byte (acfg, '\x25');
1155 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1156 #elif defined(__native_client_codegen__)
1158 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1159 guint8 *code = buf_aligned;
1161 /* mov <OFFSET>(%rip), %r10d */
1162 emit_byte (acfg, '\x45');
1163 emit_byte (acfg, '\x8b');
1164 emit_byte (acfg, '\x15');
1165 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1167 /* mov <OFFSET>(%rip), %r11d */
1168 emit_byte (acfg, '\x45');
1169 emit_byte (acfg, '\x8b');
1170 emit_byte (acfg, '\x1d');
1171 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1174 amd64_jump_reg (code, AMD64_R11);
1175 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1177 emit_alignment (acfg, kNaClAlignment);
1178 *tramp_size = kNaClAlignment;
1179 #endif /*__native_client_codegen__*/
1181 #elif defined(TARGET_ARM)
1185 /* This should be exactly 24 bytes long */
1188 /* Load rgctx value */
1189 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1190 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1191 /* Load branch addr + branch */
1192 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1193 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1195 g_assert (code - buf == 16);
1198 emit_bytes (acfg, buf, code - buf);
1199 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1200 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1201 #elif defined(TARGET_POWERPC)
1208 g_assert (!acfg->use_bin_writer);
1211 * PPC has no ip relative addressing, so we need to compute the address
1212 * of the mscorlib got. That is slow and complex, so instead, we store it
1213 * in the second got slot of every aot image. The caller already computed
1214 * the address of its got and placed it into r30.
1216 img_writer_emit_unset_mode (acfg->w);
1217 /* Load mscorlib got address */
1218 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1220 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1221 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1222 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1223 /* Load target address */
1224 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1225 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1226 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1227 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1228 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1229 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1231 fprintf (acfg->fp, "mtctr 11\n");
1232 /* Branch to the target address */
1233 fprintf (acfg->fp, "bctr\n");
1235 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1236 *tramp_size = 11 * 4;
1238 *tramp_size = 9 * 4;
1241 #elif defined(TARGET_X86)
1245 /* Similar to the PPC code above */
1247 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1250 /* Load mscorlib got address */
1251 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1253 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1254 /* Branch to the target address */
1255 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1257 #ifdef __native_client_codegen__
1259 /* emit nops to next 32 byte alignment */
1260 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1261 while (code < (buf + a)) x86_nop(code);
1265 emit_bytes (acfg, buf, code - buf);
1267 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1268 g_assert (code - buf == *tramp_size);
1270 g_assert_not_reached ();
1275 * arch_emit_imt_thunk:
1277 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1278 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1279 * key is the IMT key, and ptr holds the address of a memory location holding
1280 * the address to branch to if the IMT arg matches the key. The array is
1281 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1283 * TRAMP_SIZE is set to the size of the emitted trampoline.
1286 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1288 #if defined(TARGET_AMD64)
1290 #if defined(__native_client_codegen__)
1295 guint8 *mov_buf_ptr = mov_buf;
1297 const int kSizeOfMove = 7;
1298 #if defined(__default_codegen__)
1299 code = buf = g_malloc (256);
1300 #elif defined(__native_client_codegen__)
1301 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1302 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1303 /* The RIP relative move below is emitted first */
1308 /* FIXME: Optimize this, i.e. use binary search etc. */
1309 /* Maybe move the body into a separate function (slower, but much smaller) */
1311 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1314 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1316 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1319 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1321 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1324 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1325 amd64_jump_code (code, labels [0]);
1328 mono_amd64_patch (labels [2], code);
1329 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1330 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1334 mono_amd64_patch (labels [1], code);
1335 x86_breakpoint (code);
1337 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1338 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1339 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1340 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1341 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1342 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1344 emit_bytes (acfg, buf, code - buf);
1346 *tramp_size = code - buf + kSizeOfMove;
1347 #if defined(__native_client_codegen__)
1348 /* The tramp will be padded to the next kNaClAlignment bundle. */
1349 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1352 #if defined(__default_codegen__)
1354 #elif defined(__native_client_codegen__)
1358 #elif defined(TARGET_X86)
1360 #ifdef __native_client_codegen__
1365 #if defined(__default_codegen__)
1366 code = buf = g_malloc (256);
1367 #elif defined(__native_client_codegen__)
1368 buf_alloc = g_malloc (256 + kNaClAlignment);
1369 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1372 /* Allocate a temporary stack slot */
1373 x86_push_reg (code, X86_EAX);
1375 x86_push_reg (code, X86_EAX);
1377 /* Load mscorlib got address */
1378 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1380 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1383 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1385 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1388 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1390 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1393 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1394 x86_jump_code (code, labels [0]);
1397 mono_x86_patch (labels [2], code);
1398 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1399 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1400 /* Save the target address to the temporary stack location */
1401 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1403 x86_pop_reg (code, X86_EAX);
1404 /* Jump to the target address */
1409 mono_x86_patch (labels [1], code);
1410 x86_breakpoint (code);
1412 #ifdef __native_client_codegen__
1414 /* emit nops to next 32 byte alignment */
1415 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1416 while (code < (buf + a)) x86_nop(code);
1419 emit_bytes (acfg, buf, code - buf);
1421 *tramp_size = code - buf;
1423 #if defined(__default_codegen__)
1425 #elif defined(__native_client_codegen__)
1429 #elif defined(TARGET_ARM)
1431 guint8 *code, *code2, *labels [16];
1435 /* The IMT method is in v5 */
1437 /* Need at least two free registers, plus a slot for storing the pc */
1438 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1440 /* Load the parameter from the GOT */
1441 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1442 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1445 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1446 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1448 ARM_B_COND (code, ARMCOND_EQ, 0);
1450 /* End-of-loop check */
1451 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1453 ARM_B_COND (code, ARMCOND_EQ, 0);
1456 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1459 arm_patch (labels [4], labels [1]);
1462 arm_patch (labels [2], code);
1463 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1464 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1465 /* Save it to the third stack slot */
1466 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1467 /* Restore the registers and branch */
1468 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1471 arm_patch (labels [3], code);
1476 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1478 emit_bytes (acfg, buf, code - buf);
1479 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1481 *tramp_size = code - buf + 4;
1482 #elif defined(TARGET_POWERPC)
1484 guint8 *code, *labels [16];
1488 /* Load the mscorlib got address */
1489 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1490 /* Load the parameter from the GOT */
1491 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1492 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1494 /* Load and check key */
1496 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1497 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1499 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1501 /* End-of-loop check */
1502 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1504 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1507 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1510 mono_ppc_patch (labels [4], labels [1]);
1513 mono_ppc_patch (labels [2], code);
1514 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1515 /* r11 now contains the value of the vtable slot */
1516 /* this is not a function descriptor on ppc64 */
1517 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1518 ppc_mtctr (code, ppc_r11);
1519 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1522 mono_ppc_patch (labels [3], code);
1526 *tramp_size = code - buf;
1528 emit_bytes (acfg, buf, code - buf);
1530 g_assert_not_reached ();
1535 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1537 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1538 /* Based on code generated by gcc */
1539 img_writer_emit_unset_mode (acfg->w);
1542 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1543 ".section .ctors,\"aw\",@progbits\n"
1547 ".section .opd,\"aw\"\n"
1550 ".long .%s,.TOC.@tocbase32\n"
1553 ".type .%s,@function\n"
1555 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1557 ".section .ctors,\"aw\",@progbits\n"
1561 ".section .opd,\"aw\"\n"
1564 ".long .%1$s,.TOC.@tocbase32\n"
1565 ".size %1$s,.-%1$s\n"
1567 ".type .%1$s,@function\n"
1569 ".%1$s:\n", symbol);
1580 "lis 3, .Lglobals@h\n"
1581 "ori 3, 3, .Lglobals@l\n"
1582 "bl .mono_aot_register_module\n"
1590 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1592 ".size .%s,.-.%s\n", symbol, symbol);
1595 ".size .%1$s,.-.%1$s\n", symbol);
1601 /* END OF ARCH SPECIFIC CODE */
1604 mono_get_field_token (MonoClassField *field)
1606 MonoClass *klass = field->parent;
1609 for (i = 0; i < klass->field.count; ++i) {
1610 if (field == &klass->fields [i])
1611 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1614 g_assert_not_reached ();
1619 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1623 //printf ("ENCODE: %d 0x%x.\n", value, value);
1626 * Same encoding as the one used in the metadata, extended to handle values
1627 * greater than 0x1fffffff.
1629 if ((value >= 0) && (value <= 127))
1631 else if ((value >= 0) && (value <= 16383)) {
1632 p [0] = 0x80 | (value >> 8);
1633 p [1] = value & 0xff;
1635 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1636 p [0] = (value >> 24) | 0xc0;
1637 p [1] = (value >> 16) & 0xff;
1638 p [2] = (value >> 8) & 0xff;
1639 p [3] = value & 0xff;
1644 p [1] = (value >> 24) & 0xff;
1645 p [2] = (value >> 16) & 0xff;
1646 p [3] = (value >> 8) & 0xff;
1647 p [4] = value & 0xff;
1655 stream_init (MonoDynamicStream *sh)
1658 sh->alloc_size = 4096;
1659 sh->data = g_malloc (4096);
1661 /* So offsets are > 0 */
1667 make_room_in_stream (MonoDynamicStream *stream, int size)
1669 if (size <= stream->alloc_size)
1672 while (stream->alloc_size <= size) {
1673 if (stream->alloc_size < 4096)
1674 stream->alloc_size = 4096;
1676 stream->alloc_size *= 2;
1679 stream->data = g_realloc (stream->data, stream->alloc_size);
1683 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1687 make_room_in_stream (stream, stream->index + len);
1688 memcpy (stream->data + stream->index, data, len);
1689 idx = stream->index;
1690 stream->index += len;
1697 * Add data to the binary blob inside the aot image. Returns the offset inside the
1698 * blob where the data was stored.
1701 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1703 if (acfg->blob.alloc_size == 0)
1704 stream_init (&acfg->blob);
1706 return add_stream_data (&acfg->blob, (char*)data, data_len);
1710 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1715 if (acfg->blob.alloc_size == 0)
1716 stream_init (&acfg->blob);
1718 count = acfg->blob.index % align;
1720 /* we assume the stream data will be aligned */
1722 add_stream_data (&acfg->blob, buf, 4 - count);
1724 return add_stream_data (&acfg->blob, (char*)data, data_len);
1728 * emit_offset_table:
1730 * Emit a table of increasing offsets in a compact form using differential encoding.
1731 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1732 * group size, the more compact the table becomes, but the slower it becomes to compute
1733 * a given entry. Returns the size of the table.
1736 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1738 gint32 current_offset;
1739 int i, buf_size, ngroups, index_entry_size;
1741 guint32 *index_offsets;
1743 ngroups = (noffsets + (group_size - 1)) / group_size;
1745 index_offsets = g_new0 (guint32, ngroups);
1747 buf_size = noffsets * 4;
1748 p = buf = g_malloc0 (buf_size);
1751 for (i = 0; i < noffsets; ++i) {
1752 //printf ("D: %d -> %d\n", i, offsets [i]);
1753 if ((i % group_size) == 0) {
1754 index_offsets [i / group_size] = p - buf;
1755 /* Emit the full value for these entries */
1756 encode_value (offsets [i], p, &p);
1758 /* The offsets are allowed to be non-increasing */
1759 //g_assert (offsets [i] >= current_offset);
1760 encode_value (offsets [i] - current_offset, p, &p);
1762 current_offset = offsets [i];
1765 if (ngroups && index_offsets [ngroups - 1] < 65000)
1766 index_entry_size = 2;
1768 index_entry_size = 4;
1770 /* Emit the header */
1771 emit_int32 (acfg, noffsets);
1772 emit_int32 (acfg, group_size);
1773 emit_int32 (acfg, ngroups);
1774 emit_int32 (acfg, index_entry_size);
1776 /* Emit the index */
1777 for (i = 0; i < ngroups; ++i) {
1778 if (index_entry_size == 2)
1779 emit_int16 (acfg, index_offsets [i]);
1781 emit_int32 (acfg, index_offsets [i]);
1785 emit_bytes (acfg, buf, p - buf);
1787 return (int)(p - buf) + (ngroups * 4);
1791 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1795 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1799 index = g_hash_table_size (cfg->image_hash);
1800 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1801 g_ptr_array_add (cfg->image_table, image);
1807 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1810 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1812 /* FIXME: Search referenced images as well */
1813 if (!acfg->typespec_classes) {
1814 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1815 for (i = 0; i < len; ++i) {
1816 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1819 for (i = 0; i < len; ++i) {
1820 if (acfg->typespec_classes [i] == klass)
1825 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1831 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1836 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1837 * standard metadata encoding.
1840 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1844 if (klass->generic_class) {
1846 g_assert (klass->type_token);
1848 /* Find a typespec for a class if possible */
1849 token = find_typespec_for_class (acfg, klass);
1851 encode_value (token, p, &p);
1852 encode_value (get_image_index (acfg, acfg->image), p, &p);
1854 MonoClass *gclass = klass->generic_class->container_class;
1855 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1858 /* Encode it ourselves */
1860 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1861 encode_value (MONO_TYPE_GENERICINST, p, &p);
1862 encode_klass_ref (acfg, gclass, p, &p);
1863 encode_value (inst->type_argc, p, &p);
1864 for (i = 0; i < inst->type_argc; ++i)
1865 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1867 } else if (klass->type_token) {
1868 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1869 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1870 encode_value (get_image_index (acfg, klass->image), p, &p);
1871 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1872 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1873 g_assert (container);
1876 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1877 encode_value (klass->byval_arg.type, p, &p);
1879 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1881 encode_value (container->is_method, p, &p);
1882 if (container->is_method)
1883 encode_method_ref (acfg, container->owner.method, p, &p);
1885 encode_klass_ref (acfg, container->owner.klass, p, &p);
1888 g_assert (klass->rank > 0);
1889 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1890 encode_value (get_image_index (acfg, klass->image), p, &p);
1891 encode_value (klass->rank, p, &p);
1892 encode_klass_ref (acfg, klass->element_class, p, &p);
1898 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1900 guint32 token = mono_get_field_token (field);
1903 encode_klass_ref (cfg, field->parent, p, &p);
1904 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1905 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1910 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1914 MonoGenericInst *inst;
1916 /* Encode the context */
1917 inst = context->class_inst;
1918 encode_value (inst ? 1 : 0, p, &p);
1920 encode_value (inst->type_argc, p, &p);
1921 for (i = 0; i < inst->type_argc; ++i)
1922 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1924 inst = context->method_inst;
1925 encode_value (inst ? 1 : 0, p, &p);
1927 encode_value (inst->type_argc, p, &p);
1928 for (i = 0; i < inst->type_argc; ++i)
1929 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1935 #define MAX_IMAGE_INDEX 250
1938 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1940 guint32 image_index = get_image_index (acfg, method->klass->image);
1941 guint32 token = method->token;
1942 MonoJumpInfoToken *ji;
1947 * The encoding for most methods is as follows:
1948 * - image index encoded as a leb128
1949 * - token index encoded as a leb128
1950 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1951 * types of method encodings.
1954 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1956 /* Mark methods which can't use aot trampolines because they need the further
1957 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1959 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1960 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1961 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1964 * Some wrapper methods are shared using their signature, encode their
1965 * stringified signature instead.
1966 * FIXME: Optimize disk usage
1969 if (method->wrapper_type) {
1970 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1971 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1972 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1973 name = mono_aot_wrapper_name (method);
1974 } else if (mono_marshal_method_from_wrapper (method) != method) {
1975 /* Direct wrapper, encode it normally */
1977 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1980 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1981 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1982 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1984 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1985 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1986 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1988 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1989 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1990 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1996 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1997 strcpy ((char*)p, name);
1998 p += strlen (name) + 1;
2000 } else if (method->wrapper_type) {
2001 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2003 encode_value (method->wrapper_type, p, &p);
2005 switch (method->wrapper_type) {
2006 case MONO_WRAPPER_REMOTING_INVOKE:
2007 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2008 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2011 m = mono_marshal_method_from_wrapper (method);
2013 encode_method_ref (acfg, m, p, &p);
2016 case MONO_WRAPPER_PROXY_ISINST:
2017 case MONO_WRAPPER_LDFLD:
2018 case MONO_WRAPPER_LDFLDA:
2019 case MONO_WRAPPER_STFLD:
2020 case MONO_WRAPPER_ISINST: {
2021 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2022 encode_klass_ref (acfg, proxy_class, p, &p);
2025 case MONO_WRAPPER_LDFLD_REMOTE:
2026 case MONO_WRAPPER_STFLD_REMOTE:
2028 case MONO_WRAPPER_ALLOC: {
2029 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2031 /* The GC name is saved once in MonoAotFileInfo */
2032 g_assert (info->alloc_type != -1);
2033 encode_value (info->alloc_type, p, &p);
2036 case MONO_WRAPPER_WRITE_BARRIER:
2038 case MONO_WRAPPER_STELEMREF: {
2039 MonoClass *klass = mono_marshal_get_wrapper_info (method);
2041 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
2045 case MONO_WRAPPER_UNKNOWN:
2046 if (strcmp (method->name, "FastMonitorEnter") == 0) {
2047 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
2048 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2049 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
2050 } else if (strcmp (method->name, "PtrToStructure") == 0) {
2051 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2052 encode_klass_ref (acfg, method->klass, p, &p);
2053 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2054 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2055 encode_klass_ref (acfg, method->klass, p, &p);
2057 g_assert_not_reached ();
2060 case MONO_WRAPPER_SYNCHRONIZED:
2061 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2062 case MONO_WRAPPER_RUNTIME_INVOKE: {
2065 m = mono_marshal_method_from_wrapper (method);
2067 g_assert (m != method);
2068 encode_method_ref (acfg, m, p, &p);
2071 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2072 if (!strcmp (method->name, "ElementAddr")) {
2073 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2076 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2077 encode_value (info->rank, p, &p);
2078 encode_value (info->elem_size, p, &p);
2080 g_assert_not_reached ();
2084 g_assert_not_reached ();
2086 } else if (mono_method_signature (method)->is_inflated) {
2088 * This is a generic method, find the original token which referenced it and
2090 * Obtain the token from information recorded by the JIT.
2092 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2094 image_index = get_image_index (acfg, ji->image);
2095 g_assert (image_index < MAX_IMAGE_INDEX);
2098 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2099 encode_value (image_index, p, &p);
2100 encode_value (token, p, &p);
2102 MonoMethod *declaring;
2103 MonoGenericContext *context = mono_method_get_context (method);
2105 g_assert (method->is_inflated);
2106 declaring = ((MonoMethodInflated*)method)->declaring;
2109 * This might be a non-generic method of a generic instance, which
2110 * doesn't have a token since the reference is generated by the JIT
2111 * like Nullable:Box/Unbox, or by generic sharing.
2114 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2115 /* Encode the klass */
2116 encode_klass_ref (acfg, method->klass, p, &p);
2117 /* Encode the method */
2118 image_index = get_image_index (acfg, method->klass->image);
2119 g_assert (image_index < MAX_IMAGE_INDEX);
2120 g_assert (declaring->token);
2121 token = declaring->token;
2122 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2123 encode_value (image_index, p, &p);
2124 encode_value (token, p, &p);
2125 encode_generic_context (acfg, context, p, &p);
2127 } else if (token == 0) {
2128 /* This might be a method of a constructed type like int[,].Set */
2129 /* Obtain the token from information recorded by the JIT */
2130 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2132 image_index = get_image_index (acfg, ji->image);
2133 g_assert (image_index < MAX_IMAGE_INDEX);
2136 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2137 encode_value (image_index, p, &p);
2138 encode_value (token, p, &p);
2141 g_assert (method->klass->rank);
2143 /* Encode directly */
2144 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2145 encode_klass_ref (acfg, method->klass, p, &p);
2146 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2147 encode_value (0, p, &p);
2148 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2149 encode_value (1, p, &p);
2150 else if (!strcmp (method->name, "Get"))
2151 encode_value (2, p, &p);
2152 else if (!strcmp (method->name, "Address"))
2153 encode_value (3, p, &p);
2154 else if (!strcmp (method->name, "Set"))
2155 encode_value (4, p, &p);
2157 g_assert_not_reached ();
2160 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2161 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2167 compare_patches (gconstpointer a, gconstpointer b)
2171 i = (*(MonoJumpInfo**)a)->ip.i;
2172 j = (*(MonoJumpInfo**)b)->ip.i;
2183 static G_GNUC_UNUSED char*
2184 patch_to_string (MonoJumpInfo *patch_info)
2188 str = g_string_new ("");
2190 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2192 switch (patch_info->type) {
2193 case MONO_PATCH_INFO_VTABLE:
2194 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2199 g_string_append_printf (str, ")");
2200 return g_string_free (str, FALSE);
2206 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2209 static inline gboolean
2210 is_plt_patch (MonoJumpInfo *patch_info)
2212 switch (patch_info->type) {
2213 case MONO_PATCH_INFO_METHOD:
2214 case MONO_PATCH_INFO_INTERNAL_METHOD:
2215 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2216 case MONO_PATCH_INFO_ICALL_ADDR:
2217 case MONO_PATCH_INFO_CLASS_INIT:
2218 case MONO_PATCH_INFO_RGCTX_FETCH:
2219 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2220 case MONO_PATCH_INFO_MONITOR_ENTER:
2221 case MONO_PATCH_INFO_MONITOR_EXIT:
2222 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2232 * Return the symbol identifying the plt entry PLT_OFFSET.
2235 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2239 * The Apple linker reorganizes object files, so it doesn't like branches to local
2240 * labels, since those have no relocations.
2242 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2244 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2251 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2253 static MonoPltEntry*
2254 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2258 if (!is_plt_patch (patch_info))
2261 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2263 // FIXME: This breaks the calculation of final_got_size
2264 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2266 * Allocate a separate PLT slot for each such patch, since some plt
2267 * entries will refer to the method itself, and some will refer to the
2274 MonoJumpInfo *new_ji;
2276 g_assert (!acfg->final_got_size);
2278 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2280 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2281 res->plt_offset = acfg->plt_offset;
2283 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2284 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2286 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2288 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2290 acfg->plt_offset ++;
2299 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2300 * JI could be found if it exists, otherwise allocates a new one.
2303 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2307 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2309 return got_offset - 1;
2311 got_offset = acfg->got_offset;
2312 acfg->got_offset ++;
2314 if (acfg->final_got_size)
2315 g_assert (got_offset < acfg->final_got_size);
2317 acfg->stats.got_slots ++;
2318 acfg->stats.got_slot_types [ji->type] ++;
2320 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2321 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2322 g_ptr_array_add (acfg->got_patches, ji);
2327 /* Add a method to the list of methods which need to be emitted */
2329 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2332 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2333 g_ptr_array_add (acfg->methods, method);
2334 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2335 acfg->nmethods = acfg->methods->len + 1;
2338 if (method->wrapper_type || extra)
2339 g_ptr_array_add (acfg->extra_methods, method);
2343 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2345 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2353 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2357 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2361 index = acfg->method_index;
2362 add_method_with_index (acfg, method, index, extra);
2364 /* FIXME: Fix quadratic behavior */
2365 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2367 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2369 acfg->method_index ++;
2375 add_method (MonoAotCompile *acfg, MonoMethod *method)
2377 return add_method_full (acfg, method, FALSE, 0);
2381 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2383 add_method_full (acfg, method, TRUE, 0);
2387 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2389 add_method_full (acfg, method, TRUE, depth);
2393 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2395 MonoAotCompile *acfg = user_data;
2396 MonoJitICallInfo *callinfo = value;
2397 MonoMethod *wrapper;
2403 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2404 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2407 add_method (acfg, wrapper);
2411 get_runtime_invoke_sig (MonoMethodSignature *sig)
2413 MonoMethodBuilder *mb;
2416 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2417 m = mono_mb_create_method (mb, sig, 16);
2418 return mono_marshal_get_runtime_invoke (m, FALSE);
2422 can_marshal_struct (MonoClass *klass)
2424 MonoClassField *field;
2425 gboolean can_marshal = TRUE;
2426 gpointer iter = NULL;
2428 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2431 /* Only allow a few field types to avoid asserts in the marshalling code */
2432 while ((field = mono_class_get_fields (klass, &iter))) {
2433 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2436 switch (field->type->type) {
2441 case MONO_TYPE_BOOLEAN:
2444 case MONO_TYPE_CHAR:
2452 case MONO_TYPE_STRING:
2454 case MONO_TYPE_VALUETYPE:
2455 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2456 can_marshal = FALSE;
2459 can_marshal = FALSE;
2465 /* Its hard to compute whenever these can be marshalled or not */
2466 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2473 add_wrappers (MonoAotCompile *acfg)
2475 MonoMethod *method, *m;
2477 MonoMethodSignature *sig, *csig;
2481 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2482 * so there is only one wrapper of a given type, or inlining their contents into their
2487 * FIXME: This depends on the fact that different wrappers have different
2491 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2493 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2494 gboolean skip = FALSE;
2496 method = mono_get_method (acfg->image, token, NULL);
2498 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2499 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2500 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2503 if (method->is_generic || method->klass->generic_container)
2506 /* Skip methods which can not be handled by get_runtime_invoke () */
2507 sig = mono_method_signature (method);
2510 if ((sig->ret->type == MONO_TYPE_PTR) ||
2511 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2514 for (j = 0; j < sig->param_count; j++) {
2515 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2519 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2520 if (!method->klass->contextbound) {
2521 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2522 gboolean has_nullable = FALSE;
2524 for (j = 0; j < sig->param_count; j++) {
2525 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2526 has_nullable = TRUE;
2529 if (info && !has_nullable) {
2530 /* Supported by the dynamic runtime-invoke wrapper */
2538 //printf ("%s\n", mono_method_full_name (method, TRUE));
2539 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2543 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2544 #ifdef MONO_ARCH_HAVE_TLS_GET
2545 MonoMethodDesc *desc;
2546 MonoMethod *orig_method;
2550 /* Runtime invoke wrappers */
2552 /* void runtime-invoke () [.cctor] */
2553 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2554 csig->ret = &mono_defaults.void_class->byval_arg;
2555 add_method (acfg, get_runtime_invoke_sig (csig));
2557 /* void runtime-invoke () [Finalize] */
2558 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2560 csig->ret = &mono_defaults.void_class->byval_arg;
2561 add_method (acfg, get_runtime_invoke_sig (csig));
2563 /* void runtime-invoke (string) [exception ctor] */
2564 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2566 csig->ret = &mono_defaults.void_class->byval_arg;
2567 csig->params [0] = &mono_defaults.string_class->byval_arg;
2568 add_method (acfg, get_runtime_invoke_sig (csig));
2570 /* void runtime-invoke (string, string) [exception ctor] */
2571 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2573 csig->ret = &mono_defaults.void_class->byval_arg;
2574 csig->params [0] = &mono_defaults.string_class->byval_arg;
2575 csig->params [1] = &mono_defaults.string_class->byval_arg;
2576 add_method (acfg, get_runtime_invoke_sig (csig));
2578 /* string runtime-invoke () [Exception.ToString ()] */
2579 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2581 csig->ret = &mono_defaults.string_class->byval_arg;
2582 add_method (acfg, get_runtime_invoke_sig (csig));
2584 /* void runtime-invoke (string, Exception) [exception ctor] */
2585 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2587 csig->ret = &mono_defaults.void_class->byval_arg;
2588 csig->params [0] = &mono_defaults.string_class->byval_arg;
2589 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2590 add_method (acfg, get_runtime_invoke_sig (csig));
2592 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2593 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2595 csig->ret = &(mono_class_from_name (
2596 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2597 csig->params [0] = &mono_defaults.string_class->byval_arg;
2598 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2599 add_method (acfg, get_runtime_invoke_sig (csig));
2601 /* runtime-invoke used by finalizers */
2602 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2604 /* This is used by mono_runtime_capture_context () */
2605 method = mono_get_context_capture_method ();
2607 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2609 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2610 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2613 /* JIT icall wrappers */
2614 /* FIXME: locking */
2615 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2618 add_method (acfg, mono_marshal_get_stelemref ());
2620 #ifdef MONO_ARCH_HAVE_TLS_GET
2621 /* Managed Allocators */
2622 nallocators = mono_gc_get_managed_allocator_types ();
2623 for (i = 0; i < nallocators; ++i) {
2624 m = mono_gc_get_managed_allocator_by_type (i);
2626 add_method (acfg, m);
2629 /* Monitor Enter/Exit */
2630 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2631 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2632 g_assert (orig_method);
2633 mono_method_desc_free (desc);
2634 method = mono_monitor_get_fast_path (orig_method);
2636 add_method (acfg, method);
2638 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2639 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2640 g_assert (orig_method);
2641 mono_method_desc_free (desc);
2642 method = mono_monitor_get_fast_path (orig_method);
2644 add_method (acfg, method);
2647 /* Stelemref wrappers */
2648 /* There is only a constant number of these, iterating over all types should handle them all */
2649 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2652 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2653 klass = mono_class_get (acfg->image, token);
2655 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2660 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2661 * we use the original method instead at runtime.
2662 * Since full-aot doesn't support remoting, this is not a problem.
2665 /* remoting-invoke wrappers */
2666 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2667 MonoMethodSignature *sig;
2669 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2670 method = mono_get_method (acfg->image, token, NULL);
2672 sig = mono_method_signature (method);
2674 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2675 m = mono_marshal_get_remoting_invoke_with_check (method);
2677 add_method (acfg, m);
2682 /* delegate-invoke wrappers */
2683 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2686 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2687 klass = mono_class_get (acfg->image, token);
2689 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2690 method = mono_get_delegate_invoke (klass);
2692 m = mono_marshal_get_delegate_invoke (method, NULL);
2694 add_method (acfg, m);
2696 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2697 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2699 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2700 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2704 /* Synchronized wrappers */
2705 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2706 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2707 method = mono_get_method (acfg->image, token, NULL);
2709 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2710 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2713 /* pinvoke wrappers */
2714 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2716 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2718 method = mono_get_method (acfg->image, token, NULL);
2720 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2721 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2722 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2726 /* native-to-managed wrappers */
2727 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2729 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2730 MonoCustomAttrInfo *cattr;
2733 method = mono_get_method (acfg->image, token, NULL);
2736 * Only generate native-to-managed wrappers for methods which have an
2737 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2738 * name to avoid defining a new assembly to contain it.
2740 cattr = mono_custom_attrs_from_method (method);
2743 for (j = 0; j < cattr->num_attrs; ++j)
2744 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2746 if (j < cattr->num_attrs) {
2747 MonoCustomAttrEntry *e = &cattr->attrs [j];
2748 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2749 const char *p = (const char*)e->data;
2755 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2757 g_assert (sig->param_count == 1);
2758 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2761 * Decode the cattr manually since we can't create objects
2762 * during aot compilation.
2768 /* From load_cattr_value () in reflection.c */
2769 slen = mono_metadata_decode_value (p, &p);
2770 n = g_memdup (p, slen + 1);
2772 t = mono_reflection_type_from_name (n, acfg->image);
2776 klass = mono_class_from_mono_type (t);
2777 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2779 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2783 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2784 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2785 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2789 /* StructureToPtr/PtrToStructure wrappers */
2790 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2793 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2794 klass = mono_class_get (acfg->image, token);
2796 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2797 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2798 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2804 has_type_vars (MonoClass *klass)
2806 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2809 return has_type_vars (klass->element_class);
2810 if (klass->generic_class) {
2811 MonoGenericContext *context = &klass->generic_class->context;
2812 if (context->class_inst) {
2815 for (i = 0; i < context->class_inst->type_argc; ++i)
2816 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2824 method_has_type_vars (MonoMethod *method)
2826 if (has_type_vars (method->klass))
2829 if (method->is_inflated) {
2830 MonoGenericContext *context = mono_method_get_context (method);
2831 if (context->method_inst) {
2834 for (i = 0; i < context->method_inst->type_argc; ++i)
2835 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2842 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2845 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2847 /* This might lead to a huge code blowup so only do it if neccesary */
2848 if (!acfg->aot_opts.full_aot && !force)
2851 add_generic_class_with_depth (acfg, klass, 0);
2855 * add_generic_class:
2857 * Add all methods of a generic class.
2860 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2868 mono_class_init (klass);
2870 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2873 if (has_type_vars (klass))
2876 if (!klass->generic_class && !klass->rank)
2880 while ((method = mono_class_get_methods (klass, &iter))) {
2881 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2885 if (method->is_generic)
2890 * FIXME: Instances which are referenced by these methods are not added,
2891 * for example Array.Resize<int> for List<int>.Add ().
2893 add_extra_method_with_depth (acfg, method, depth + 1);
2896 if (klass->delegate) {
2897 method = mono_get_delegate_invoke (klass);
2899 method = mono_marshal_get_delegate_invoke (method, NULL);
2901 add_method (acfg, method);
2905 * For ICollection<T>, add instances of the helper methods
2906 * in Array, since a T[] could be cast to ICollection<T>.
2908 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2909 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2910 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2911 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2915 if (!strcmp (klass->name, "IEnumerator`1"))
2916 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2918 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2920 /* Add the T[]/InternalEnumerator class */
2921 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2925 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2926 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2930 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2931 add_generic_class (acfg, nclass, FALSE);
2935 while ((method = mono_class_get_methods (array_class, &iter))) {
2936 if (strstr (method->name, name_prefix)) {
2937 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2938 add_extra_method_with_depth (acfg, m, depth);
2942 g_free (name_prefix);
2945 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2946 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2947 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2948 MonoClass *icomparable, *gcomparer;
2949 MonoGenericContext ctx;
2950 MonoType *args [16];
2952 memset (&ctx, 0, sizeof (ctx));
2954 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2955 g_assert (icomparable);
2956 args [0] = &tclass->byval_arg;
2957 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2959 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2960 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2961 g_assert (gcomparer);
2962 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2966 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2967 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2968 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2969 MonoClass *iface, *gcomparer;
2970 MonoGenericContext ctx;
2971 MonoType *args [16];
2973 memset (&ctx, 0, sizeof (ctx));
2975 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2977 args [0] = &tclass->byval_arg;
2978 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2980 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2981 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2982 g_assert (gcomparer);
2983 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2989 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
2992 MonoGenericContext ctx;
2993 MonoType *args [16];
2995 memset (&ctx, 0, sizeof (ctx));
2997 for (i = 0; i < ninsts; ++i) {
2998 args [0] = insts [i];
2999 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3000 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3005 * add_generic_instances:
3007 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3010 add_generic_instances (MonoAotCompile *acfg)
3015 MonoMethodHeader *header;
3016 MonoMethodSignature *sig;
3017 MonoGenericContext *context;
3019 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3020 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3021 method = mono_get_method (acfg->image, token, NULL);
3026 if (method->klass->image != acfg->image)
3029 context = mono_method_get_context (method);
3031 if (context && ((context->class_inst && context->class_inst->is_open)))
3035 * For open methods, create an instantiation which can be passed to the JIT.
3036 * FIXME: Handle class_inst as well.
3038 if (context && context->method_inst && context->method_inst->is_open) {
3039 MonoGenericContext shared_context;
3040 MonoGenericInst *inst;
3041 MonoType **type_argv;
3043 MonoMethod *declaring_method;
3044 gboolean supported = TRUE;
3046 /* Check that the context doesn't contain open constructed types */
3047 if (context->class_inst) {
3048 inst = context->class_inst;
3049 for (i = 0; i < inst->type_argc; ++i) {
3050 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)
3052 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3056 if (context->method_inst) {
3057 inst = context->method_inst;
3058 for (i = 0; i < inst->type_argc; ++i) {
3059 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)
3061 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3069 memset (&shared_context, 0, sizeof (MonoGenericContext));
3071 inst = context->class_inst;
3073 type_argv = g_new0 (MonoType*, inst->type_argc);
3074 for (i = 0; i < inst->type_argc; ++i) {
3075 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)
3076 type_argv [i] = &mono_defaults.object_class->byval_arg;
3078 type_argv [i] = inst->type_argv [i];
3081 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3085 inst = context->method_inst;
3087 type_argv = g_new0 (MonoType*, inst->type_argc);
3088 for (i = 0; i < inst->type_argc; ++i) {
3089 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)
3090 type_argv [i] = &mono_defaults.object_class->byval_arg;
3092 type_argv [i] = inst->type_argv [i];
3095 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3099 if (method->is_generic || method->klass->generic_container)
3100 declaring_method = method;
3102 declaring_method = mono_method_get_declaring_generic_method (method);
3104 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3108 * If the method is fully sharable, it was already added in place of its
3109 * generic definition.
3111 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3115 * FIXME: Partially shared methods are not shared here, so we end up with
3116 * many identical methods.
3118 add_extra_method (acfg, method);
3121 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3124 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3126 klass = mono_class_get (acfg->image, token);
3127 if (!klass || klass->rank)
3130 add_generic_class (acfg, klass, FALSE);
3133 /* Add types of args/locals */
3134 for (i = 0; i < acfg->methods->len; ++i) {
3137 method = g_ptr_array_index (acfg->methods, i);
3139 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3141 sig = mono_method_signature (method);
3144 for (j = 0; j < sig->param_count; ++j)
3145 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3146 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3149 header = mono_method_get_header (method);
3152 for (j = 0; j < header->num_locals; ++j)
3153 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3154 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3158 if (acfg->image == mono_defaults.corlib) {
3160 MonoType *insts [256];
3163 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3164 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3165 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3166 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3167 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3168 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3169 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3170 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3171 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3172 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3173 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3174 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3176 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3177 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3179 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3180 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3182 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3184 /* Add instances of the array generic interfaces for primitive types */
3185 /* This will add instances of the InternalArray_ helper methods in Array too */
3186 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3188 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3189 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3191 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3192 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3194 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3197 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3198 * used for all instances of GetGenericValueImpl by the AOT runtime.
3201 MonoGenericContext ctx;
3202 MonoType *args [16];
3203 MonoMethod *get_method;
3204 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3206 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3209 memset (&ctx, 0, sizeof (ctx));
3210 args [0] = &mono_defaults.object_class->byval_arg;
3211 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3212 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3216 /* Same for CompareExchange<T> */
3218 MonoGenericContext ctx;
3219 MonoType *args [16];
3220 MonoMethod *cas_method;
3221 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3222 gpointer iter = NULL;
3224 while ((cas_method = mono_class_get_methods (interlocked_klass, &iter))) {
3225 if (!strcmp (cas_method->name, "CompareExchange") && cas_method->is_generic) {
3226 memset (&ctx, 0, sizeof (ctx));
3227 args [0] = &mono_defaults.object_class->byval_arg;
3228 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3229 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (cas_method, &ctx), TRUE, TRUE));
3237 * is_direct_callable:
3239 * Return whenever the method identified by JI is directly callable without
3240 * going through the PLT.
3243 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3245 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3246 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3248 gboolean direct_callable = TRUE;
3250 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3251 direct_callable = FALSE;
3252 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3253 // FIXME: Maybe call the wrapper directly ?
3254 direct_callable = FALSE;
3256 if (direct_callable)
3265 * emit_and_reloc_code:
3267 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3268 * is true, calls are made through the GOT too. This is used for emitting trampolines
3269 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3270 * since trampolines are needed to make PTL work.
3273 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3275 int i, pindex, start_index, method_index;
3277 MonoJumpInfo *patch_info;
3278 MonoMethodHeader *header;
3279 gboolean skip, direct_call;
3281 char direct_call_target [1024];
3284 header = mono_method_get_header (method);
3286 method_index = get_method_index (acfg, method);
3289 /* Collect and sort relocations */
3290 patches = g_ptr_array_new ();
3291 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3292 g_ptr_array_add (patches, patch_info);
3293 g_ptr_array_sort (patches, compare_patches);
3296 for (i = 0; i < code_len; i++) {
3298 for (pindex = start_index; pindex < patches->len; ++pindex) {
3299 patch_info = g_ptr_array_index (patches, pindex);
3300 if (patch_info->ip.i >= i)
3304 #ifdef MONO_ARCH_AOT_SUPPORTED
3306 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3307 start_index = pindex;
3309 switch (patch_info->type) {
3310 case MONO_PATCH_INFO_NONE:
3312 case MONO_PATCH_INFO_GOT_OFFSET: {
3315 arch_emit_got_offset (acfg, code + i, &code_size);
3318 patch_info->type = MONO_PATCH_INFO_NONE;
3323 * If this patch is a call, try emitting a direct call instead of
3324 * through a PLT entry. This is possible if the called method is in
3325 * the same assembly and requires no initialization.
3327 direct_call = FALSE;
3328 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3329 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3330 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3331 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3333 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3334 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3335 patch_info->type = MONO_PATCH_INFO_NONE;
3336 acfg->stats.direct_calls ++;
3339 acfg->stats.all_calls ++;
3342 if (!got_only && !direct_call) {
3343 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3345 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3347 sprintf (direct_call_target, "%s", plt_entry->symbol);
3349 /* Nullify the patch */
3350 patch_info->type = MONO_PATCH_INFO_NONE;
3351 plt_entry->jit_used = TRUE;
3358 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3363 got_slot = get_got_offset (acfg, patch_info);
3365 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3372 #endif /* MONO_ARCH_AOT_SUPPORTED */
3375 /* Find next patch */
3377 for (pindex = start_index; pindex < patches->len; ++pindex) {
3378 patch_info = g_ptr_array_index (patches, pindex);
3379 if (patch_info->ip.i >= i)
3383 /* Try to emit multiple bytes at once */
3384 if (pindex < patches->len && patch_info->ip.i > i) {
3385 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3386 i = patch_info->ip.i - 1;
3388 emit_bytes (acfg, code + i, 1);
3397 * Modify SYMBOL so it only includes characters permissible in symbols.
3400 sanitize_symbol (char *symbol)
3402 int i, len = strlen (symbol);
3404 for (i = 0; i < len; ++i)
3405 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3410 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3412 char *name1, *name2, *cached;
3413 int i, j, len, count;
3415 name1 = mono_method_full_name (method, TRUE);
3416 len = strlen (name1);
3417 name2 = malloc (strlen (prefix) + len + 16);
3418 memcpy (name2, prefix, strlen (prefix));
3419 j = strlen (prefix);
3420 for (i = 0; i < len; ++i) {
3421 if (isalnum (name1 [i])) {
3422 name2 [j ++] = name1 [i];
3423 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3425 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3428 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3437 while (g_hash_table_lookup (cache, name2)) {
3438 sprintf (name2 + j, "_%d", count);
3442 cached = g_strdup (name2);
3443 g_hash_table_insert (cache, cached, cached);
3449 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3454 char *debug_sym = NULL;
3456 int func_alignment = AOT_FUNC_ALIGNMENT;
3457 MonoMethodHeader *header;
3459 method = cfg->orig_method;
3460 code = cfg->native_code;
3461 header = cfg->header;
3463 method_index = get_method_index (acfg, method);
3465 /* Make the labels local */
3466 sprintf (symbol, "%s", cfg->asm_symbol);
3468 emit_section_change (acfg, ".text", 0);
3469 emit_alignment (acfg, func_alignment);
3470 emit_label (acfg, symbol);
3472 if (acfg->aot_opts.write_symbols) {
3474 * Write a C style symbol for every method, this has two uses:
3475 * - it works on platforms where the dwarf debugging info is not
3477 * - it allows the setting of breakpoints of aot-ed methods.
3479 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3481 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3482 if (acfg->need_no_dead_strip)
3483 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3484 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3485 emit_label (acfg, debug_sym);
3488 if (cfg->verbose_level > 0)
3489 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3491 acfg->stats.code_size += cfg->code_len;
3493 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3495 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3499 if (acfg->aot_opts.write_symbols) {
3500 emit_symbol_size (acfg, debug_sym, ".");
3504 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3505 emit_label (acfg, symbol);
3511 * Encode PATCH_INFO into its disk representation.
3514 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3518 switch (patch_info->type) {
3519 case MONO_PATCH_INFO_NONE:
3521 case MONO_PATCH_INFO_IMAGE:
3522 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3524 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3525 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3527 case MONO_PATCH_INFO_METHOD_REL:
3528 encode_value ((gint)patch_info->data.offset, p, &p);
3530 case MONO_PATCH_INFO_SWITCH: {
3531 gpointer *table = (gpointer *)patch_info->data.table->table;
3534 encode_value (patch_info->data.table->table_size, p, &p);
3535 for (k = 0; k < patch_info->data.table->table_size; k++)
3536 encode_value ((int)(gssize)table [k], p, &p);
3539 case MONO_PATCH_INFO_METHODCONST:
3540 case MONO_PATCH_INFO_METHOD:
3541 case MONO_PATCH_INFO_METHOD_JUMP:
3542 case MONO_PATCH_INFO_ICALL_ADDR:
3543 case MONO_PATCH_INFO_METHOD_RGCTX:
3544 encode_method_ref (acfg, patch_info->data.method, p, &p);
3546 case MONO_PATCH_INFO_INTERNAL_METHOD:
3547 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3548 guint32 len = strlen (patch_info->data.name);
3550 encode_value (len, p, &p);
3552 memcpy (p, patch_info->data.name, len);
3557 case MONO_PATCH_INFO_LDSTR: {
3558 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3559 guint32 token = patch_info->data.token->token;
3560 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3561 encode_value (image_index, p, &p);
3562 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3565 case MONO_PATCH_INFO_RVA:
3566 case MONO_PATCH_INFO_DECLSEC:
3567 case MONO_PATCH_INFO_LDTOKEN:
3568 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3569 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3570 encode_value (patch_info->data.token->token, p, &p);
3571 encode_value (patch_info->data.token->has_context, p, &p);
3572 if (patch_info->data.token->has_context)
3573 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3575 case MONO_PATCH_INFO_EXC_NAME: {
3576 MonoClass *ex_class;
3579 mono_class_from_name (mono_defaults.exception_class->image,
3580 "System", patch_info->data.target);
3581 g_assert (ex_class);
3582 encode_klass_ref (acfg, ex_class, p, &p);
3585 case MONO_PATCH_INFO_R4:
3586 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3588 case MONO_PATCH_INFO_R8:
3589 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3590 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3592 case MONO_PATCH_INFO_VTABLE:
3593 case MONO_PATCH_INFO_CLASS:
3594 case MONO_PATCH_INFO_IID:
3595 case MONO_PATCH_INFO_ADJUSTED_IID:
3596 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3598 case MONO_PATCH_INFO_CLASS_INIT:
3599 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3600 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3602 case MONO_PATCH_INFO_FIELD:
3603 case MONO_PATCH_INFO_SFLDA:
3604 encode_field_info (acfg, patch_info->data.field, p, &p);
3606 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3608 case MONO_PATCH_INFO_RGCTX_FETCH: {
3609 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3611 encode_method_ref (acfg, entry->method, p, &p);
3612 encode_value (entry->in_mrgctx, p, &p);
3613 encode_value (entry->info_type, p, &p);
3614 encode_value (entry->data->type, p, &p);
3615 encode_patch (acfg, entry->data, p, &p);
3618 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3619 case MONO_PATCH_INFO_MONITOR_ENTER:
3620 case MONO_PATCH_INFO_MONITOR_EXIT:
3621 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3623 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3624 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3625 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3628 g_warning ("unable to handle jump info %d", patch_info->type);
3629 g_assert_not_reached ();
3636 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3639 guint32 pindex, offset;
3640 MonoJumpInfo *patch_info;
3642 encode_value (n_patches, p, &p);
3644 for (pindex = 0; pindex < patches->len; ++pindex) {
3645 patch_info = g_ptr_array_index (patches, pindex);
3647 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3651 offset = get_got_offset (acfg, patch_info);
3652 encode_value (offset, p, &p);
3659 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3663 int pindex, buf_size, n_patches;
3666 MonoJumpInfo *patch_info;
3667 MonoMethodHeader *header;
3668 guint32 method_index;
3670 guint32 first_got_offset;
3672 method = cfg->orig_method;
3673 code = cfg->native_code;
3674 header = mono_method_get_header (method);
3676 method_index = get_method_index (acfg, method);
3678 /* Sort relocations */
3679 patches = g_ptr_array_new ();
3680 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3681 g_ptr_array_add (patches, patch_info);
3682 g_ptr_array_sort (patches, compare_patches);
3684 first_got_offset = acfg->cfgs [method_index]->got_offset;
3686 /**********************/
3687 /* Encode method info */
3688 /**********************/
3690 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3691 p = buf = g_malloc (buf_size);
3693 if (mono_class_get_cctor (method->klass))
3694 encode_klass_ref (acfg, method->klass, p, &p);
3696 /* Not needed when loading the method */
3697 encode_value (0, p, &p);
3700 if (cfg->opt & MONO_OPT_SHARED) {
3701 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3702 for (l = cfg->ldstr_list; l; l = l->next) {
3703 encode_value ((long)l->data, p, &p);
3707 /* Used only in shared mode */
3708 g_assert (!cfg->ldstr_list);
3711 for (pindex = 0; pindex < patches->len; ++pindex) {
3712 patch_info = g_ptr_array_index (patches, pindex);
3714 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3715 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3716 patch_info->type = MONO_PATCH_INFO_NONE;
3721 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3722 /* Stored in a GOT slot initialized at module load time */
3723 patch_info->type = MONO_PATCH_INFO_NONE;
3727 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3728 /* Stored in a GOT slot initialized at module load time */
3729 patch_info->type = MONO_PATCH_INFO_NONE;
3733 if (is_plt_patch (patch_info)) {
3734 /* Calls are made through the PLT */
3735 patch_info->type = MONO_PATCH_INFO_NONE;
3743 g_assert (cfg->has_got_slots);
3745 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3747 acfg->stats.info_size += p - buf;
3749 g_assert (p - buf < buf_size);
3751 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3756 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3758 guint32 cache_index;
3761 /* Reuse the unwind module to canonize and store unwind info entries */
3762 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3764 /* Use +/- 1 to distinguish 0s from missing entries */
3765 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3773 * It would be easier to use assembler symbols, but the caller needs an
3776 offset = acfg->unwind_info_offset;
3777 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3778 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3781 encode_value (encoded_len, p, &p);
3783 acfg->unwind_info_offset += encoded_len + (p - buf);
3789 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3792 int i, k, buf_size, method_index;
3793 guint32 debug_info_size;
3795 MonoMethodHeader *header;
3796 guint8 *p, *buf, *debug_info;
3797 MonoJitInfo *jinfo = cfg->jit_info;
3799 gboolean use_unwind_ops = FALSE;
3800 MonoSeqPointInfo *seq_points;
3802 method = cfg->orig_method;
3803 code = cfg->native_code;
3804 header = cfg->header;
3806 method_index = get_method_index (acfg, method);
3808 if (!acfg->aot_opts.nodebug) {
3809 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3812 debug_info_size = 0;
3815 seq_points = cfg->seq_point_info;
3817 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3818 p = buf = g_malloc (buf_size);
3820 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3821 use_unwind_ops = cfg->unwind_ops != NULL;
3824 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);
3826 encode_value (flags, p, &p);
3828 if (use_unwind_ops) {
3829 guint32 encoded_len;
3833 * This is a duplicate of the data in the .debug_frame section, but that
3834 * section cannot be accessed using the dl interface.
3836 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3837 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3840 encode_value (jinfo->used_regs, p, &p);
3843 /*Encode the number of holes before the number of clauses to make decoding easier*/
3844 if (jinfo->has_try_block_holes) {
3845 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3846 encode_value (table->num_holes, p, &p);
3849 /* Exception table */
3850 if (cfg->compile_llvm) {
3852 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3853 * since the information is only available to llc. Instead, we let llc save the data
3854 * into the LSDA, and read it from there at runtime.
3856 /* The assembly might be CIL stripped so emit the data ourselves */
3857 if (header->num_clauses)
3858 encode_value (header->num_clauses, p, &p);
3860 for (k = 0; k < header->num_clauses; ++k) {
3861 MonoExceptionClause *clause;
3863 clause = &header->clauses [k];
3865 encode_value (clause->flags, p, &p);
3866 if (clause->data.catch_class) {
3867 encode_value (1, p, &p);
3868 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3870 encode_value (0, p, &p);
3873 /* Emit a list of nesting clauses */
3874 for (i = 0; i < header->num_clauses; ++i) {
3876 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3878 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3880 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3881 encode_value (i, p, &p);
3883 encode_value (-1, p, &p);
3886 if (jinfo->num_clauses)
3887 encode_value (jinfo->num_clauses, p, &p);
3889 for (k = 0; k < jinfo->num_clauses; ++k) {
3890 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3892 encode_value (ei->flags, p, &p);
3893 encode_value (ei->exvar_offset, p, &p);
3895 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3896 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3898 if (ei->data.catch_class) {
3899 encode_value (1, p, &p);
3900 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3902 encode_value (0, p, &p);
3906 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3907 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3908 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3912 if (jinfo->has_generic_jit_info) {
3913 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3915 if (!cfg->compile_llvm) {
3916 encode_value (gi->has_this ? 1 : 0, p, &p);
3917 encode_value (gi->this_reg, p, &p);
3918 encode_value (gi->this_offset, p, &p);
3922 * Need to encode jinfo->method too, since it is not equal to 'method'
3923 * when using generic sharing.
3925 encode_method_ref (acfg, jinfo->method, p, &p);
3928 if (jinfo->has_try_block_holes) {
3929 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3930 for (i = 0; i < table->num_holes; ++i) {
3931 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3932 encode_value (hole->clause, p, &p);
3933 encode_value (hole->length, p, &p);
3934 encode_value (hole->offset, p, &p);
3939 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3941 encode_value (seq_points->len, p, &p);
3942 last_il_offset = last_native_offset = 0;
3943 for (i = 0; i < seq_points->len; ++i) {
3944 SeqPoint *sp = &seq_points->seq_points [i];
3945 il_offset = sp->il_offset;
3946 native_offset = sp->native_offset;
3947 encode_value (il_offset - last_il_offset, p, &p);
3948 encode_value (native_offset - last_native_offset, p, &p);
3949 last_il_offset = il_offset;
3950 last_native_offset = native_offset;
3952 encode_value (sp->next_len, p, &p);
3953 for (j = 0; j < sp->next_len; ++j)
3954 encode_value (sp->next [j], p, &p);
3958 g_assert (debug_info_size < buf_size);
3960 encode_value (debug_info_size, p, &p);
3961 if (debug_info_size) {
3962 memcpy (p, debug_info, debug_info_size);
3963 p += debug_info_size;
3964 g_free (debug_info);
3969 encode_value (cfg->gc_map_size, p, &p);
3970 /* The GC map requires 4 bytes of alignment */
3971 while ((gsize)p % 4)
3973 memcpy (p, cfg->gc_map, cfg->gc_map_size);
3974 p += cfg->gc_map_size;
3977 acfg->stats.ex_info_size += p - buf;
3979 g_assert (p - buf < buf_size);
3982 /* The GC Map requires 4 byte alignment */
3983 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
3988 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3990 MonoClass *klass = mono_class_get (acfg->image, token);
3992 int i, buf_size, res;
3993 gboolean no_special_static, cant_encode;
3994 gpointer iter = NULL;
3999 p = buf = g_malloc (buf_size);
4001 /* Mark as unusable */
4002 encode_value (-1, p, &p);
4004 res = add_to_blob (acfg, buf, p - buf);
4010 buf_size = 10240 + (klass->vtable_size * 16);
4011 p = buf = g_malloc (buf_size);
4015 mono_class_init (klass);
4017 mono_class_get_nested_types (klass, &iter);
4018 g_assert (klass->nested_classes_inited);
4020 mono_class_setup_vtable (klass);
4023 * Emit all the information which is required for creating vtables so
4024 * the runtime does not need to create the MonoMethod structures which
4025 * take up a lot of space.
4028 no_special_static = !mono_class_has_special_static_fields (klass);
4030 /* Check whenever we have enough info to encode the vtable */
4031 cant_encode = FALSE;
4032 for (i = 0; i < klass->vtable_size; ++i) {
4033 MonoMethod *cm = klass->vtable [i];
4035 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4039 if (klass->generic_container || cant_encode) {
4040 encode_value (-1, p, &p);
4042 encode_value (klass->vtable_size, p, &p);
4043 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);
4044 if (klass->has_cctor)
4045 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4046 if (klass->has_finalize)
4047 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4049 encode_value (klass->instance_size, p, &p);
4050 encode_value (mono_class_data_size (klass), p, &p);
4051 encode_value (klass->packing_size, p, &p);
4052 encode_value (klass->min_align, p, &p);
4054 for (i = 0; i < klass->vtable_size; ++i) {
4055 MonoMethod *cm = klass->vtable [i];
4058 encode_method_ref (acfg, cm, p, &p);
4060 encode_value (0, p, &p);
4064 acfg->stats.class_info_size += p - buf;
4066 g_assert (p - buf < buf_size);
4067 res = add_to_blob (acfg, buf, p - buf);
4074 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4076 char *debug_sym = NULL;
4079 case MONO_PATCH_INFO_METHOD:
4080 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4082 case MONO_PATCH_INFO_INTERNAL_METHOD:
4083 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4085 case MONO_PATCH_INFO_CLASS_INIT:
4086 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4087 sanitize_symbol (debug_sym);
4089 case MONO_PATCH_INFO_RGCTX_FETCH:
4090 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4092 case MONO_PATCH_INFO_ICALL_ADDR: {
4093 char *s = get_debug_sym (ji->data.method, "", cache);
4095 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4099 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4100 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4102 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4103 debug_sym = g_strdup_printf ("plt__generic_class_init");
4113 * Calls made from AOTed code are routed through a table of jumps similar to the
4114 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4115 * control to the AOT runtime through a trampoline.
4118 emit_plt (MonoAotCompile *acfg)
4124 cache = g_hash_table_new (g_str_hash, g_str_equal);
4127 sprintf (symbol, "plt");
4129 emit_section_change (acfg, ".text", 0);
4130 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4131 emit_label (acfg, symbol);
4132 emit_label (acfg, acfg->plt_symbol);
4134 for (i = 0; i < acfg->plt_offset; ++i) {
4135 char *debug_sym = NULL;
4136 MonoPltEntry *plt_entry = NULL;
4141 * The first plt entry is unused.
4145 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4150 * If the target is directly callable, alias the plt symbol to point to
4152 * FIXME: Use this to simplify emit_and_reloc_code ().
4153 * FIXME: Avoid the got slot.
4154 * FIXME: Add support to the binary writer.
4156 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4157 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4159 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4160 /* LLVM calls the PLT entries using bl, so emit a stub */
4161 fprintf (acfg->fp, "\n.thumb_func\n");
4162 emit_label (acfg, plt_entry->llvm_symbol);
4163 fprintf (acfg->fp, "bx pc\n");
4164 fprintf (acfg->fp, "nop\n");
4165 fprintf (acfg->fp, ".arm\n");
4166 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4168 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4174 if (acfg->aot_opts.write_symbols)
4175 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4176 debug_sym = plt_entry->debug_sym;
4178 if (acfg->thumb_mixed && !plt_entry->jit_used)
4179 /* Emit only a thumb version */
4182 if (!acfg->thumb_mixed)
4183 emit_label (acfg, plt_entry->llvm_symbol);
4186 if (acfg->need_no_dead_strip)
4187 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4188 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4189 emit_label (acfg, debug_sym);
4192 emit_label (acfg, plt_entry->symbol);
4194 arch_emit_plt_entry (acfg, i);
4197 emit_symbol_size (acfg, debug_sym, ".");
4200 if (acfg->thumb_mixed) {
4201 /* Make sure the ARM symbols don't alias the thumb ones */
4202 emit_zero_bytes (acfg, 16);
4205 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4208 for (i = 0; i < acfg->plt_offset; ++i) {
4209 char *debug_sym = NULL;
4210 MonoPltEntry *plt_entry = NULL;
4216 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4219 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4222 /* Skip plt entries not actually called by LLVM code */
4223 if (!plt_entry->llvm_used)
4226 if (acfg->aot_opts.write_symbols) {
4227 if (plt_entry->debug_sym)
4228 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4232 #if defined(__APPLE__)
4233 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4234 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4236 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4237 emit_label (acfg, debug_sym);
4239 fprintf (acfg->fp, "\n.thumb_func\n");
4241 emit_label (acfg, plt_entry->llvm_symbol);
4243 arch_emit_llvm_plt_entry (acfg, i);
4246 emit_symbol_size (acfg, debug_sym, ".");
4252 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4254 sprintf (symbol, "plt_end");
4255 emit_label (acfg, symbol);
4257 g_hash_table_destroy (cache);
4260 static G_GNUC_UNUSED void
4261 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4263 char start_symbol [256];
4265 guint32 buf_size, info_offset;
4266 MonoJumpInfo *patch_info;
4277 code_size = info->code_size;
4279 unwind_ops = info->unwind_ops;
4281 #ifdef __native_client_codegen__
4282 mono_nacl_fix_patches (code, ji);
4287 sprintf (start_symbol, "%s", name);
4289 emit_section_change (acfg, ".text", 0);
4290 emit_global (acfg, start_symbol, TRUE);
4291 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4292 emit_label (acfg, start_symbol);
4294 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4295 emit_label (acfg, symbol);
4298 * The code should access everything through the GOT, so we pass
4301 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4303 emit_symbol_size (acfg, start_symbol, ".");
4307 /* Sort relocations */
4308 patches = g_ptr_array_new ();
4309 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4310 if (patch_info->type != MONO_PATCH_INFO_NONE)
4311 g_ptr_array_add (patches, patch_info);
4312 g_ptr_array_sort (patches, compare_patches);
4314 buf_size = patches->len * 128 + 128;
4315 buf = g_malloc (buf_size);
4318 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4319 g_assert (p - buf < buf_size);
4321 sprintf (symbol, "%s_p", name);
4323 info_offset = add_to_blob (acfg, buf, p - buf);
4325 emit_section_change (acfg, RODATA_SECT, 0);
4326 emit_global (acfg, symbol, FALSE);
4327 emit_label (acfg, symbol);
4329 emit_int32 (acfg, info_offset);
4331 /* Emit debug info */
4335 sprintf (symbol, "%s", name);
4336 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4339 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4344 emit_trampolines (MonoAotCompile *acfg)
4347 int i, tramp_got_offset;
4348 MonoAotTrampoline ntype;
4349 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4354 if (!acfg->aot_opts.full_aot)
4357 g_assert (acfg->image->assembly);
4359 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4360 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4361 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4362 MonoTrampInfo *info;
4365 * Emit the generic trampolines.
4367 * We could save some code by treating the generic trampolines as a wrapper
4368 * method, but that approach has its own complexities, so we choose the simpler
4371 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4372 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4373 emit_trampoline (acfg, acfg->got_offset, info);
4376 mono_arch_get_nullified_class_init_trampoline (&info);
4377 emit_trampoline (acfg, acfg->got_offset, info);
4378 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4379 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4380 emit_trampoline (acfg, acfg->got_offset, info);
4381 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4382 emit_trampoline (acfg, acfg->got_offset, info);
4385 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4386 emit_trampoline (acfg, acfg->got_offset, info);
4388 /* Emit the exception related code pieces */
4389 code = mono_arch_get_restore_context (&info, TRUE);
4390 emit_trampoline (acfg, acfg->got_offset, info);
4391 code = mono_arch_get_call_filter (&info, TRUE);
4392 emit_trampoline (acfg, acfg->got_offset, info);
4393 code = mono_arch_get_throw_exception (&info, TRUE);
4394 emit_trampoline (acfg, acfg->got_offset, info);
4395 code = mono_arch_get_rethrow_exception (&info, TRUE);
4396 emit_trampoline (acfg, acfg->got_offset, info);
4397 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4398 emit_trampoline (acfg, acfg->got_offset, info);
4400 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4402 GSList *l = mono_arch_get_trampolines (TRUE);
4405 MonoTrampInfo *info = l->data;
4407 emit_trampoline (acfg, acfg->got_offset, info);
4413 for (i = 0; i < 128; ++i) {
4416 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4417 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4418 emit_trampoline (acfg, acfg->got_offset, info);
4420 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4421 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4422 emit_trampoline (acfg, acfg->got_offset, info);
4428 /* delegate_invoke_impl trampolines */
4429 l = mono_arch_get_delegate_invoke_impls ();
4431 MonoTrampInfo *info = l->data;
4433 emit_trampoline (acfg, acfg->got_offset, info);
4438 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4440 /* Emit trampolines which are numerous */
4443 * These include the following:
4444 * - specific trampolines
4445 * - static rgctx invoke trampolines
4447 * These trampolines have the same code, they are parameterized by GOT
4449 * They are defined in this file, in the arch_... routines instead of
4450 * in tramp-<ARCH>.c, since it is easier to do it this way.
4454 * When running in aot-only mode, we can't create specific trampolines at
4455 * runtime, so we create a few, and save them in the AOT file.
4456 * Normal trampolines embed their argument as a literal inside the
4457 * trampoline code, we can't do that here, so instead we embed an offset
4458 * which needs to be added to the trampoline address to get the address of
4459 * the GOT slot which contains the argument value.
4460 * The generated trampolines jump to the generic trampolines using another
4461 * GOT slot, which will be setup by the AOT loader to point to the
4462 * generic trampoline code of the given type.
4466 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4470 emit_section_change (acfg, ".text", 0);
4472 tramp_got_offset = acfg->got_offset;
4474 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4476 case MONO_AOT_TRAMP_SPECIFIC:
4477 sprintf (symbol, "specific_trampolines");
4479 case MONO_AOT_TRAMP_STATIC_RGCTX:
4480 sprintf (symbol, "static_rgctx_trampolines");
4482 case MONO_AOT_TRAMP_IMT_THUNK:
4483 sprintf (symbol, "imt_thunks");
4486 g_assert_not_reached ();
4489 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4490 emit_label (acfg, symbol);
4492 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4494 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4498 case MONO_AOT_TRAMP_SPECIFIC:
4499 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4500 tramp_got_offset += 2;
4502 case MONO_AOT_TRAMP_STATIC_RGCTX:
4503 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4504 tramp_got_offset += 2;
4506 case MONO_AOT_TRAMP_IMT_THUNK:
4507 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4508 tramp_got_offset += 1;
4511 g_assert_not_reached ();
4513 #ifdef __native_client_codegen__
4514 /* align to avoid 32-byte boundary crossings */
4515 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4518 if (!acfg->trampoline_size [ntype]) {
4519 g_assert (tramp_size);
4520 acfg->trampoline_size [ntype] = tramp_size;
4525 /* Reserve some entries at the end of the GOT for our use */
4526 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4529 acfg->got_offset += acfg->num_trampoline_got_entries;
4533 str_begins_with (const char *str1, const char *str2)
4535 int len = strlen (str2);
4536 return strncmp (str1, str2, len) == 0;
4540 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4542 gchar **args, **ptr;
4544 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4545 for (ptr = args; ptr && *ptr; ptr ++) {
4546 const char *arg = *ptr;
4548 if (str_begins_with (arg, "outfile=")) {
4549 opts->outfile = g_strdup (arg + strlen ("outfile="));
4550 } else if (str_begins_with (arg, "save-temps")) {
4551 opts->save_temps = TRUE;
4552 } else if (str_begins_with (arg, "keep-temps")) {
4553 opts->save_temps = TRUE;
4554 } else if (str_begins_with (arg, "write-symbols")) {
4555 opts->write_symbols = TRUE;
4556 } else if (str_begins_with (arg, "no-write-symbols")) {
4557 opts->write_symbols = FALSE;
4558 } else if (str_begins_with (arg, "metadata-only")) {
4559 opts->metadata_only = TRUE;
4560 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4561 opts->bind_to_runtime_version = TRUE;
4562 } else if (str_begins_with (arg, "full")) {
4563 opts->full_aot = TRUE;
4564 } else if (str_begins_with (arg, "threads=")) {
4565 opts->nthreads = atoi (arg + strlen ("threads="));
4566 } else if (str_begins_with (arg, "static")) {
4567 opts->static_link = TRUE;
4568 opts->no_dlsym = TRUE;
4569 } else if (str_begins_with (arg, "asmonly")) {
4570 opts->asm_only = TRUE;
4571 } else if (str_begins_with (arg, "asmwriter")) {
4572 opts->asm_writer = TRUE;
4573 } else if (str_begins_with (arg, "nodebug")) {
4574 opts->nodebug = TRUE;
4575 } else if (str_begins_with (arg, "ntrampolines=")) {
4576 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4577 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4578 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4579 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4580 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4581 } else if (str_begins_with (arg, "autoreg")) {
4582 opts->autoreg = TRUE;
4583 } else if (str_begins_with (arg, "tool-prefix=")) {
4584 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4585 } else if (str_begins_with (arg, "soft-debug")) {
4586 opts->soft_debug = TRUE;
4587 } else if (str_begins_with (arg, "print-skipped")) {
4588 opts->print_skipped_methods = TRUE;
4589 } else if (str_begins_with (arg, "stats")) {
4591 } else if (str_begins_with (arg, "mtriple=")) {
4592 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4593 } else if (str_begins_with (arg, "llvm-path=")) {
4594 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
4595 } else if (str_begins_with (arg, "info")) {
4596 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
4598 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
4599 printf ("Supported options for --aot:\n");
4600 printf (" outfile=\n");
4601 printf (" save-temps\n");
4602 printf (" keep-temps\n");
4603 printf (" write-symbols\n");
4604 printf (" metadata-only\n");
4605 printf (" bind-to-runtime-version\n");
4607 printf (" threads=\n");
4608 printf (" static\n");
4609 printf (" asmonly\n");
4610 printf (" asmwriter\n");
4611 printf (" nodebug\n");
4612 printf (" ntrampolines=\n");
4613 printf (" nrgctx-trampolines=\n");
4614 printf (" nimt-trampolines=\n");
4615 printf (" autoreg\n");
4616 printf (" tool-prefix=\n");
4617 printf (" soft-debug\n");
4618 printf (" print-skipped\n");
4619 printf (" stats\n");
4621 printf (" help/?\n");
4624 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4633 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4635 MonoMethod *method = (MonoMethod*)key;
4636 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4637 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4638 MonoAotCompile *acfg = user_data;
4640 new_ji->image = ji->image;
4641 new_ji->token = ji->token;
4642 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4646 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4648 if (klass->type_token)
4650 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4653 return can_encode_class (acfg, klass->element_class);
4658 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4660 switch (patch_info->type) {
4661 case MONO_PATCH_INFO_METHOD:
4662 case MONO_PATCH_INFO_METHODCONST: {
4663 MonoMethod *method = patch_info->data.method;
4665 if (method->wrapper_type) {
4666 switch (method->wrapper_type) {
4667 case MONO_WRAPPER_NONE:
4668 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4669 case MONO_WRAPPER_XDOMAIN_INVOKE:
4670 case MONO_WRAPPER_STFLD:
4671 case MONO_WRAPPER_LDFLD:
4672 case MONO_WRAPPER_LDFLDA:
4673 case MONO_WRAPPER_LDFLD_REMOTE:
4674 case MONO_WRAPPER_STFLD_REMOTE:
4675 case MONO_WRAPPER_STELEMREF:
4676 case MONO_WRAPPER_ISINST:
4677 case MONO_WRAPPER_PROXY_ISINST:
4678 case MONO_WRAPPER_ALLOC:
4679 case MONO_WRAPPER_REMOTING_INVOKE:
4680 case MONO_WRAPPER_UNKNOWN:
4681 case MONO_WRAPPER_WRITE_BARRIER:
4683 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4684 if (!strcmp (method->name, "ElementAddr"))
4689 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4693 if (!method->token) {
4694 /* The method is part of a constructed type like Int[,].Set (). */
4695 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4696 if (method->klass->rank)
4704 case MONO_PATCH_INFO_VTABLE:
4705 case MONO_PATCH_INFO_CLASS_INIT:
4706 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4707 case MONO_PATCH_INFO_CLASS:
4708 case MONO_PATCH_INFO_IID:
4709 case MONO_PATCH_INFO_ADJUSTED_IID:
4710 if (!can_encode_class (acfg, patch_info->data.klass)) {
4711 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4715 case MONO_PATCH_INFO_RGCTX_FETCH: {
4716 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4718 if (!can_encode_patch (acfg, entry->data))
4732 * AOT compile a given method.
4733 * This function might be called by multiple threads, so it must be thread-safe.
4736 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4739 MonoJumpInfo *patch_info;
4742 MonoMethod *wrapped;
4744 if (acfg->aot_opts.metadata_only)
4747 mono_acfg_lock (acfg);
4748 index = get_method_index (acfg, method);
4749 mono_acfg_unlock (acfg);
4751 /* fixme: maybe we can also precompile wrapper methods */
4752 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4753 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4754 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4755 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4759 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4762 wrapped = mono_marshal_method_from_wrapper (method);
4763 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4764 // FIXME: The wrapper should be generic too, but it is not
4767 InterlockedIncrement (&acfg->stats.mcount);
4770 if (method->is_generic || method->klass->generic_container) {
4771 InterlockedIncrement (&acfg->stats.genericcount);
4776 //acfg->aot_opts.print_skipped_methods = TRUE;
4779 * Since these methods are the only ones which are compiled with
4780 * AOT support, and they are not used by runtime startup/shutdown code,
4781 * the runtime will not see AOT methods during AOT compilation,so it
4782 * does not need to support them by creating a fake GOT etc.
4784 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4785 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4786 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4787 InterlockedIncrement (&acfg->stats.genericcount);
4790 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4791 /* Let the exception happen at runtime */
4795 if (cfg->disable_aot) {
4796 if (acfg->aot_opts.print_skipped_methods)
4797 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4798 InterlockedIncrement (&acfg->stats.ocount);
4799 mono_destroy_compile (cfg);
4803 /* Nullify patches which need no aot processing */
4804 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4805 switch (patch_info->type) {
4806 case MONO_PATCH_INFO_LABEL:
4807 case MONO_PATCH_INFO_BB:
4808 patch_info->type = MONO_PATCH_INFO_NONE;
4815 /* Collect method->token associations from the cfg */
4816 mono_acfg_lock (acfg);
4817 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4818 mono_acfg_unlock (acfg);
4821 * Check for absolute addresses.
4824 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4825 switch (patch_info->type) {
4826 case MONO_PATCH_INFO_ABS:
4827 /* unable to handle this */
4836 if (acfg->aot_opts.print_skipped_methods)
4837 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4838 InterlockedIncrement (&acfg->stats.abscount);
4839 mono_destroy_compile (cfg);
4843 /* Lock for the rest of the code */
4844 mono_acfg_lock (acfg);
4847 * Check for methods/klasses we can't encode.
4850 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4851 if (!can_encode_patch (acfg, patch_info))
4856 if (acfg->aot_opts.print_skipped_methods)
4857 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4858 acfg->stats.ocount++;
4859 mono_destroy_compile (cfg);
4860 mono_acfg_unlock (acfg);
4864 /* Adds generic instances referenced by this method */
4866 * The depth is used to avoid infinite loops when generic virtual recursion is
4869 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4871 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4872 switch (patch_info->type) {
4873 case MONO_PATCH_INFO_METHOD: {
4874 MonoMethod *m = patch_info->data.method;
4875 if (m->is_inflated) {
4876 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4877 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4878 !method_has_type_vars (m)) {
4879 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4880 if (acfg->aot_opts.full_aot)
4881 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4883 add_extra_method_with_depth (acfg, m, depth + 1);
4886 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4888 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4889 add_extra_method_with_depth (acfg, m, depth + 1);
4892 case MONO_PATCH_INFO_VTABLE: {
4893 MonoClass *klass = patch_info->data.klass;
4895 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4896 add_generic_class_with_depth (acfg, klass, depth + 5);
4905 /* Determine whenever the method has GOT slots */
4906 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4907 switch (patch_info->type) {
4908 case MONO_PATCH_INFO_GOT_OFFSET:
4909 case MONO_PATCH_INFO_NONE:
4910 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4912 case MONO_PATCH_INFO_IMAGE:
4913 /* The assembly is stored in GOT slot 0 */
4914 if (patch_info->data.image != acfg->image)
4915 cfg->has_got_slots = TRUE;
4918 if (!is_plt_patch (patch_info))
4919 cfg->has_got_slots = TRUE;
4924 if (!cfg->has_got_slots)
4925 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4928 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4930 /* Make a copy of the patch info which is in the mempool */
4932 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4934 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4935 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4938 patches = new_patch_info;
4940 patches_end->next = new_patch_info;
4941 patches_end = new_patch_info;
4943 cfg->patch_info = patches;
4945 /* Make a copy of the unwind info */
4947 GSList *l, *unwind_ops;
4951 for (l = cfg->unwind_ops; l; l = l->next) {
4952 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4953 memcpy (op, l->data, sizeof (MonoUnwindOp));
4954 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4956 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4958 /* Make a copy of the argument/local info */
4960 MonoInst **args, **locals;
4961 MonoMethodSignature *sig;
4962 MonoMethodHeader *header;
4965 sig = mono_method_signature (method);
4966 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4967 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4968 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4969 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4973 header = mono_method_get_header (method);
4974 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4975 for (i = 0; i < header->num_locals; ++i) {
4976 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4977 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4979 cfg->locals = locals;
4982 /* Free some fields used by cfg to conserve memory */
4983 mono_mempool_destroy (cfg->mempool);
4984 cfg->mempool = NULL;
4985 g_free (cfg->varinfo);
4986 cfg->varinfo = NULL;
4990 mono_regstate_free (cfg->rs);
4994 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4996 while (index >= acfg->cfgs_size) {
4997 MonoCompile **new_cfgs;
5000 new_size = acfg->cfgs_size * 2;
5001 new_cfgs = g_new0 (MonoCompile*, new_size);
5002 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5003 g_free (acfg->cfgs);
5004 acfg->cfgs = new_cfgs;
5005 acfg->cfgs_size = new_size;
5007 acfg->cfgs [index] = cfg;
5009 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5012 if (cfg->orig_method->wrapper_type)
5013 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5016 mono_acfg_unlock (acfg);
5018 InterlockedIncrement (&acfg->stats.ccount);
5022 compile_thread_main (gpointer *user_data)
5024 MonoDomain *domain = user_data [0];
5025 MonoAotCompile *acfg = user_data [1];
5026 GPtrArray *methods = user_data [2];
5029 mono_thread_attach (domain);
5031 for (i = 0; i < methods->len; ++i)
5032 compile_method (acfg, g_ptr_array_index (methods, i));
5036 load_profile_files (MonoAotCompile *acfg)
5040 int file_index, res, method_index, i;
5047 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5049 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5054 infile = fopen (tmp, "r");
5057 printf ("Using profile data file '%s'\n", tmp);
5062 res = fscanf (infile, "%32s\n", ver);
5063 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5064 printf ("Profile file has wrong version or invalid.\n");
5071 MonoMethodDesc *desc;
5074 if (fgets (name, 1023, infile) == NULL)
5077 /* Kill the newline */
5078 if (strlen (name) > 0)
5079 name [strlen (name) - 1] = '\0';
5081 desc = mono_method_desc_new (name, TRUE);
5083 method = mono_method_desc_search_in_image (desc, acfg->image);
5085 if (method && mono_method_get_token (method)) {
5086 token = mono_method_get_token (method);
5087 method_index = mono_metadata_token_index (token) - 1;
5089 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
5090 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
5093 //printf ("No method found matching '%s'.\n", name);
5099 /* Add missing methods */
5101 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
5102 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
5103 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
5105 unordered = g_list_reverse (unordered);
5106 if (acfg->method_order)
5107 g_list_last (acfg->method_order)->next = unordered;
5109 acfg->method_order = unordered;
5112 /* Used by the LLVM backend */
5114 mono_aot_get_got_offset (MonoJumpInfo *ji)
5116 return get_got_offset (llvm_acfg, ji);
5120 mono_aot_get_method_name (MonoCompile *cfg)
5122 if (llvm_acfg->aot_opts.static_link)
5123 /* Include the assembly name too to avoid duplicate symbol errors */
5124 return g_strdup_printf ("%s_%s", llvm_acfg->image->assembly->aname.name, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5126 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5130 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5132 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5133 MonoPltEntry *plt_entry;
5136 ji->data.target = data;
5138 if (!can_encode_patch (llvm_acfg, ji))
5141 plt_entry = get_plt_entry (llvm_acfg, ji);
5142 plt_entry->llvm_used = TRUE;
5144 #if defined(__APPLE__)
5145 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5147 return g_strdup_printf (plt_entry->llvm_symbol);
5152 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5156 mono_acfg_lock (llvm_acfg);
5157 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5158 mono_acfg_unlock (llvm_acfg);
5168 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5172 emit_llvm_file (MonoAotCompile *acfg)
5174 char *command, *opts;
5176 MonoJumpInfo *patch_info;
5179 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5183 /* Compute the final size of the got */
5184 for (i = 0; i < acfg->nmethods; ++i) {
5185 if (acfg->cfgs [i]) {
5186 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5187 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5188 if (!is_plt_patch (patch_info))
5189 get_got_offset (acfg, patch_info);
5191 get_plt_entry (acfg, patch_info);
5197 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5199 if (acfg->aot_opts.full_aot) {
5203 * Need to add the got entries used by the trampolines.
5204 * This is only a conservative approximation.
5206 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5207 /* For the generic + rgctx trampolines */
5208 acfg->final_got_size += 200;
5209 /* For the specific trampolines */
5210 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5211 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5216 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5219 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5220 * a lot of time, and doesn't seem to save much space.
5221 * The following optimizations cannot be enabled:
5223 * - 'jump-threading' changes our blockaddress references to int constants.
5224 * The opt list below was produced by taking the output of:
5225 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5226 * then removing tailcallelim + the global opts, and adding a second gvn.
5228 opts = g_strdup ("-instcombine -simplifycfg");
5229 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
5231 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5232 printf ("Executing opt: %s\n", command);
5233 if (system (command) != 0) {
5239 if (!acfg->llc_args)
5240 acfg->llc_args = g_string_new ("");
5242 /* Verbose asm slows down llc greatly */
5243 g_string_append (acfg->llc_args, " -asm-verbose=false");
5245 if (acfg->aot_opts.mtriple)
5246 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5248 if (llvm_acfg->aot_opts.static_link)
5249 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5251 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5252 unlink (acfg->tmpfname);
5254 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);
5256 printf ("Executing llc: %s\n", command);
5258 if (system (command) != 0) {
5265 emit_code (MonoAotCompile *acfg)
5269 char end_symbol [256];
5272 #if defined(TARGET_POWERPC64)
5273 sprintf (symbol, ".Lgot_addr");
5274 emit_section_change (acfg, ".text", 0);
5275 emit_alignment (acfg, 8);
5276 emit_label (acfg, symbol);
5277 emit_pointer (acfg, acfg->got_symbol);
5281 * This global symbol is used to compute the address of each method using the
5282 * code_offsets array. It is also used to compute the memory ranges occupied by
5283 * AOT code, so it must be equal to the address of the first emitted method.
5285 sprintf (symbol, "methods");
5286 emit_section_change (acfg, ".text", 0);
5287 emit_alignment (acfg, 8);
5289 for (i = 0; i < acfg->nmethods; ++i) {
5290 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5291 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5295 if (i == acfg->nmethods)
5296 /* No LLVM compiled methods */
5297 emit_label (acfg, symbol);
5299 emit_label (acfg, symbol);
5303 * Emit some padding so the local symbol for the first method doesn't have the
5304 * same address as 'methods'.
5306 #if defined(__default_codegen__)
5307 emit_zero_bytes (acfg, 16);
5308 #elif defined(__native_client_codegen__)
5310 const int kPaddingSize = 16;
5311 guint8 pad_buffer[kPaddingSize];
5312 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5313 emit_bytes (acfg, pad_buffer, kPaddingSize);
5318 for (l = acfg->method_order; l != NULL; l = l->next) {
5322 i = GPOINTER_TO_UINT (l->data);
5324 cfg = acfg->cfgs [i];
5329 method = cfg->orig_method;
5331 /* Emit unbox trampoline */
5332 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5333 char call_target [256];
5335 if (!method->wrapper_type && !method->is_inflated) {
5336 g_assert (method->token);
5337 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5339 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5342 emit_section_change (acfg, ".text", 0);
5343 #ifdef __native_client_codegen__
5344 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5346 emit_global (acfg, symbol, TRUE);
5348 if (acfg->thumb_mixed && cfg->compile_llvm)
5349 fprintf (acfg->fp, "\n.thumb_func\n");
5351 emit_label (acfg, symbol);
5353 sprintf (call_target, "%s", cfg->asm_symbol);
5355 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, call_target);
5358 if (cfg->compile_llvm)
5359 acfg->stats.llvm_count ++;
5361 emit_method_code (acfg, cfg);
5364 sprintf (symbol, "methods_end");
5365 emit_section_change (acfg, ".text", 0);
5366 emit_alignment (acfg, 8);
5367 emit_label (acfg, symbol);
5370 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5371 * from optimizing them away, since it doesn't see that code_offsets references them.
5372 * JITted methods don't need this since they are referenced using assembler local
5374 * FIXME: This is why write-symbols doesn't work on OSX ?
5376 if (acfg->llvm && acfg->need_no_dead_strip) {
5377 fprintf (acfg->fp, "\n");
5378 for (i = 0; i < acfg->nmethods; ++i) {
5379 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5380 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5384 sprintf (symbol, "code_offsets");
5385 emit_section_change (acfg, RODATA_SECT, 1);
5386 emit_alignment (acfg, 8);
5387 emit_label (acfg, symbol);
5389 acfg->stats.offsets_size += acfg->nmethods * 4;
5391 sprintf (end_symbol, "methods");
5392 for (i = 0; i < acfg->nmethods; ++i) {
5393 if (acfg->cfgs [i]) {
5394 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5396 emit_int32 (acfg, 0xffffffff);
5403 emit_info (MonoAotCompile *acfg)
5410 offsets = g_new0 (gint32, acfg->nmethods);
5412 for (l = acfg->method_order; l != NULL; l = l->next) {
5413 i = GPOINTER_TO_UINT (l->data);
5415 if (acfg->cfgs [i]) {
5416 emit_method_info (acfg, acfg->cfgs [i]);
5417 offsets [i] = acfg->cfgs [i]->method_info_offset;
5423 sprintf (symbol, "method_info_offsets");
5424 emit_section_change (acfg, RODATA_SECT, 1);
5425 emit_alignment (acfg, 8);
5426 emit_label (acfg, symbol);
5428 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5433 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5435 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5436 #define mix(a,b,c) { \
5437 a -= c; a ^= rot(c, 4); c += b; \
5438 b -= a; b ^= rot(a, 6); a += c; \
5439 c -= b; c ^= rot(b, 8); b += a; \
5440 a -= c; a ^= rot(c,16); c += b; \
5441 b -= a; b ^= rot(a,19); a += c; \
5442 c -= b; c ^= rot(b, 4); b += a; \
5444 #define final(a,b,c) { \
5445 c ^= b; c -= rot(b,14); \
5446 a ^= c; a -= rot(c,11); \
5447 b ^= a; b -= rot(a,25); \
5448 c ^= b; c -= rot(b,16); \
5449 a ^= c; a -= rot(c,4); \
5450 b ^= a; b -= rot(a,14); \
5451 c ^= b; c -= rot(b,24); \
5455 mono_aot_type_hash (MonoType *t1)
5457 guint hash = t1->type;
5459 hash |= t1->byref << 6; /* do not collide with t1->type values */
5461 case MONO_TYPE_VALUETYPE:
5462 case MONO_TYPE_CLASS:
5463 case MONO_TYPE_SZARRAY:
5464 /* check if the distribution is good enough */
5465 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5467 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5468 case MONO_TYPE_ARRAY:
5469 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5470 case MONO_TYPE_GENERICINST:
5471 return ((hash << 5) - hash) ^ 0;
5477 * mono_aot_method_hash:
5479 * Return a hash code for methods which only depends on metadata.
5482 mono_aot_method_hash (MonoMethod *method)
5484 MonoMethodSignature *sig;
5488 guint32 *hashes_start, *hashes;
5490 MonoGenericInst *ginst = NULL;
5492 /* Similar to the hash in mono_method_get_imt_slot () */
5494 sig = mono_method_signature (method);
5496 if (method->is_inflated)
5497 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5499 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5500 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5501 hashes = hashes_start;
5503 /* Some wrappers are assigned to random classes */
5504 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5505 klass = method->klass;
5507 klass = mono_defaults.object_class;
5509 if (!method->wrapper_type) {
5510 char *full_name = mono_type_full_name (&klass->byval_arg);
5512 hashes [0] = mono_metadata_str_hash (full_name);
5516 hashes [0] = mono_metadata_str_hash (klass->name);
5517 hashes [1] = mono_metadata_str_hash (klass->name_space);
5519 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5520 /* The method name includes a stringified pointer */
5523 hashes [2] = mono_metadata_str_hash (method->name);
5524 hashes [3] = method->wrapper_type;
5525 hashes [4] = mono_aot_type_hash (sig->ret);
5527 for (i = 0; i < sig->param_count; i++) {
5528 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5531 for (i = 0; i < ginst->type_argc; ++i)
5532 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5534 g_assert (hindex == hashes_count);
5536 /* Setup internal state */
5537 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5539 /* Handle most of the hashes */
5540 while (hashes_count > 3) {
5549 /* Handle the last 3 hashes (all the case statements fall through) */
5550 switch (hashes_count) {
5551 case 3 : c += hashes [2];
5552 case 2 : b += hashes [1];
5553 case 1 : a += hashes [0];
5555 case 0: /* nothing left to add */
5559 free (hashes_start);
5568 * mono_aot_wrapper_name:
5570 * Return a string which uniqely identifies the given wrapper method.
5573 mono_aot_wrapper_name (MonoMethod *method)
5575 char *name, *tmpsig, *klass_desc;
5577 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5579 switch (method->wrapper_type) {
5580 case MONO_WRAPPER_RUNTIME_INVOKE:
5581 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5582 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5584 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5587 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5588 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5589 g_free (klass_desc);
5599 * mono_aot_get_array_helper_from_wrapper;
5601 * Get the helper method in Array called by an array wrapper method.
5604 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5608 MonoGenericContext ctx;
5609 MonoType *args [16];
5610 char *mname, *iname, *s, *s2, *helper_name = NULL;
5612 prefix = "System.Collections.Generic";
5613 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5614 s2 = strstr (s, "`1.");
5620 //printf ("X: %s %s\n", iname, mname);
5622 if (!strcmp (iname, "IList"))
5623 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5625 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5626 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5628 g_free (helper_name);
5631 if (m->is_generic) {
5632 memset (&ctx, 0, sizeof (ctx));
5633 args [0] = &method->klass->element_class->byval_arg;
5634 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5635 m = mono_class_inflate_generic_method (m, &ctx);
5641 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5643 typedef struct HashEntry {
5644 guint32 key, value, index;
5645 struct HashEntry *next;
5649 * emit_extra_methods:
5651 * Emit methods which are not in the METHOD table, like wrappers.
5654 emit_extra_methods (MonoAotCompile *acfg)
5656 int i, table_size, buf_size;
5659 guint32 *info_offsets;
5662 HashEntry *entry, *new_entry;
5663 int nmethods, max_chain_length;
5666 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5668 /* Emit method info */
5670 for (i = 0; i < acfg->extra_methods->len; ++i) {
5671 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5672 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5679 p = buf = g_malloc (buf_size);
5683 method = cfg->method_to_register;
5686 if (method->wrapper_type) {
5687 gboolean encode_ref = FALSE;
5690 * We encode some wrappers using their name, since encoding them
5691 * directly would be difficult. This works because at runtime, we only need to
5692 * check whenever a method ref matches an existing MonoMethod. The downside is
5693 * that the method names are large, so we use the binary encoding if possible.
5695 switch (method->wrapper_type) {
5696 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5697 case MONO_WRAPPER_SYNCHRONIZED:
5700 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5701 /* Skip JIT icall wrappers */
5702 if (!strstr (method->name, "__icall_wrapper"))
5705 case MONO_WRAPPER_UNKNOWN:
5706 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5709 case MONO_WRAPPER_RUNTIME_INVOKE:
5710 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5711 /* Direct wrapper, encode normally */
5719 name = mono_aot_wrapper_name (method);
5723 encode_value (1, p, &p);
5724 encode_value (method->wrapper_type, p, &p);
5725 strcpy ((char*)p, name);
5726 p += strlen (name ) + 1;
5729 encode_value (0, p, &p);
5730 encode_method_ref (acfg, method, p, &p);
5733 g_assert ((p - buf) < buf_size);
5735 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5740 * Construct a chained hash table for mapping indexes in extra_method_info to
5743 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5744 table = g_ptr_array_sized_new (table_size);
5745 for (i = 0; i < table_size; ++i)
5746 g_ptr_array_add (table, NULL);
5747 chain_lengths = g_new0 (int, table_size);
5748 max_chain_length = 0;
5749 for (i = 0; i < acfg->extra_methods->len; ++i) {
5750 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5751 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5757 key = info_offsets [i];
5758 value = get_method_index (acfg, method);
5760 hash = mono_aot_method_hash (method) % table_size;
5762 chain_lengths [hash] ++;
5763 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5765 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5766 new_entry->key = key;
5767 new_entry->value = value;
5769 entry = g_ptr_array_index (table, hash);
5770 if (entry == NULL) {
5771 new_entry->index = hash;
5772 g_ptr_array_index (table, hash) = new_entry;
5775 entry = entry->next;
5777 entry->next = new_entry;
5778 new_entry->index = table->len;
5779 g_ptr_array_add (table, new_entry);
5783 //printf ("MAX: %d\n", max_chain_length);
5785 /* Emit the table */
5786 sprintf (symbol, "extra_method_table");
5787 emit_section_change (acfg, RODATA_SECT, 0);
5788 emit_alignment (acfg, 8);
5789 emit_label (acfg, symbol);
5791 emit_int32 (acfg, table_size);
5792 for (i = 0; i < table->len; ++i) {
5793 HashEntry *entry = g_ptr_array_index (table, i);
5795 if (entry == NULL) {
5796 emit_int32 (acfg, 0);
5797 emit_int32 (acfg, 0);
5798 emit_int32 (acfg, 0);
5800 //g_assert (entry->key > 0);
5801 emit_int32 (acfg, entry->key);
5802 emit_int32 (acfg, entry->value);
5804 emit_int32 (acfg, entry->next->index);
5806 emit_int32 (acfg, 0);
5811 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5812 * This is used by mono_aot_find_jit_info ().
5814 sprintf (symbol, "extra_method_info_offsets");
5815 emit_section_change (acfg, RODATA_SECT, 0);
5816 emit_alignment (acfg, 8);
5817 emit_label (acfg, symbol);
5819 emit_int32 (acfg, acfg->extra_methods->len);
5820 for (i = 0; i < acfg->extra_methods->len; ++i) {
5821 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5823 emit_int32 (acfg, get_method_index (acfg, method));
5824 emit_int32 (acfg, info_offsets [i]);
5829 emit_exception_info (MonoAotCompile *acfg)
5835 offsets = g_new0 (gint32, acfg->nmethods);
5836 for (i = 0; i < acfg->nmethods; ++i) {
5837 if (acfg->cfgs [i]) {
5838 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5839 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5845 sprintf (symbol, "ex_info_offsets");
5846 emit_section_change (acfg, RODATA_SECT, 1);
5847 emit_alignment (acfg, 8);
5848 emit_label (acfg, symbol);
5850 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5855 emit_unwind_info (MonoAotCompile *acfg)
5861 * The unwind info contains a lot of duplicates so we emit each unique
5862 * entry once, and only store the offset from the start of the table in the
5866 sprintf (symbol, "unwind_info");
5867 emit_section_change (acfg, RODATA_SECT, 1);
5868 emit_alignment (acfg, 8);
5869 emit_label (acfg, symbol);
5871 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5872 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5873 guint8 *unwind_info;
5874 guint32 unwind_info_len;
5878 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5881 encode_value (unwind_info_len, p, &p);
5882 emit_bytes (acfg, buf, p - buf);
5883 emit_bytes (acfg, unwind_info, unwind_info_len);
5885 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5890 emit_class_info (MonoAotCompile *acfg)
5896 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5897 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5898 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5900 sprintf (symbol, "class_info_offsets");
5901 emit_section_change (acfg, RODATA_SECT, 1);
5902 emit_alignment (acfg, 8);
5903 emit_label (acfg, symbol);
5905 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5909 typedef struct ClassNameTableEntry {
5910 guint32 token, index;
5911 struct ClassNameTableEntry *next;
5912 } ClassNameTableEntry;
5915 emit_class_name_table (MonoAotCompile *acfg)
5918 guint32 token, hash;
5923 ClassNameTableEntry *entry, *new_entry;
5926 * Construct a chained hash table for mapping class names to typedef tokens.
5928 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5929 table = g_ptr_array_sized_new (table_size);
5930 for (i = 0; i < table_size; ++i)
5931 g_ptr_array_add (table, NULL);
5932 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5933 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5934 klass = mono_class_get (acfg->image, token);
5937 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5938 hash = mono_metadata_str_hash (full_name) % table_size;
5941 /* FIXME: Allocate from the mempool */
5942 new_entry = g_new0 (ClassNameTableEntry, 1);
5943 new_entry->token = token;
5945 entry = g_ptr_array_index (table, hash);
5946 if (entry == NULL) {
5947 new_entry->index = hash;
5948 g_ptr_array_index (table, hash) = new_entry;
5951 entry = entry->next;
5953 entry->next = new_entry;
5954 new_entry->index = table->len;
5955 g_ptr_array_add (table, new_entry);
5959 /* Emit the table */
5960 sprintf (symbol, "class_name_table");
5961 emit_section_change (acfg, RODATA_SECT, 0);
5962 emit_alignment (acfg, 8);
5963 emit_label (acfg, symbol);
5965 /* FIXME: Optimize memory usage */
5966 g_assert (table_size < 65000);
5967 emit_int16 (acfg, table_size);
5968 g_assert (table->len < 65000);
5969 for (i = 0; i < table->len; ++i) {
5970 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5972 if (entry == NULL) {
5973 emit_int16 (acfg, 0);
5974 emit_int16 (acfg, 0);
5976 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5978 emit_int16 (acfg, entry->next->index);
5980 emit_int16 (acfg, 0);
5986 emit_image_table (MonoAotCompile *acfg)
5992 * The image table is small but referenced in a lot of places.
5993 * So we emit it at once, and reference its elements by an index.
5996 sprintf (symbol, "image_table");
5997 emit_section_change (acfg, RODATA_SECT, 1);
5998 emit_alignment (acfg, 8);
5999 emit_label (acfg, symbol);
6001 emit_int32 (acfg, acfg->image_table->len);
6002 for (i = 0; i < acfg->image_table->len; i++) {
6003 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6004 MonoAssemblyName *aname = &image->assembly->aname;
6006 /* FIXME: Support multi-module assemblies */
6007 g_assert (image->assembly->image == image);
6009 emit_string (acfg, image->assembly_name);
6010 emit_string (acfg, image->guid);
6011 emit_string (acfg, aname->culture ? aname->culture : "");
6012 emit_string (acfg, (const char*)aname->public_key_token);
6014 emit_alignment (acfg, 8);
6015 emit_int32 (acfg, aname->flags);
6016 emit_int32 (acfg, aname->major);
6017 emit_int32 (acfg, aname->minor);
6018 emit_int32 (acfg, aname->build);
6019 emit_int32 (acfg, aname->revision);
6024 emit_got_info (MonoAotCompile *acfg)
6027 int i, first_plt_got_patch, buf_size;
6029 guint32 *got_info_offsets;
6031 /* Add the patches needed by the PLT to the GOT */
6032 acfg->plt_got_offset_base = acfg->got_offset;
6033 first_plt_got_patch = acfg->got_patches->len;
6034 for (i = 1; i < acfg->plt_offset; ++i) {
6035 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6037 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6040 acfg->got_offset += acfg->plt_offset;
6044 * - optimize offsets table.
6045 * - reduce number of exported symbols.
6046 * - emit info for a klass only once.
6047 * - determine when a method uses a GOT slot which is guaranteed to be already
6049 * - clean up and document the code.
6050 * - use String.Empty in class libs.
6053 /* Encode info required to decode shared GOT entries */
6054 buf_size = acfg->got_patches->len * 128;
6055 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6056 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6057 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6059 if (acfg->plt_offset)
6060 acfg->plt_got_info_offsets [0] = 0;
6061 for (i = 0; i < acfg->got_patches->len; ++i) {
6062 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6066 encode_value (ji->type, p, &p);
6067 encode_patch (acfg, ji, p, &p);
6069 g_assert (p - buf <= buf_size);
6070 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6072 if (i >= first_plt_got_patch)
6073 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6074 acfg->stats.got_info_size += p - buf;
6077 /* Emit got_info_offsets table */
6078 sprintf (symbol, "got_info_offsets");
6079 emit_section_change (acfg, RODATA_SECT, 1);
6080 emit_alignment (acfg, 8);
6081 emit_label (acfg, symbol);
6083 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6084 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6088 emit_got (MonoAotCompile *acfg)
6093 /* Don't make GOT global so accesses to it don't need relocations */
6094 sprintf (symbol, "%s", acfg->got_symbol);
6095 emit_section_change (acfg, ".bss", 0);
6096 emit_alignment (acfg, 8);
6097 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6098 emit_label (acfg, symbol);
6099 if (acfg->got_offset > 0)
6100 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6102 sprintf (symbol, "got_end");
6103 emit_label (acfg, symbol);
6107 typedef struct GlobalsTableEntry {
6108 guint32 value, index;
6109 struct GlobalsTableEntry *next;
6110 } GlobalsTableEntry;
6113 emit_globals (MonoAotCompile *acfg)
6119 GlobalsTableEntry *entry, *new_entry;
6121 if (!acfg->aot_opts.static_link)
6125 * When static linking, we emit a table containing our globals.
6129 * Construct a chained hash table for mapping global names to their index in
6130 * the globals table.
6132 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6133 table = g_ptr_array_sized_new (table_size);
6134 for (i = 0; i < table_size; ++i)
6135 g_ptr_array_add (table, NULL);
6136 for (i = 0; i < acfg->globals->len; ++i) {
6137 char *name = g_ptr_array_index (acfg->globals, i);
6139 hash = mono_metadata_str_hash (name) % table_size;
6141 /* FIXME: Allocate from the mempool */
6142 new_entry = g_new0 (GlobalsTableEntry, 1);
6143 new_entry->value = i;
6145 entry = g_ptr_array_index (table, hash);
6146 if (entry == NULL) {
6147 new_entry->index = hash;
6148 g_ptr_array_index (table, hash) = new_entry;
6151 entry = entry->next;
6153 entry->next = new_entry;
6154 new_entry->index = table->len;
6155 g_ptr_array_add (table, new_entry);
6159 /* Emit the table */
6160 sprintf (symbol, ".Lglobals_hash");
6161 emit_section_change (acfg, RODATA_SECT, 0);
6162 emit_alignment (acfg, 8);
6163 emit_label (acfg, symbol);
6165 /* FIXME: Optimize memory usage */
6166 g_assert (table_size < 65000);
6167 emit_int16 (acfg, table_size);
6168 for (i = 0; i < table->len; ++i) {
6169 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6171 if (entry == NULL) {
6172 emit_int16 (acfg, 0);
6173 emit_int16 (acfg, 0);
6175 emit_int16 (acfg, entry->value + 1);
6177 emit_int16 (acfg, entry->next->index);
6179 emit_int16 (acfg, 0);
6183 /* Emit the names */
6184 for (i = 0; i < acfg->globals->len; ++i) {
6185 char *name = g_ptr_array_index (acfg->globals, i);
6187 sprintf (symbol, "name_%d", i);
6188 emit_section_change (acfg, RODATA_SECT, 1);
6190 emit_alignment (acfg, 4);
6192 emit_label (acfg, symbol);
6193 emit_string (acfg, name);
6196 /* Emit the globals table */
6197 sprintf (symbol, "globals");
6198 emit_section_change (acfg, ".data", 0);
6199 /* This is not a global, since it is accessed by the init function */
6200 emit_alignment (acfg, 8);
6201 emit_label (acfg, symbol);
6203 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6204 emit_pointer (acfg, symbol);
6206 for (i = 0; i < acfg->globals->len; ++i) {
6207 char *name = g_ptr_array_index (acfg->globals, i);
6209 sprintf (symbol, "name_%d", i);
6210 emit_pointer (acfg, symbol);
6212 sprintf (symbol, "%s", name);
6213 emit_pointer (acfg, symbol);
6215 /* Null terminate the table */
6216 emit_int32 (acfg, 0);
6217 emit_int32 (acfg, 0);
6221 emit_autoreg (MonoAotCompile *acfg)
6226 * Emit a function into the .ctor section which will be called by the ELF
6227 * loader to register this module with the runtime.
6229 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6232 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6234 arch_emit_autoreg (acfg, symbol);
6240 emit_mem_end (MonoAotCompile *acfg)
6244 sprintf (symbol, "mem_end");
6245 emit_section_change (acfg, ".text", 1);
6246 emit_alignment (acfg, 8);
6247 emit_label (acfg, symbol);
6251 * Emit a structure containing all the information not stored elsewhere.
6254 emit_file_info (MonoAotCompile *acfg)
6259 const char *gc_name;
6262 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6264 if (acfg->aot_opts.bind_to_runtime_version) {
6265 build_info = mono_get_runtime_build_info ();
6266 emit_string_symbol (acfg, "runtime_version", build_info);
6267 g_free (build_info);
6269 emit_string_symbol (acfg, "runtime_version", "");
6272 /* Emit a string holding the assembly name */
6273 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6276 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6279 gc_name = mono_gc_get_gc_name ();
6280 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6282 sprintf (symbol, "mono_aot_file_info");
6283 emit_section_change (acfg, ".data", 0);
6284 emit_alignment (acfg, 8);
6285 emit_label (acfg, symbol);
6286 if (!acfg->aot_opts.static_link)
6287 emit_global (acfg, symbol, FALSE);
6289 /* The data emitted here must match MonoAotFileInfo. */
6291 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6292 emit_int32 (acfg, 0);
6295 * We emit pointers to our data structures instead of emitting global symbols which
6296 * point to them, to reduce the number of globals, and because using globals leads to
6297 * various problems (i.e. arm/thumb).
6299 emit_pointer (acfg, acfg->got_symbol);
6300 emit_pointer (acfg, "methods");
6303 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6305 emit_pointer (acfg, "mono_eh_frame");
6307 emit_pointer (acfg, NULL);
6309 emit_pointer (acfg, "blob");
6310 emit_pointer (acfg, "class_name_table");
6311 emit_pointer (acfg, "class_info_offsets");
6312 emit_pointer (acfg, "method_info_offsets");
6313 emit_pointer (acfg, "ex_info_offsets");
6314 emit_pointer (acfg, "code_offsets");
6315 emit_pointer (acfg, "extra_method_info_offsets");
6316 emit_pointer (acfg, "extra_method_table");
6317 emit_pointer (acfg, "got_info_offsets");
6318 emit_pointer (acfg, "methods_end");
6319 emit_pointer (acfg, "unwind_info");
6320 emit_pointer (acfg, "mem_end");
6321 emit_pointer (acfg, "image_table");
6322 emit_pointer (acfg, "plt");
6323 emit_pointer (acfg, "plt_end");
6324 emit_pointer (acfg, "assembly_guid");
6325 emit_pointer (acfg, "runtime_version");
6326 if (acfg->num_trampoline_got_entries) {
6327 emit_pointer (acfg, "specific_trampolines");
6328 emit_pointer (acfg, "static_rgctx_trampolines");
6329 emit_pointer (acfg, "imt_thunks");
6331 emit_pointer (acfg, NULL);
6332 emit_pointer (acfg, NULL);
6333 emit_pointer (acfg, NULL);
6335 if (acfg->thumb_mixed) {
6336 emit_pointer (acfg, "thumb_end");
6338 emit_pointer (acfg, NULL);
6340 if (acfg->aot_opts.static_link) {
6341 emit_pointer (acfg, "globals");
6343 emit_pointer (acfg, NULL);
6345 emit_pointer (acfg, "assembly_name");
6347 emit_int32 (acfg, acfg->plt_got_offset_base);
6348 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6349 emit_int32 (acfg, acfg->plt_offset);
6350 emit_int32 (acfg, acfg->nmethods);
6351 emit_int32 (acfg, acfg->flags);
6352 emit_int32 (acfg, acfg->opts);
6353 emit_int32 (acfg, gc_name_offset);
6355 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6356 emit_int32 (acfg, acfg->num_trampolines [i]);
6357 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6358 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6359 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6360 emit_int32 (acfg, acfg->trampoline_size [i]);
6362 #if defined (TARGET_ARM) && defined (__APPLE__)
6367 t.type = MONO_TYPE_R8;
6368 mono_type_size (&t, &align);
6370 emit_int32 (acfg, align);
6372 t.type = MONO_TYPE_I8;
6373 mono_type_size (&t, &align);
6375 emit_int32 (acfg, align);
6378 emit_int32 (acfg, __alignof__ (double));
6379 emit_int32 (acfg, __alignof__ (gint64));
6382 if (acfg->aot_opts.static_link) {
6386 * Emit a global symbol which can be passed by an embedding app to
6387 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6390 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6391 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6393 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6396 /* Get rid of characters which cannot occur in symbols */
6398 for (p = symbol; *p; ++p) {
6399 if (!(isalnum (*p) || *p == '_'))
6402 acfg->static_linking_symbol = g_strdup (symbol);
6403 emit_global_inner (acfg, symbol, FALSE);
6404 emit_label (acfg, symbol);
6405 emit_pointer (acfg, "mono_aot_file_info");
6410 emit_blob (MonoAotCompile *acfg)
6414 sprintf (symbol, "blob");
6415 emit_section_change (acfg, RODATA_SECT, 1);
6416 emit_alignment (acfg, 8);
6417 emit_label (acfg, symbol);
6419 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6423 emit_dwarf_info (MonoAotCompile *acfg)
6425 #ifdef EMIT_DWARF_INFO
6427 char symbol [128], symbol2 [128];
6429 /* DIEs for methods */
6430 for (i = 0; i < acfg->nmethods; ++i) {
6431 MonoCompile *cfg = acfg->cfgs [i];
6436 // FIXME: LLVM doesn't define .Lme_...
6437 if (cfg->compile_llvm)
6440 sprintf (symbol, "%s", cfg->asm_symbol);
6441 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6443 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 ()));
6449 collect_methods (MonoAotCompile *acfg)
6452 MonoImage *image = acfg->image;
6454 /* Collect methods */
6455 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6457 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6459 method = mono_get_method (acfg->image, token, NULL);
6462 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6466 /* Load all methods eagerly to skip the slower lazy loading code */
6467 mono_class_setup_methods (method->klass);
6469 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6470 /* Compile the wrapper instead */
6471 /* We do this here instead of add_wrappers () because it is easy to do it here */
6472 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6476 /* FIXME: Some mscorlib methods don't have debug info */
6478 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6479 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6480 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6481 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6482 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6483 if (!mono_debug_lookup_method (method)) {
6484 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6491 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6492 add_method_with_index (acfg, method, i, FALSE);
6493 acfg->method_index ++;
6496 add_generic_instances (acfg);
6498 if (acfg->aot_opts.full_aot)
6499 add_wrappers (acfg);
6503 compile_methods (MonoAotCompile *acfg)
6507 if (acfg->aot_opts.nthreads > 0) {
6512 gpointer *user_data;
6513 MonoMethod **methods;
6515 methods_len = acfg->methods->len;
6517 len = acfg->methods->len / acfg->aot_opts.nthreads;
6520 * Partition the list of methods into fragments, and hand it to threads to
6523 threads = g_ptr_array_new ();
6524 /* Make a copy since acfg->methods is modified by compile_method () */
6525 methods = g_new0 (MonoMethod*, methods_len);
6526 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6527 for (i = 0; i < methods_len; ++i)
6528 methods [i] = g_ptr_array_index (acfg->methods, i);
6530 while (i < methods_len) {
6531 frag = g_ptr_array_new ();
6532 for (j = 0; j < len; ++j) {
6533 if (i < methods_len) {
6534 g_ptr_array_add (frag, methods [i]);
6539 user_data = g_new0 (gpointer, 3);
6540 user_data [0] = mono_domain_get ();
6541 user_data [1] = acfg;
6542 user_data [2] = frag;
6544 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6545 g_ptr_array_add (threads, handle);
6549 for (i = 0; i < threads->len; ++i) {
6550 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6556 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6557 for (i = methods_len; i < acfg->methods->len; ++i) {
6558 /* This can new methods to acfg->methods */
6559 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6564 compile_asm (MonoAotCompile *acfg)
6566 char *command, *objfile;
6567 char *outfile_name, *tmp_outfile_name;
6568 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6570 #if defined(TARGET_AMD64)
6571 #define AS_OPTIONS "--64"
6572 #elif defined(TARGET_POWERPC64)
6573 #define AS_OPTIONS "-a64 -mppc64"
6574 #define LD_OPTIONS "-m elf64ppc"
6575 #elif defined(sparc) && SIZEOF_VOID_P == 8
6576 #define AS_OPTIONS "-xarch=v9"
6577 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6578 #define AS_OPTIONS "-arch i386 -W"
6580 #define AS_OPTIONS ""
6583 #ifdef __native_client_codegen__
6584 #if defined(TARGET_AMD64)
6585 #define AS_NAME "nacl64-as"
6587 #define AS_NAME "nacl-as"
6590 #define AS_NAME "as"
6594 #define LD_OPTIONS ""
6597 #define EH_LD_OPTIONS ""
6599 if (acfg->aot_opts.asm_only) {
6600 printf ("Output file: '%s'.\n", acfg->tmpfname);
6601 if (acfg->aot_opts.static_link)
6602 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6606 if (acfg->aot_opts.static_link) {
6607 if (acfg->aot_opts.outfile)
6608 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6610 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6612 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6614 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);
6615 printf ("Executing the native assembler: %s\n", command);
6616 if (system (command) != 0) {
6624 if (acfg->aot_opts.static_link) {
6625 printf ("Output file: '%s'.\n", objfile);
6626 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6631 if (acfg->aot_opts.outfile)
6632 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6634 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6636 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6639 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6640 #elif defined(__ppc__) && defined(__APPLE__)
6641 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6642 #elif defined(HOST_WIN32)
6643 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6644 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6645 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6647 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6649 printf ("Executing the native linker: %s\n", command);
6650 if (system (command) != 0) {
6651 g_free (tmp_outfile_name);
6652 g_free (outfile_name);
6660 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6661 printf ("Stripping the binary: %s\n", com);
6665 #if defined(TARGET_ARM) && !defined(__APPLE__)
6667 * gas generates 'mapping symbols' each time code and data is mixed, which
6668 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6670 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6671 printf ("Stripping the binary: %s\n", command);
6672 if (system (command) != 0) {
6673 g_free (tmp_outfile_name);
6674 g_free (outfile_name);
6681 rename (tmp_outfile_name, outfile_name);
6683 g_free (tmp_outfile_name);
6684 g_free (outfile_name);
6687 if (acfg->aot_opts.save_temps)
6688 printf ("Retained input file.\n");
6690 unlink (acfg->tmpfname);
6695 static MonoAotCompile*
6696 acfg_create (MonoAssembly *ass, guint32 opts)
6698 MonoImage *image = ass->image;
6699 MonoAotCompile *acfg;
6702 acfg = g_new0 (MonoAotCompile, 1);
6703 acfg->methods = g_ptr_array_new ();
6704 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6705 acfg->method_depth = g_hash_table_new (NULL, NULL);
6706 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6707 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6708 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6709 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6710 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6711 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6712 acfg->got_patches = g_ptr_array_new ();
6713 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6714 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6715 acfg->image_hash = g_hash_table_new (NULL, NULL);
6716 acfg->image_table = g_ptr_array_new ();
6717 acfg->globals = g_ptr_array_new ();
6718 acfg->image = image;
6720 acfg->mempool = mono_mempool_new ();
6721 acfg->extra_methods = g_ptr_array_new ();
6722 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6723 acfg->unwind_ops = g_ptr_array_new ();
6724 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6725 InitializeCriticalSection (&acfg->mutex);
6731 acfg_free (MonoAotCompile *acfg)
6735 img_writer_destroy (acfg->w);
6736 for (i = 0; i < acfg->nmethods; ++i)
6738 g_free (acfg->cfgs [i]);
6739 g_free (acfg->cfgs);
6740 g_free (acfg->static_linking_symbol);
6741 g_free (acfg->got_symbol);
6742 g_free (acfg->plt_symbol);
6743 g_ptr_array_free (acfg->methods, TRUE);
6744 g_ptr_array_free (acfg->got_patches, TRUE);
6745 g_ptr_array_free (acfg->image_table, TRUE);
6746 g_ptr_array_free (acfg->globals, TRUE);
6747 g_ptr_array_free (acfg->unwind_ops, TRUE);
6748 g_hash_table_destroy (acfg->method_indexes);
6749 g_hash_table_destroy (acfg->method_depth);
6750 g_hash_table_destroy (acfg->plt_offset_to_entry);
6751 g_hash_table_destroy (acfg->patch_to_plt_entry);
6752 g_hash_table_destroy (acfg->patch_to_got_offset);
6753 g_hash_table_destroy (acfg->method_to_cfg);
6754 g_hash_table_destroy (acfg->token_info_hash);
6755 g_hash_table_destroy (acfg->image_hash);
6756 g_hash_table_destroy (acfg->unwind_info_offsets);
6757 g_hash_table_destroy (acfg->method_label_hash);
6758 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6759 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6760 g_free (acfg->patch_to_got_offset_by_type);
6761 mono_mempool_destroy (acfg->mempool);
6766 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6768 MonoImage *image = ass->image;
6770 MonoAotCompile *acfg;
6771 char *outfile_name, *tmp_outfile_name, *p;
6775 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6777 acfg = acfg_create (ass, opts);
6779 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6780 acfg->aot_opts.write_symbols = TRUE;
6781 acfg->aot_opts.ntrampolines = 1024;
6782 acfg->aot_opts.nrgctx_trampolines = 1024;
6783 acfg->aot_opts.nimt_trampolines = 128;
6784 acfg->aot_opts.llvm_path = g_strdup ("");
6786 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6788 if (acfg->aot_opts.static_link)
6789 acfg->aot_opts.autoreg = TRUE;
6791 //acfg->aot_opts.print_skipped_methods = TRUE;
6793 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6794 if (acfg->aot_opts.full_aot) {
6795 printf ("--aot=full is not supported on this platform.\n");
6800 if (acfg->aot_opts.static_link)
6801 acfg->aot_opts.asm_writer = TRUE;
6803 if (acfg->aot_opts.soft_debug) {
6804 MonoDebugOptions *opt = mini_get_debug_options ();
6806 opt->mdb_optimizations = TRUE;
6807 opt->gen_seq_points = TRUE;
6809 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6810 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6813 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6816 if (mono_use_llvm) {
6818 acfg->aot_opts.asm_writer = TRUE;
6819 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6821 if (acfg->aot_opts.soft_debug) {
6822 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
6827 if (acfg->aot_opts.full_aot)
6828 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6830 load_profile_files (acfg);
6832 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6833 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6834 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6836 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6838 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6842 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6843 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6845 /* Get rid of characters which cannot occur in symbols */
6846 for (p = acfg->got_symbol_base; *p; ++p) {
6847 if (!(isalnum (*p) || *p == '_'))
6850 for (p = acfg->plt_symbol; *p; ++p) {
6851 if (!(isalnum (*p) || *p == '_'))
6855 acfg->method_index = 1;
6857 collect_methods (acfg);
6859 acfg->cfgs_size = acfg->methods->len + 32;
6860 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6862 /* PLT offset 0 is reserved for the PLT trampoline */
6863 acfg->plt_offset = 1;
6868 mono_llvm_create_aot_module (acfg->got_symbol_base);
6872 /* GOT offset 0 is reserved for the address of the current assembly */
6876 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6877 ji->type = MONO_PATCH_INFO_IMAGE;
6878 ji->data.image = acfg->image;
6880 get_got_offset (acfg, ji);
6882 /* Slot 1 is reserved for the mscorlib got addr */
6883 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6884 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6885 get_got_offset (acfg, ji);
6887 /* This is very common */
6888 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6889 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6890 get_got_offset (acfg, ji);
6895 compile_methods (acfg);
6899 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6905 if (acfg->aot_opts.asm_only) {
6906 if (acfg->aot_opts.outfile)
6907 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6909 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6911 acfg->tmpfname = g_strdup ("temp.s");
6914 emit_llvm_file (acfg);
6918 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6919 if (acfg->aot_opts.outfile)
6920 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6922 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6925 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6926 * it might be in another file system so the rename () won't work.
6928 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6930 acfg->fp = fopen (tmp_outfile_name, "w");
6932 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6936 acfg->w = img_writer_create (acfg->fp, TRUE);
6937 acfg->use_bin_writer = TRUE;
6940 /* Append to the .s file created by llvm */
6941 /* FIXME: Use multiple files instead */
6942 acfg->fp = fopen (acfg->tmpfname, "a+");
6944 if (acfg->aot_opts.asm_only) {
6945 if (acfg->aot_opts.outfile)
6946 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6948 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6949 acfg->fp = fopen (acfg->tmpfname, "w+");
6951 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6952 acfg->fp = fdopen (i, "w+");
6954 g_assert (acfg->fp);
6956 acfg->w = img_writer_create (acfg->fp, FALSE);
6958 tmp_outfile_name = NULL;
6959 outfile_name = NULL;
6962 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6964 /* Compute symbols for methods */
6965 for (i = 0; i < acfg->nmethods; ++i) {
6966 if (acfg->cfgs [i]) {
6967 MonoCompile *cfg = acfg->cfgs [i];
6968 int method_index = get_method_index (acfg, cfg->orig_method);
6970 if (COMPILE_LLVM (cfg))
6971 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
6973 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
6977 if (!acfg->aot_opts.nodebug)
6978 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6980 img_writer_emit_start (acfg->w);
6983 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6985 if (acfg->thumb_mixed) {
6988 * This global symbol marks the end of THUMB code, and the beginning of ARM
6989 * code generated by our JIT.
6991 sprintf (symbol, "thumb_end");
6992 emit_section_change (acfg, ".text", 0);
6993 emit_label (acfg, symbol);
6994 emit_zero_bytes (acfg, 16);
6996 fprintf (acfg->fp, ".arm\n");
7003 emit_extra_methods (acfg);
7005 emit_trampolines (acfg);
7007 emit_class_name_table (acfg);
7009 emit_got_info (acfg);
7011 emit_exception_info (acfg);
7013 emit_unwind_info (acfg);
7015 emit_class_info (acfg);
7019 emit_image_table (acfg);
7023 emit_file_info (acfg);
7027 emit_globals (acfg);
7029 emit_autoreg (acfg);
7032 emit_dwarf_info (acfg);
7033 mono_dwarf_writer_close (acfg->dwarf);
7036 emit_mem_end (acfg);
7040 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7043 g_assert (acfg->got_offset <= acfg->final_got_size);
7045 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);
7048 res = img_writer_emit_writeout (acfg->w);
7053 if (acfg->use_bin_writer) {
7054 int err = rename (tmp_outfile_name, outfile_name);
7057 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7061 res = compile_asm (acfg);
7068 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7070 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);
7071 if (acfg->stats.genericcount)
7072 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7073 if (acfg->stats.abscount)
7074 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7075 if (acfg->stats.lmfcount)
7076 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7077 if (acfg->stats.ocount)
7078 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7080 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7081 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);
7082 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7084 if (acfg->aot_opts.stats) {
7087 printf ("GOT slot distribution:\n");
7088 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7089 if (acfg->stats.got_slot_types [i])
7090 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
7093 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);
7105 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)