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(__MACH__)
84 #define SHARED_EXT ".dylib"
86 #define SHARED_EXT ".so"
89 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
90 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
91 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
93 typedef struct MonoAotOptions {
96 gboolean write_symbols;
97 gboolean metadata_only;
98 gboolean bind_to_runtime_version;
101 gboolean static_link;
108 int nrgctx_trampolines;
109 int nimt_trampolines;
110 gboolean print_skipped_methods;
116 typedef struct MonoAotStats {
117 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
118 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
119 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
120 int got_slots, offsets_size;
121 int got_slot_types [MONO_PATCH_INFO_NONE];
122 int jit_time, gen_time, link_time;
125 typedef struct MonoAotCompile {
128 GHashTable *method_indexes;
129 GHashTable *method_depth;
132 GHashTable *patch_to_plt_entry;
133 GHashTable *plt_offset_to_entry;
134 GHashTable *patch_to_got_offset;
135 GHashTable **patch_to_got_offset_by_type;
136 GPtrArray *got_patches;
137 GHashTable *image_hash;
138 GHashTable *method_to_cfg;
139 GHashTable *token_info_hash;
140 GPtrArray *extra_methods;
141 GPtrArray *image_table;
144 guint32 *plt_got_info_offsets;
145 guint32 got_offset, plt_offset, plt_got_offset_base;
146 guint32 final_got_size;
147 /* Number of GOT entries reserved for trampolines */
148 guint32 num_trampoline_got_entries;
150 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
151 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
152 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
154 MonoAotOptions aot_opts;
157 MonoMemPool *mempool;
160 char *static_linking_symbol;
161 CRITICAL_SECTION mutex;
162 gboolean use_bin_writer;
164 MonoDwarfWriter *dwarf;
168 GHashTable *unwind_info_offsets;
169 GPtrArray *unwind_ops;
170 guint32 unwind_info_offset;
171 char *got_symbol_base;
174 GHashTable *method_label_hash;
175 const char *temp_prefix;
176 const char *llvm_label_prefix;
177 guint32 label_generator;
179 MonoAotFileFlags flags;
180 MonoDynamicStream blob;
189 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
190 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
192 /* This points to the current acfg in LLVM mode */
193 static MonoAotCompile *llvm_acfg;
195 #ifdef HAVE_ARRAY_ELEM_INIT
196 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
197 #define MSGSTRFIELD1(line) str##line
198 static const struct msgstr_t {
199 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
200 #include "patch-info.h"
203 #define PATCH_INFO(a,b) b,
204 #include "patch-info.h"
207 static const gint16 opidx [] = {
208 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
209 #include "patch-info.h"
213 static G_GNUC_UNUSED const char*
214 get_patch_name (int info)
216 return (const char*)&opstr + opidx [info];
220 #define PATCH_INFO(a,b) b,
221 static const char* const
222 patch_types [MONO_PATCH_INFO_NUM + 1] = {
223 #include "patch-info.h"
227 static G_GNUC_UNUSED const char*
228 get_patch_name (int info)
230 return patch_types [info];
235 /* Wrappers around the image writer functions */
238 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
240 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
244 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
246 img_writer_emit_push_section (acfg->w, section_name, subsection);
250 emit_pop_section (MonoAotCompile *acfg)
252 img_writer_emit_pop_section (acfg->w);
256 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
258 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
262 emit_label (MonoAotCompile *acfg, const char *name)
264 img_writer_emit_label (acfg->w, name);
268 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
270 img_writer_emit_bytes (acfg->w, buf, size);
274 emit_string (MonoAotCompile *acfg, const char *value)
276 img_writer_emit_string (acfg->w, value);
280 emit_line (MonoAotCompile *acfg)
282 img_writer_emit_line (acfg->w);
286 emit_alignment (MonoAotCompile *acfg, int size)
288 img_writer_emit_alignment (acfg->w, size);
292 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
294 img_writer_emit_pointer_unaligned (acfg->w, target);
298 emit_pointer (MonoAotCompile *acfg, const char *target)
300 img_writer_emit_pointer (acfg->w, target);
304 emit_int16 (MonoAotCompile *acfg, int value)
306 img_writer_emit_int16 (acfg->w, value);
310 emit_int32 (MonoAotCompile *acfg, int value)
312 img_writer_emit_int32 (acfg->w, value);
316 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
318 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
322 emit_zero_bytes (MonoAotCompile *acfg, int num)
324 img_writer_emit_zero_bytes (acfg->w, num);
328 emit_byte (MonoAotCompile *acfg, guint8 val)
330 img_writer_emit_byte (acfg->w, val);
333 #ifdef __native_client_codegen__
335 emit_nacl_call_alignment (MonoAotCompile *acfg)
337 img_writer_emit_nacl_call_alignment (acfg->w);
341 static G_GNUC_UNUSED void
342 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
344 img_writer_emit_global (acfg->w, name, func);
348 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
350 if (acfg->aot_opts.no_dlsym) {
351 g_ptr_array_add (acfg->globals, g_strdup (name));
352 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
354 img_writer_emit_global (acfg->w, name, func);
359 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
361 img_writer_emit_symbol_size (acfg->w, name, end_label);
365 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
367 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
368 emit_global (acfg, name, FALSE);
369 img_writer_emit_label (acfg->w, name);
370 img_writer_emit_string (acfg->w, value);
373 static G_GNUC_UNUSED void
374 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
377 guint8 b = value & 0x7f;
379 if (value != 0) /* more bytes to come */
385 static G_GNUC_UNUSED void
386 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
389 gboolean negative = (value < 0);
396 /* the following is unnecessary if the
397 * implementation of >>= uses an arithmetic rather
398 * than logical shift for a signed left operand
402 value |= - ((gint64)1 <<(size - 7));
403 /* sign bit of byte is second high order bit (0x40) */
404 if ((value == 0 && !(byte & 0x40)) ||
405 (value == -1 && (byte & 0x40)))
409 emit_byte (acfg, byte);
413 static G_GNUC_UNUSED void
414 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
419 guint8 b = value & 0x7f;
421 if (value != 0) /* more bytes to come */
429 static G_GNUC_UNUSED void
430 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
433 gboolean negative = (value < 0);
441 /* the following is unnecessary if the
442 * implementation of >>= uses an arithmetic rather
443 * than logical shift for a signed left operand
447 value |= - (1 <<(size - 7));
448 /* sign bit of byte is second high order bit (0x40) */
449 if ((value == 0 && !(byte & 0x40)) ||
450 (value == -1 && (byte & 0x40)))
460 /* ARCHITECTURE SPECIFIC CODE */
462 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
463 #define EMIT_DWARF_INFO 1
466 #if defined(TARGET_ARM)
467 #define AOT_FUNC_ALIGNMENT 4
469 #define AOT_FUNC_ALIGNMENT 16
471 #if defined(TARGET_X86) && defined(__native_client_codegen__)
472 #undef AOT_FUNC_ALIGNMENT
473 #define AOT_FUNC_ALIGNMENT 32
476 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
477 #define PPC_LD_OP "ld"
478 #define PPC_LDX_OP "ldx"
480 #define PPC_LD_OP "lwz"
481 #define PPC_LDX_OP "lwzx"
487 #define LLVM_LABEL_PREFIX "_"
489 #define LLVM_LABEL_PREFIX ""
494 #define LLC_TARGET_ARGS "-march=arm -mattr=+v6 -mtriple=arm-apple-darwin"
496 //#define LLC_TARGET_ARGS "-march=arm -mtriple=arm-linux-gnueabi -soft-float"
498 #define LLC_TARGET_ARGS ""
502 * arch_emit_direct_call:
504 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
508 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
510 #if defined(TARGET_X86) || defined(TARGET_AMD64)
511 /* Need to make sure this is exactly 5 bytes long */
512 emit_byte (acfg, '\xe8');
513 emit_symbol_diff (acfg, target, ".", -4);
515 #elif defined(TARGET_ARM)
516 if (acfg->use_bin_writer) {
523 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
524 emit_bytes (acfg, buf, 4);
526 img_writer_emit_unset_mode (acfg->w);
527 fprintf (acfg->fp, "bl %s\n", target);
530 #elif defined(TARGET_POWERPC)
531 if (acfg->use_bin_writer) {
532 g_assert_not_reached ();
534 img_writer_emit_unset_mode (acfg->w);
535 fprintf (acfg->fp, "bl %s\n", target);
539 g_assert_not_reached ();
545 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
547 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
548 * in in the 2. slot of every GOT, and require every method to place the GOT
549 * address in r30, even when it doesn't access the GOT otherwise. This way,
550 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
555 * PPC64 uses function descriptors which greatly complicate all code, since
556 * these are used very inconsistently in the runtime. Some functions like
557 * mono_compile_method () return ftn descriptors, while others like the
558 * trampoline creation functions do not.
559 * We assume that all GOT slots contain function descriptors, and create
560 * descriptors in aot-runtime.c when needed.
561 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
562 * from function descriptors, we could do the same, but it would require
563 * rewriting all the ppc/aot code to handle function descriptors properly.
564 * So instead, we use the same approach as on PPC32.
565 * This is a horrible mess, but fixing it would probably lead to an even bigger
571 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
574 #ifdef MONO_ARCH_AOT_SUPPORTED
576 * arch_emit_got_offset:
578 * The memory pointed to by CODE should hold native code for computing the GOT
579 * address. Emit this code while patching it with the offset between code and
580 * the GOT. CODE_SIZE is set to the number of bytes emitted.
583 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
585 #if defined(TARGET_POWERPC64)
586 g_assert (!acfg->use_bin_writer);
587 img_writer_emit_unset_mode (acfg->w);
589 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
590 * unsupported relocations. So we store the got address into the .Lgot_addr
591 * symbol which is in the text segment, compute its address, and load it.
593 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
594 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
595 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
596 fprintf (acfg->fp, "add 30, 30, 0\n");
597 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
598 acfg->label_generator ++;
600 #elif defined(TARGET_POWERPC)
601 g_assert (!acfg->use_bin_writer);
602 img_writer_emit_unset_mode (acfg->w);
603 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
604 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
605 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
606 acfg->label_generator ++;
609 guint32 offset = mono_arch_get_patch_offset (code);
610 emit_bytes (acfg, code, offset);
611 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
613 *code_size = offset + 4;
618 * arch_emit_got_access:
620 * The memory pointed to by CODE should hold native code for loading a GOT
621 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
622 * CODE_SIZE is set to the number of bytes emitted.
625 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
627 /* Emit beginning of instruction */
628 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
630 /* Emit the offset */
632 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
633 *code_size = mono_arch_get_patch_offset (code) + 4;
634 #elif defined(TARGET_X86)
635 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
636 *code_size = mono_arch_get_patch_offset (code) + 4;
637 #elif defined(TARGET_ARM)
638 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
639 *code_size = mono_arch_get_patch_offset (code) + 4;
640 #elif defined(TARGET_POWERPC)
646 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
647 g_assert (code - buf == 8);
648 emit_bytes (acfg, buf, code - buf);
649 *code_size = code - buf;
652 g_assert_not_reached ();
659 * arch_emit_plt_entry:
661 * Emit code for the PLT entry with index INDEX.
664 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
666 #if defined(TARGET_X86)
667 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
669 #ifdef __native_client_codegen__
670 const guint8 kSizeOfNaClJmp = 11;
671 guint8 bytes[kSizeOfNaClJmp];
672 guint8 *pbytes = &bytes[0];
674 x86_jump_membase32 (pbytes, X86_EBX, offset);
675 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
676 /* four bytes of data, used by mono_arch_patch_plt_entry */
677 /* For Native Client, make this work with data embedded in push. */
678 emit_byte (acfg, 0x68); /* hide data in a push */
679 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
680 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
682 /* jmp *<offset>(%ebx) */
683 emit_byte (acfg, 0xff);
684 emit_byte (acfg, 0xa3);
685 emit_int32 (acfg, offset);
686 /* Used by mono_aot_get_plt_info_offset */
687 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
688 #endif /* __native_client_codegen__ */
689 #elif defined(TARGET_AMD64)
691 * We can't emit jumps because they are 32 bits only so they can't be patched.
692 * So we make indirect calls through GOT entries which are patched by the AOT
693 * loader to point to .Lpd entries.
695 /* jmpq *<offset>(%rip) */
696 emit_byte (acfg, '\xff');
697 emit_byte (acfg, '\x25');
698 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
699 /* Used by mono_aot_get_plt_info_offset */
700 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
701 #elif defined(TARGET_ARM)
706 * - optimize OP_AOTCONST implementation
707 * - optimize the PLT entries
708 * - optimize SWITCH AOT implementation
711 if (acfg->use_bin_writer && FALSE) {
712 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
713 /* We only emit 1 relocation since we implement it ourselves anyway */
714 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
715 /* FIXME: A 2 instruction encoding is sufficient in most cases */
716 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
717 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
718 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
719 emit_bytes (acfg, buf, code - buf);
720 /* Used by mono_aot_get_plt_info_offset */
721 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
723 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
724 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
725 emit_bytes (acfg, buf, code - buf);
726 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
727 /* Used by mono_aot_get_plt_info_offset */
728 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
731 * The plt_got_info_offset is computed automatically by
732 * mono_aot_get_plt_info_offset (), so no need to save it here.
734 #elif defined(TARGET_POWERPC)
735 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
737 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
738 g_assert (!acfg->use_bin_writer);
739 img_writer_emit_unset_mode (acfg->w);
740 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
741 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
742 fprintf (acfg->fp, "add 11, 11, 30\n");
743 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
744 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
745 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
746 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
748 fprintf (acfg->fp, "mtctr 11\n");
749 fprintf (acfg->fp, "bctr\n");
750 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
752 g_assert_not_reached ();
757 * arch_emit_specific_trampoline:
759 * Emit code for a specific trampoline. OFFSET is the offset of the first of
760 * two GOT slots which contain the generic trampoline address and the trampoline
761 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
764 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
767 * The trampolines created here are variations of the specific
768 * trampolines created in mono_arch_create_specific_trampoline (). The
770 * - the generic trampoline address is taken from a got slot.
771 * - the offset of the got slot where the trampoline argument is stored
772 * is embedded in the instruction stream, and the generic trampoline
773 * can load the argument by loading the offset, adding it to the
774 * address of the trampoline to get the address of the got slot, and
775 * loading the argument from there.
776 * - all the trampolines should be of the same length.
778 #if defined(TARGET_AMD64)
779 /* This should be exactly 16 bytes long */
781 /* call *<offset>(%rip) */
782 emit_byte (acfg, '\x41');
783 emit_byte (acfg, '\xff');
784 emit_byte (acfg, '\x15');
785 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
786 /* This should be relative to the start of the trampoline */
787 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
788 emit_zero_bytes (acfg, 5);
789 #elif defined(TARGET_ARM)
793 /* This should be exactly 20 bytes long */
796 ARM_PUSH (code, 0x5fff);
797 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
798 /* Load the value from the GOT */
799 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
801 ARM_BLX_REG (code, ARMREG_R1);
803 g_assert (code - buf == 16);
806 emit_bytes (acfg, buf, code - buf);
808 * Only one offset is needed, since the second one would be equal to the
811 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
812 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
813 #elif defined(TARGET_POWERPC)
820 g_assert (!acfg->use_bin_writer);
823 * PPC has no ip relative addressing, so we need to compute the address
824 * of the mscorlib got. That is slow and complex, so instead, we store it
825 * in the second got slot of every aot image. The caller already computed
826 * the address of its got and placed it into r30.
828 img_writer_emit_unset_mode (acfg->w);
829 /* Load mscorlib got address */
830 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
831 /* Load generic trampoline address */
832 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
833 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
834 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
835 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
836 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
838 fprintf (acfg->fp, "mtctr 11\n");
839 /* Load trampoline argument */
840 /* On ppc, we pass it normally to the generic trampoline */
841 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
842 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
843 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
844 /* Branch to generic trampoline */
845 fprintf (acfg->fp, "bctr\n");
847 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
848 *tramp_size = 10 * 4;
852 #elif defined(TARGET_X86)
856 /* Similar to the PPC code above */
858 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
860 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
861 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
862 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
866 /* Load mscorlib got address */
867 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
868 /* Push trampoline argument */
869 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
870 /* Load generic trampoline address */
871 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
872 /* Branch to generic trampoline */
873 x86_jump_reg (code, X86_ECX);
875 #ifdef __native_client_codegen__
877 /* emit nops to next 32 byte alignment */
878 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
879 while (code < (buf + a)) x86_nop(code);
882 emit_bytes (acfg, buf, code - buf);
884 *tramp_size = NACL_SIZE(17, kNaClAlignment);
885 g_assert (code - buf == *tramp_size);
887 g_assert_not_reached ();
892 * arch_emit_unbox_trampoline:
894 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
895 * CALL_TARGET is the symbol pointing to the native code of METHOD.
898 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
900 #if defined(TARGET_AMD64)
905 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
907 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
909 emit_bytes (acfg, buf, code - buf);
911 emit_byte (acfg, '\xe9');
912 emit_symbol_diff (acfg, call_target, ".", -4);
913 #elif defined(TARGET_X86)
920 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
922 emit_bytes (acfg, buf, code - buf);
925 emit_byte (acfg, '\xe9');
926 emit_symbol_diff (acfg, call_target, ".", -4);
927 #elif defined(TARGET_ARM)
933 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
935 emit_bytes (acfg, buf, code - buf);
937 if (acfg->use_bin_writer) {
944 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
945 emit_bytes (acfg, buf, 4);
947 fprintf (acfg->fp, "\n\tb %s\n", call_target);
949 #elif defined(TARGET_POWERPC)
952 g_assert (!acfg->use_bin_writer);
954 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
955 fprintf (acfg->fp, "\n\tb %s\n", call_target);
957 g_assert_not_reached ();
962 * arch_emit_static_rgctx_trampoline:
964 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
965 * two GOT slots which contain the rgctx argument, and the method to jump to.
966 * TRAMP_SIZE is set to the size of the emitted trampoline.
967 * These kinds of trampolines cannot be enumerated statically, since there could
968 * be one trampoline per method instantiation, so we emit the same code for all
969 * trampolines, and parameterize them using two GOT slots.
972 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
974 #if defined(TARGET_AMD64)
975 /* This should be exactly 13 bytes long */
978 /* mov <OFFSET>(%rip), %r10 */
979 emit_byte (acfg, '\x4d');
980 emit_byte (acfg, '\x8b');
981 emit_byte (acfg, '\x15');
982 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
984 /* jmp *<offset>(%rip) */
985 emit_byte (acfg, '\xff');
986 emit_byte (acfg, '\x25');
987 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
988 #elif defined(TARGET_ARM)
992 /* This should be exactly 24 bytes long */
995 /* Load rgctx value */
996 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
997 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
998 /* Load branch addr + branch */
999 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1000 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1002 g_assert (code - buf == 16);
1005 emit_bytes (acfg, buf, code - buf);
1006 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1007 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1008 #elif defined(TARGET_POWERPC)
1015 g_assert (!acfg->use_bin_writer);
1018 * PPC has no ip relative addressing, so we need to compute the address
1019 * of the mscorlib got. That is slow and complex, so instead, we store it
1020 * in the second got slot of every aot image. The caller already computed
1021 * the address of its got and placed it into r30.
1023 img_writer_emit_unset_mode (acfg->w);
1024 /* Load mscorlib got address */
1025 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1027 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1028 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1029 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1030 /* Load target address */
1031 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1032 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1033 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1034 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1035 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1036 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1038 fprintf (acfg->fp, "mtctr 11\n");
1039 /* Branch to the target address */
1040 fprintf (acfg->fp, "bctr\n");
1042 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1043 *tramp_size = 11 * 4;
1045 *tramp_size = 9 * 4;
1048 #elif defined(TARGET_X86)
1052 /* Similar to the PPC code above */
1054 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1057 /* Load mscorlib got address */
1058 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1060 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1061 /* Branch to the target address */
1062 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1064 #ifdef __native_client_codegen__
1066 /* emit nops to next 32 byte alignment */
1067 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1068 while (code < (buf + a)) x86_nop(code);
1072 emit_bytes (acfg, buf, code - buf);
1074 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1075 g_assert (code - buf == *tramp_size);
1077 g_assert_not_reached ();
1082 * arch_emit_imt_thunk:
1084 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1085 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1086 * key is the IMT key, and ptr holds the address of a memory location holding
1087 * the address to branch to if the IMT arg matches the key. The array is
1088 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1090 * TRAMP_SIZE is set to the size of the emitted trampoline.
1093 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1095 #if defined(TARGET_AMD64)
1099 code = buf = g_malloc (256);
1101 /* FIXME: Optimize this, i.e. use binary search etc. */
1102 /* Maybe move the body into a separate function (slower, but much smaller) */
1104 /* R11 is a free register */
1107 amd64_alu_membase_imm (code, X86_CMP, AMD64_R11, 0, 0);
1109 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1112 amd64_alu_membase_reg (code, X86_CMP, AMD64_R11, 0, MONO_ARCH_IMT_REG);
1114 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1117 amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, 2 * sizeof (gpointer));
1118 amd64_jump_code (code, labels [0]);
1121 mono_amd64_patch (labels [2], code);
1122 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, sizeof (gpointer), 8);
1123 amd64_jump_membase (code, AMD64_R11, 0);
1127 mono_amd64_patch (labels [1], code);
1128 x86_breakpoint (code);
1130 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 12345678, 8);
1132 /* mov <OFFSET>(%rip), %r11 */
1133 emit_byte (acfg, '\x4d');
1134 emit_byte (acfg, '\x8b');
1135 emit_byte (acfg, '\x1d');
1136 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1138 emit_bytes (acfg, buf, code - buf);
1140 *tramp_size = code - buf + 7;
1141 #elif defined(TARGET_X86)
1143 #ifdef __native_client_codegen__
1148 #ifdef __native_client_codegen__
1149 buf_alloc = g_malloc (256 + kNaClAlignment);
1150 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1152 code = buf = g_malloc (256);
1155 /* Allocate a temporary stack slot */
1156 x86_push_reg (code, X86_EAX);
1158 x86_push_reg (code, X86_EAX);
1160 /* Load mscorlib got address */
1161 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1163 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1166 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1168 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1171 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1173 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1176 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1177 x86_jump_code (code, labels [0]);
1180 mono_x86_patch (labels [2], code);
1181 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1182 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1183 /* Save the target address to the temporary stack location */
1184 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1186 x86_pop_reg (code, X86_EAX);
1187 /* Jump to the target address */
1192 mono_x86_patch (labels [1], code);
1193 x86_breakpoint (code);
1195 #ifdef __native_client_codegen__
1197 /* emit nops to next 32 byte alignment */
1198 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1199 while (code < (buf + a)) x86_nop(code);
1202 emit_bytes (acfg, buf, code - buf);
1204 *tramp_size = code - buf;
1205 #elif defined(TARGET_ARM)
1207 guint8 *code, *code2, *labels [16];
1211 /* The IMT method is in v5 */
1213 /* Need at least two free registers, plus a slot for storing the pc */
1214 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1216 /* Load the parameter from the GOT */
1217 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1218 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1221 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1222 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1224 ARM_B_COND (code, ARMCOND_EQ, 0);
1226 /* End-of-loop check */
1227 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1229 ARM_B_COND (code, ARMCOND_EQ, 0);
1232 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1235 arm_patch (labels [4], labels [1]);
1238 arm_patch (labels [2], code);
1239 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1240 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1241 /* Save it to the third stack slot */
1242 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1243 /* Restore the registers and branch */
1244 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1247 arm_patch (labels [3], code);
1252 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1254 emit_bytes (acfg, buf, code - buf);
1255 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1257 *tramp_size = code - buf + 4;
1258 #elif defined(TARGET_POWERPC)
1260 guint8 *code, *labels [16];
1264 /* Load the mscorlib got address */
1265 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1266 /* Load the parameter from the GOT */
1267 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1268 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1270 /* Load and check key */
1272 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1273 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1275 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1277 /* End-of-loop check */
1278 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1280 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1283 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1286 mono_ppc_patch (labels [4], labels [1]);
1289 mono_ppc_patch (labels [2], code);
1290 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1291 /* r11 now contains the value of the vtable slot */
1292 /* this is not a function descriptor on ppc64 */
1293 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1294 ppc_mtctr (code, ppc_r11);
1295 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1298 mono_ppc_patch (labels [3], code);
1302 *tramp_size = code - buf;
1304 emit_bytes (acfg, buf, code - buf);
1306 g_assert_not_reached ();
1311 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1313 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1314 /* Based on code generated by gcc */
1315 img_writer_emit_unset_mode (acfg->w);
1318 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1319 ".section .ctors,\"aw\",@progbits\n"
1323 ".section .opd,\"aw\"\n"
1326 ".long .%s,.TOC.@tocbase32\n"
1329 ".type .%s,@function\n"
1331 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1333 ".section .ctors,\"aw\",@progbits\n"
1337 ".section .opd,\"aw\"\n"
1340 ".long .%1$s,.TOC.@tocbase32\n"
1341 ".size %1$s,.-%1$s\n"
1343 ".type .%1$s,@function\n"
1345 ".%1$s:\n", symbol);
1356 "lis 3, .Lglobals@h\n"
1357 "ori 3, 3, .Lglobals@l\n"
1358 "bl .mono_aot_register_module\n"
1366 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1368 ".size .%s,.-.%s\n", symbol, symbol);
1371 ".size .%1$s,.-.%1$s\n", symbol);
1377 /* END OF ARCH SPECIFIC CODE */
1380 mono_get_field_token (MonoClassField *field)
1382 MonoClass *klass = field->parent;
1385 for (i = 0; i < klass->field.count; ++i) {
1386 if (field == &klass->fields [i])
1387 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1390 g_assert_not_reached ();
1395 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1399 //printf ("ENCODE: %d 0x%x.\n", value, value);
1402 * Same encoding as the one used in the metadata, extended to handle values
1403 * greater than 0x1fffffff.
1405 if ((value >= 0) && (value <= 127))
1407 else if ((value >= 0) && (value <= 16383)) {
1408 p [0] = 0x80 | (value >> 8);
1409 p [1] = value & 0xff;
1411 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1412 p [0] = (value >> 24) | 0xc0;
1413 p [1] = (value >> 16) & 0xff;
1414 p [2] = (value >> 8) & 0xff;
1415 p [3] = value & 0xff;
1420 p [1] = (value >> 24) & 0xff;
1421 p [2] = (value >> 16) & 0xff;
1422 p [3] = (value >> 8) & 0xff;
1423 p [4] = value & 0xff;
1431 stream_init (MonoDynamicStream *sh)
1434 sh->alloc_size = 4096;
1435 sh->data = g_malloc (4096);
1437 /* So offsets are > 0 */
1442 make_room_in_stream (MonoDynamicStream *stream, int size)
1444 if (size <= stream->alloc_size)
1447 while (stream->alloc_size <= size) {
1448 if (stream->alloc_size < 4096)
1449 stream->alloc_size = 4096;
1451 stream->alloc_size *= 2;
1454 stream->data = g_realloc (stream->data, stream->alloc_size);
1458 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1462 make_room_in_stream (stream, stream->index + len);
1463 memcpy (stream->data + stream->index, data, len);
1464 idx = stream->index;
1465 stream->index += len;
1472 * Add data to the binary blob inside the aot image. Returns the offset inside the
1473 * blob where the data was stored.
1476 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1478 if (acfg->blob.alloc_size == 0)
1479 stream_init (&acfg->blob);
1481 return add_stream_data (&acfg->blob, (char*)data, data_len);
1485 * emit_offset_table:
1487 * Emit a table of increasing offsets in a compact form using differential encoding.
1488 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1489 * group size, the more compact the table becomes, but the slower it becomes to compute
1490 * a given entry. Returns the size of the table.
1493 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1495 gint32 current_offset;
1496 int i, buf_size, ngroups, index_entry_size;
1498 guint32 *index_offsets;
1500 ngroups = (noffsets + (group_size - 1)) / group_size;
1502 index_offsets = g_new0 (guint32, ngroups);
1504 buf_size = noffsets * 4;
1505 p = buf = g_malloc0 (buf_size);
1508 for (i = 0; i < noffsets; ++i) {
1509 //printf ("D: %d -> %d\n", i, offsets [i]);
1510 if ((i % group_size) == 0) {
1511 index_offsets [i / group_size] = p - buf;
1512 /* Emit the full value for these entries */
1513 encode_value (offsets [i], p, &p);
1515 /* The offsets are allowed to be non-increasing */
1516 //g_assert (offsets [i] >= current_offset);
1517 encode_value (offsets [i] - current_offset, p, &p);
1519 current_offset = offsets [i];
1522 if (ngroups && index_offsets [ngroups - 1] < 65000)
1523 index_entry_size = 2;
1525 index_entry_size = 4;
1527 /* Emit the header */
1528 emit_int32 (acfg, noffsets);
1529 emit_int32 (acfg, group_size);
1530 emit_int32 (acfg, ngroups);
1531 emit_int32 (acfg, index_entry_size);
1533 /* Emit the index */
1534 for (i = 0; i < ngroups; ++i) {
1535 if (index_entry_size == 2)
1536 emit_int16 (acfg, index_offsets [i]);
1538 emit_int32 (acfg, index_offsets [i]);
1542 emit_bytes (acfg, buf, p - buf);
1544 return (int)(p - buf) + (ngroups * 4);
1548 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1552 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1556 index = g_hash_table_size (cfg->image_hash);
1557 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1558 g_ptr_array_add (cfg->image_table, image);
1564 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1567 MonoClass *k = NULL;
1569 /* FIXME: Search referenced images as well */
1570 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1571 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1576 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1577 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1583 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1588 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1589 * standard metadata encoding.
1592 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1596 if (klass->generic_class) {
1598 g_assert (klass->type_token);
1600 /* Find a typespec for a class if possible */
1601 token = find_typespec_for_class (acfg, klass);
1603 encode_value (token, p, &p);
1604 encode_value (get_image_index (acfg, acfg->image), p, &p);
1606 MonoClass *gclass = klass->generic_class->container_class;
1607 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1610 /* Encode it ourselves */
1612 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1613 encode_value (MONO_TYPE_GENERICINST, p, &p);
1614 encode_klass_ref (acfg, gclass, p, &p);
1615 encode_value (inst->type_argc, p, &p);
1616 for (i = 0; i < inst->type_argc; ++i)
1617 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1619 } else if (klass->type_token) {
1620 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1621 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1622 encode_value (get_image_index (acfg, klass->image), p, &p);
1623 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1624 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1625 g_assert (container);
1628 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1629 encode_value (klass->byval_arg.type, p, &p);
1631 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1633 encode_value (container->is_method, p, &p);
1634 if (container->is_method)
1635 encode_method_ref (acfg, container->owner.method, p, &p);
1637 encode_klass_ref (acfg, container->owner.klass, p, &p);
1640 g_assert (klass->rank > 0);
1641 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1642 encode_value (get_image_index (acfg, klass->image), p, &p);
1643 encode_value (klass->rank, p, &p);
1644 encode_klass_ref (acfg, klass->element_class, p, &p);
1650 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1652 guint32 token = mono_get_field_token (field);
1655 encode_klass_ref (cfg, field->parent, p, &p);
1656 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1657 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1662 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1666 MonoGenericInst *inst;
1668 /* Encode the context */
1669 inst = context->class_inst;
1670 encode_value (inst ? 1 : 0, p, &p);
1672 encode_value (inst->type_argc, p, &p);
1673 for (i = 0; i < inst->type_argc; ++i)
1674 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1676 inst = context->method_inst;
1677 encode_value (inst ? 1 : 0, p, &p);
1679 encode_value (inst->type_argc, p, &p);
1680 for (i = 0; i < inst->type_argc; ++i)
1681 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1687 #define MAX_IMAGE_INDEX 250
1690 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1692 guint32 image_index = get_image_index (acfg, method->klass->image);
1693 guint32 token = method->token;
1694 MonoJumpInfoToken *ji;
1699 * The encoding for most methods is as follows:
1700 * - image index encoded as a leb128
1701 * - token index encoded as a leb128
1702 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1703 * types of method encodings.
1706 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1708 /* Mark methods which can't use aot trampolines because they need the further
1709 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1711 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1712 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1713 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1716 * Some wrapper methods are shared using their signature, encode their
1717 * stringified signature instead.
1718 * FIXME: Optimize disk usage
1721 if (method->wrapper_type) {
1722 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1723 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1724 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1725 name = mono_aot_wrapper_name (method);
1726 } else if (mono_marshal_method_from_wrapper (method) != method) {
1727 /* Direct wrapper, encode it normally */
1729 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1732 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1733 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1734 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1736 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1737 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1738 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1740 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1741 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1742 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1748 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1749 strcpy ((char*)p, name);
1750 p += strlen (name) + 1;
1752 } else if (method->wrapper_type) {
1753 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1755 encode_value (method->wrapper_type, p, &p);
1757 switch (method->wrapper_type) {
1758 case MONO_WRAPPER_REMOTING_INVOKE:
1759 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1760 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1763 m = mono_marshal_method_from_wrapper (method);
1765 encode_method_ref (acfg, m, p, &p);
1768 case MONO_WRAPPER_PROXY_ISINST:
1769 case MONO_WRAPPER_LDFLD:
1770 case MONO_WRAPPER_LDFLDA:
1771 case MONO_WRAPPER_STFLD:
1772 case MONO_WRAPPER_ISINST: {
1773 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1774 encode_klass_ref (acfg, proxy_class, p, &p);
1777 case MONO_WRAPPER_LDFLD_REMOTE:
1778 case MONO_WRAPPER_STFLD_REMOTE:
1780 case MONO_WRAPPER_ALLOC: {
1781 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1783 /* The GC name is saved once in MonoAotFileInfo */
1784 g_assert (info->alloc_type != -1);
1785 encode_value (info->alloc_type, p, &p);
1788 case MONO_WRAPPER_WRITE_BARRIER:
1790 case MONO_WRAPPER_STELEMREF:
1792 case MONO_WRAPPER_UNKNOWN:
1793 if (strcmp (method->name, "FastMonitorEnter") == 0)
1794 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1795 else if (strcmp (method->name, "FastMonitorExit") == 0)
1796 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1798 g_assert_not_reached ();
1800 case MONO_WRAPPER_SYNCHRONIZED:
1801 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1802 case MONO_WRAPPER_RUNTIME_INVOKE: {
1805 m = mono_marshal_method_from_wrapper (method);
1807 g_assert (m != method);
1808 encode_method_ref (acfg, m, p, &p);
1811 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1812 if (!strcmp (method->name, "ElementAddr")) {
1813 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1816 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1817 encode_value (info->rank, p, &p);
1818 encode_value (info->elem_size, p, &p);
1820 g_assert_not_reached ();
1824 g_assert_not_reached ();
1826 } else if (mono_method_signature (method)->is_inflated) {
1828 * This is a generic method, find the original token which referenced it and
1830 * Obtain the token from information recorded by the JIT.
1832 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1834 image_index = get_image_index (acfg, ji->image);
1835 g_assert (image_index < MAX_IMAGE_INDEX);
1838 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1839 encode_value (image_index, p, &p);
1840 encode_value (token, p, &p);
1842 MonoMethod *declaring;
1843 MonoGenericContext *context = mono_method_get_context (method);
1845 g_assert (method->is_inflated);
1846 declaring = ((MonoMethodInflated*)method)->declaring;
1849 * This might be a non-generic method of a generic instance, which
1850 * doesn't have a token since the reference is generated by the JIT
1851 * like Nullable:Box/Unbox, or by generic sharing.
1854 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1855 /* Encode the klass */
1856 encode_klass_ref (acfg, method->klass, p, &p);
1857 /* Encode the method */
1858 image_index = get_image_index (acfg, method->klass->image);
1859 g_assert (image_index < MAX_IMAGE_INDEX);
1860 g_assert (declaring->token);
1861 token = declaring->token;
1862 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1863 encode_value (image_index, p, &p);
1864 encode_value (token, p, &p);
1865 encode_generic_context (acfg, context, p, &p);
1867 } else if (token == 0) {
1868 /* This might be a method of a constructed type like int[,].Set */
1869 /* Obtain the token from information recorded by the JIT */
1870 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1872 image_index = get_image_index (acfg, ji->image);
1873 g_assert (image_index < MAX_IMAGE_INDEX);
1876 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1877 encode_value (image_index, p, &p);
1878 encode_value (token, p, &p);
1881 g_assert (method->klass->rank);
1883 /* Encode directly */
1884 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1885 encode_klass_ref (acfg, method->klass, p, &p);
1886 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1887 encode_value (0, p, &p);
1888 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1889 encode_value (1, p, &p);
1890 else if (!strcmp (method->name, "Get"))
1891 encode_value (2, p, &p);
1892 else if (!strcmp (method->name, "Address"))
1893 encode_value (3, p, &p);
1894 else if (!strcmp (method->name, "Set"))
1895 encode_value (4, p, &p);
1897 g_assert_not_reached ();
1900 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1901 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1907 compare_patches (gconstpointer a, gconstpointer b)
1911 i = (*(MonoJumpInfo**)a)->ip.i;
1912 j = (*(MonoJumpInfo**)b)->ip.i;
1923 static G_GNUC_UNUSED char*
1924 patch_to_string (MonoJumpInfo *patch_info)
1928 str = g_string_new ("");
1930 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
1932 switch (patch_info->type) {
1933 case MONO_PATCH_INFO_VTABLE:
1934 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
1939 g_string_append_printf (str, ")");
1940 return g_string_free (str, FALSE);
1946 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1949 static inline gboolean
1950 is_plt_patch (MonoJumpInfo *patch_info)
1952 switch (patch_info->type) {
1953 case MONO_PATCH_INFO_METHOD:
1954 case MONO_PATCH_INFO_INTERNAL_METHOD:
1955 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1956 case MONO_PATCH_INFO_ICALL_ADDR:
1957 case MONO_PATCH_INFO_CLASS_INIT:
1958 case MONO_PATCH_INFO_RGCTX_FETCH:
1959 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1960 case MONO_PATCH_INFO_MONITOR_ENTER:
1961 case MONO_PATCH_INFO_MONITOR_EXIT:
1962 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1972 * Return the symbol identifying the plt entry PLT_OFFSET.
1975 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
1979 * The Apple linker reorganizes object files, so it doesn't like branches to local
1980 * labels, since those have no relocations.
1982 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
1984 return g_strdup_printf ("%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
1991 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
1993 static MonoPltEntry*
1994 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1998 if (!is_plt_patch (patch_info))
2001 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2003 // FIXME: This breaks the calculation of final_got_size
2004 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2006 * Allocate a separate PLT slot for each such patch, since some plt
2007 * entries will refer to the method itself, and some will refer to the
2014 MonoJumpInfo *new_ji;
2016 g_assert (!acfg->final_got_size);
2018 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2020 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2021 res->plt_offset = acfg->plt_offset;
2023 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2025 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2027 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2029 acfg->plt_offset ++;
2038 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2039 * JI could be found if it exists, otherwise allocates a new one.
2042 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2046 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2048 return got_offset - 1;
2050 got_offset = acfg->got_offset;
2051 acfg->got_offset ++;
2053 if (acfg->final_got_size)
2054 g_assert (got_offset < acfg->final_got_size);
2056 acfg->stats.got_slots ++;
2057 acfg->stats.got_slot_types [ji->type] ++;
2059 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2060 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2061 g_ptr_array_add (acfg->got_patches, ji);
2066 /* Add a method to the list of methods which need to be emitted */
2068 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2071 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2072 g_ptr_array_add (acfg->methods, method);
2073 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2074 acfg->nmethods = acfg->methods->len + 1;
2077 if (method->wrapper_type || extra)
2078 g_ptr_array_add (acfg->extra_methods, method);
2082 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2084 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2092 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2096 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2100 index = acfg->method_index;
2101 add_method_with_index (acfg, method, index, extra);
2103 /* FIXME: Fix quadratic behavior */
2104 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2106 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2108 acfg->method_index ++;
2114 add_method (MonoAotCompile *acfg, MonoMethod *method)
2116 return add_method_full (acfg, method, FALSE, 0);
2120 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2122 add_method_full (acfg, method, TRUE, 0);
2126 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2128 add_method_full (acfg, method, TRUE, depth);
2132 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2134 MonoAotCompile *acfg = user_data;
2135 MonoJitICallInfo *callinfo = value;
2136 MonoMethod *wrapper;
2142 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2143 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2146 add_method (acfg, wrapper);
2150 get_runtime_invoke_sig (MonoMethodSignature *sig)
2152 MonoMethodBuilder *mb;
2155 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2156 m = mono_mb_create_method (mb, sig, 16);
2157 return mono_marshal_get_runtime_invoke (m, FALSE);
2161 can_marshal_struct (MonoClass *klass)
2163 MonoClassField *field;
2164 gboolean can_marshal = TRUE;
2165 gpointer iter = NULL;
2167 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2170 /* Only allow a few field types to avoid asserts in the marshalling code */
2171 while ((field = mono_class_get_fields (klass, &iter))) {
2172 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2175 switch (field->type->type) {
2180 case MONO_TYPE_BOOLEAN:
2183 case MONO_TYPE_CHAR:
2191 case MONO_TYPE_STRING:
2193 case MONO_TYPE_VALUETYPE:
2194 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2195 can_marshal = FALSE;
2198 can_marshal = FALSE;
2204 /* Its hard to compute whenever these can be marshalled or not */
2205 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2212 add_wrappers (MonoAotCompile *acfg)
2214 MonoMethod *method, *m;
2216 MonoMethodSignature *sig, *csig;
2220 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2221 * so there is only one wrapper of a given type, or inlining their contents into their
2226 * FIXME: This depends on the fact that different wrappers have different
2230 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2232 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2233 gboolean skip = FALSE;
2235 method = mono_get_method (acfg->image, token, NULL);
2237 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2238 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2239 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2242 if (method->is_generic || method->klass->generic_container)
2245 /* Skip methods which can not be handled by get_runtime_invoke () */
2246 sig = mono_method_signature (method);
2247 if ((sig->ret->type == MONO_TYPE_PTR) ||
2248 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2251 for (j = 0; j < sig->param_count; j++) {
2252 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2256 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2257 if (!method->klass->contextbound) {
2258 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2259 gboolean has_nullable = FALSE;
2261 for (j = 0; j < sig->param_count; j++) {
2262 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2263 has_nullable = TRUE;
2266 if (info && !has_nullable) {
2267 /* Supported by the dynamic runtime-invoke wrapper */
2275 //printf ("%s\n", mono_method_full_name (method, TRUE));
2276 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2280 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2281 #ifdef MONO_ARCH_HAVE_TLS_GET
2282 MonoMethodDesc *desc;
2283 MonoMethod *orig_method;
2287 /* Runtime invoke wrappers */
2289 /* void runtime-invoke () [.cctor] */
2290 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2291 csig->ret = &mono_defaults.void_class->byval_arg;
2292 add_method (acfg, get_runtime_invoke_sig (csig));
2294 /* void runtime-invoke () [Finalize] */
2295 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2297 csig->ret = &mono_defaults.void_class->byval_arg;
2298 add_method (acfg, get_runtime_invoke_sig (csig));
2300 /* void runtime-invoke (string) [exception ctor] */
2301 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2303 csig->ret = &mono_defaults.void_class->byval_arg;
2304 csig->params [0] = &mono_defaults.string_class->byval_arg;
2305 add_method (acfg, get_runtime_invoke_sig (csig));
2307 /* void runtime-invoke (string, string) [exception ctor] */
2308 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2310 csig->ret = &mono_defaults.void_class->byval_arg;
2311 csig->params [0] = &mono_defaults.string_class->byval_arg;
2312 csig->params [1] = &mono_defaults.string_class->byval_arg;
2313 add_method (acfg, get_runtime_invoke_sig (csig));
2315 /* string runtime-invoke () [Exception.ToString ()] */
2316 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2318 csig->ret = &mono_defaults.string_class->byval_arg;
2319 add_method (acfg, get_runtime_invoke_sig (csig));
2321 /* void runtime-invoke (string, Exception) [exception ctor] */
2322 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2324 csig->ret = &mono_defaults.void_class->byval_arg;
2325 csig->params [0] = &mono_defaults.string_class->byval_arg;
2326 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2327 add_method (acfg, get_runtime_invoke_sig (csig));
2329 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2330 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2332 csig->ret = &(mono_class_from_name (
2333 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2334 csig->params [0] = &mono_defaults.string_class->byval_arg;
2335 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2336 add_method (acfg, get_runtime_invoke_sig (csig));
2338 /* runtime-invoke used by finalizers */
2339 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2341 /* This is used by mono_runtime_capture_context () */
2342 method = mono_get_context_capture_method ();
2344 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2346 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2347 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2350 /* JIT icall wrappers */
2351 /* FIXME: locking */
2352 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2355 add_method (acfg, mono_marshal_get_stelemref ());
2357 #ifdef MONO_ARCH_HAVE_TLS_GET
2358 /* Managed Allocators */
2359 nallocators = mono_gc_get_managed_allocator_types ();
2360 for (i = 0; i < nallocators; ++i) {
2361 m = mono_gc_get_managed_allocator_by_type (i);
2363 add_method (acfg, m);
2366 /* Monitor Enter/Exit */
2367 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2368 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2369 g_assert (orig_method);
2370 mono_method_desc_free (desc);
2371 method = mono_monitor_get_fast_path (orig_method);
2373 add_method (acfg, method);
2375 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2376 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2377 g_assert (orig_method);
2378 mono_method_desc_free (desc);
2379 method = mono_monitor_get_fast_path (orig_method);
2381 add_method (acfg, method);
2386 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2387 * we use the original method instead at runtime.
2388 * Since full-aot doesn't support remoting, this is not a problem.
2391 /* remoting-invoke wrappers */
2392 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2393 MonoMethodSignature *sig;
2395 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2396 method = mono_get_method (acfg->image, token, NULL);
2398 sig = mono_method_signature (method);
2400 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2401 m = mono_marshal_get_remoting_invoke_with_check (method);
2403 add_method (acfg, m);
2408 /* delegate-invoke wrappers */
2409 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2412 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2413 klass = mono_class_get (acfg->image, token);
2415 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2416 method = mono_get_delegate_invoke (klass);
2418 m = mono_marshal_get_delegate_invoke (method, NULL);
2420 add_method (acfg, m);
2422 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2423 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2425 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2426 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2430 /* Synchronized wrappers */
2431 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2432 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2433 method = mono_get_method (acfg->image, token, NULL);
2435 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2436 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2439 /* pinvoke wrappers */
2440 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2442 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2444 method = mono_get_method (acfg->image, token, NULL);
2446 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2447 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2448 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2452 /* native-to-managed wrappers */
2453 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2455 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2456 MonoCustomAttrInfo *cattr;
2459 method = mono_get_method (acfg->image, token, NULL);
2462 * Only generate native-to-managed wrappers for methods which have an
2463 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2464 * name to avoid defining a new assembly to contain it.
2466 cattr = mono_custom_attrs_from_method (method);
2469 for (j = 0; j < cattr->num_attrs; ++j)
2470 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2472 if (j < cattr->num_attrs) {
2473 MonoCustomAttrEntry *e = &cattr->attrs [j];
2474 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2475 const char *p = (const char*)e->data;
2481 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2483 g_assert (sig->param_count == 1);
2484 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2487 * Decode the cattr manually since we can't create objects
2488 * during aot compilation.
2494 /* From load_cattr_value () in reflection.c */
2495 slen = mono_metadata_decode_value (p, &p);
2496 n = g_memdup (p, slen + 1);
2498 t = mono_reflection_type_from_name (n, acfg->image);
2502 klass = mono_class_from_mono_type (t);
2503 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2505 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2509 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2510 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2511 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2515 /* StructureToPtr/PtrToStructure wrappers */
2516 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2519 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2520 klass = mono_class_get (acfg->image, token);
2522 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2523 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2524 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2530 has_type_vars (MonoClass *klass)
2532 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2535 return has_type_vars (klass->element_class);
2536 if (klass->generic_class) {
2537 MonoGenericContext *context = &klass->generic_class->context;
2538 if (context->class_inst) {
2541 for (i = 0; i < context->class_inst->type_argc; ++i)
2542 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2550 method_has_type_vars (MonoMethod *method)
2552 if (has_type_vars (method->klass))
2555 if (method->is_inflated) {
2556 MonoGenericContext *context = mono_method_get_context (method);
2557 if (context->method_inst) {
2560 for (i = 0; i < context->method_inst->type_argc; ++i)
2561 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2568 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2571 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2573 add_generic_class_with_depth (acfg, klass, 0);
2577 * add_generic_class:
2579 * Add all methods of a generic class.
2582 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2587 mono_class_init (klass);
2589 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2592 if (has_type_vars (klass))
2595 if (!klass->generic_class && !klass->rank)
2599 while ((method = mono_class_get_methods (klass, &iter))) {
2600 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2604 if (method->is_generic)
2609 * FIXME: Instances which are referenced by these methods are not added,
2610 * for example Array.Resize<int> for List<int>.Add ().
2612 add_extra_method_with_depth (acfg, method, depth);
2615 if (klass->delegate) {
2616 method = mono_get_delegate_invoke (klass);
2618 method = mono_marshal_get_delegate_invoke (method, NULL);
2620 add_method (acfg, method);
2624 * For ICollection<T>, add instances of the helper methods
2625 * in Array, since a T[] could be cast to ICollection<T>.
2627 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2628 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2629 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2630 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2634 if (!strcmp (klass->name, "IEnumerator`1"))
2635 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2637 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2639 /* Add the T[]/InternalEnumerator class */
2640 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2644 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2645 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2649 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2650 add_generic_class (acfg, nclass);
2654 while ((method = mono_class_get_methods (array_class, &iter))) {
2655 if (strstr (method->name, name_prefix)) {
2656 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2657 add_extra_method_with_depth (acfg, m, depth);
2661 g_free (name_prefix);
2664 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2665 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2666 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2667 MonoClass *icomparable, *gcomparer;
2668 MonoGenericContext ctx;
2669 MonoType *args [16];
2671 memset (&ctx, 0, sizeof (ctx));
2673 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2674 g_assert (icomparable);
2675 args [0] = &tclass->byval_arg;
2676 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2678 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2679 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2680 g_assert (gcomparer);
2681 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2687 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2690 MonoGenericContext ctx;
2691 MonoType *args [16];
2693 memset (&ctx, 0, sizeof (ctx));
2695 for (i = 0; i < ninsts; ++i) {
2696 args [0] = insts [i];
2697 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2698 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2703 * add_generic_instances:
2705 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2708 add_generic_instances (MonoAotCompile *acfg)
2713 MonoMethodHeader *header;
2714 MonoMethodSignature *sig;
2715 MonoGenericContext *context;
2717 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2718 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2719 method = mono_get_method (acfg->image, token, NULL);
2721 if (method->klass->image != acfg->image)
2724 context = mono_method_get_context (method);
2726 if (context && ((context->class_inst && context->class_inst->is_open)))
2730 * For open methods, create an instantiation which can be passed to the JIT.
2731 * FIXME: Handle class_inst as well.
2733 if (context && context->method_inst && context->method_inst->is_open) {
2734 MonoGenericContext shared_context;
2735 MonoGenericInst *inst;
2736 MonoType **type_argv;
2738 MonoMethod *declaring_method;
2739 gboolean supported = TRUE;
2741 /* Check that the context doesn't contain open constructed types */
2742 if (context->class_inst) {
2743 inst = context->class_inst;
2744 for (i = 0; i < inst->type_argc; ++i) {
2745 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)
2747 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2751 if (context->method_inst) {
2752 inst = context->method_inst;
2753 for (i = 0; i < inst->type_argc; ++i) {
2754 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)
2756 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2764 memset (&shared_context, 0, sizeof (MonoGenericContext));
2766 inst = context->class_inst;
2768 type_argv = g_new0 (MonoType*, inst->type_argc);
2769 for (i = 0; i < inst->type_argc; ++i) {
2770 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)
2771 type_argv [i] = &mono_defaults.object_class->byval_arg;
2773 type_argv [i] = inst->type_argv [i];
2776 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2780 inst = context->method_inst;
2782 type_argv = g_new0 (MonoType*, inst->type_argc);
2783 for (i = 0; i < inst->type_argc; ++i) {
2784 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)
2785 type_argv [i] = &mono_defaults.object_class->byval_arg;
2787 type_argv [i] = inst->type_argv [i];
2790 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2794 if (method->is_generic || method->klass->generic_container)
2795 declaring_method = method;
2797 declaring_method = mono_method_get_declaring_generic_method (method);
2799 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2803 * If the method is fully sharable, it was already added in place of its
2804 * generic definition.
2806 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2810 * FIXME: Partially shared methods are not shared here, so we end up with
2811 * many identical methods.
2813 add_extra_method (acfg, method);
2816 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2819 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2821 klass = mono_class_get (acfg->image, token);
2822 if (!klass || klass->rank)
2825 add_generic_class (acfg, klass);
2828 /* Add types of args/locals */
2829 for (i = 0; i < acfg->methods->len; ++i) {
2832 method = g_ptr_array_index (acfg->methods, i);
2834 sig = mono_method_signature (method);
2837 for (j = 0; j < sig->param_count; ++j)
2838 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2839 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2842 header = mono_method_get_header (method);
2845 for (j = 0; j < header->num_locals; ++j)
2846 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2847 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2851 if (acfg->image == mono_defaults.corlib) {
2853 MonoType *insts [256];
2856 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2857 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2858 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2859 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2860 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2861 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2862 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2863 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2864 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2865 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2866 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2867 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2869 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2870 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2872 add_instances_of (acfg, klass, insts, ninsts);
2873 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2875 add_instances_of (acfg, klass, insts, ninsts);
2877 /* Add instances of the array generic interfaces for primitive types */
2878 /* This will add instances of the InternalArray_ helper methods in Array too */
2879 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2881 add_instances_of (acfg, klass, insts, ninsts);
2882 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2884 add_instances_of (acfg, klass, insts, ninsts);
2885 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2887 add_instances_of (acfg, klass, insts, ninsts);
2890 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2891 * used for all instances of GetGenericValueImpl by the AOT runtime.
2894 MonoGenericContext ctx;
2895 MonoType *args [16];
2896 MonoMethod *get_method;
2897 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2899 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2902 memset (&ctx, 0, sizeof (ctx));
2903 args [0] = &mono_defaults.object_class->byval_arg;
2904 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2905 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2912 * is_direct_callable:
2914 * Return whenever the method identified by JI is directly callable without
2915 * going through the PLT.
2918 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2920 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2921 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2923 gboolean direct_callable = TRUE;
2925 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2926 direct_callable = FALSE;
2927 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2928 // FIXME: Maybe call the wrapper directly ?
2929 direct_callable = FALSE;
2931 if (direct_callable)
2940 * emit_and_reloc_code:
2942 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2943 * is true, calls are made through the GOT too. This is used for emitting trampolines
2944 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2945 * since trampolines are needed to make PTL work.
2948 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2950 int i, pindex, start_index, method_index;
2952 MonoJumpInfo *patch_info;
2953 MonoMethodHeader *header;
2954 gboolean skip, direct_call;
2956 char direct_call_target [128];
2959 header = mono_method_get_header (method);
2961 method_index = get_method_index (acfg, method);
2964 /* Collect and sort relocations */
2965 patches = g_ptr_array_new ();
2966 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2967 g_ptr_array_add (patches, patch_info);
2968 g_ptr_array_sort (patches, compare_patches);
2971 for (i = 0; i < code_len; i++) {
2973 for (pindex = start_index; pindex < patches->len; ++pindex) {
2974 patch_info = g_ptr_array_index (patches, pindex);
2975 if (patch_info->ip.i >= i)
2979 #ifdef MONO_ARCH_AOT_SUPPORTED
2981 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2982 start_index = pindex;
2984 switch (patch_info->type) {
2985 case MONO_PATCH_INFO_NONE:
2987 case MONO_PATCH_INFO_GOT_OFFSET: {
2990 arch_emit_got_offset (acfg, code + i, &code_size);
2993 patch_info->type = MONO_PATCH_INFO_NONE;
2998 * If this patch is a call, try emitting a direct call instead of
2999 * through a PLT entry. This is possible if the called method is in
3000 * the same assembly and requires no initialization.
3002 direct_call = FALSE;
3003 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3004 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3005 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3006 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3008 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3009 patch_info->type = MONO_PATCH_INFO_NONE;
3010 acfg->stats.direct_calls ++;
3013 acfg->stats.all_calls ++;
3016 if (!got_only && !direct_call) {
3017 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3019 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3021 sprintf (direct_call_target, "%s", plt_entry->symbol);
3023 /* Nullify the patch */
3024 patch_info->type = MONO_PATCH_INFO_NONE;
3031 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3036 got_slot = get_got_offset (acfg, patch_info);
3038 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3045 #endif /* MONO_ARCH_AOT_SUPPORTED */
3048 /* Find next patch */
3050 for (pindex = start_index; pindex < patches->len; ++pindex) {
3051 patch_info = g_ptr_array_index (patches, pindex);
3052 if (patch_info->ip.i >= i)
3056 /* Try to emit multiple bytes at once */
3057 if (pindex < patches->len && patch_info->ip.i > i) {
3058 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3059 i = patch_info->ip.i - 1;
3061 emit_bytes (acfg, code + i, 1);
3070 * Modify SYMBOL so it only includes characters permissible in symbols.
3073 sanitize_symbol (char *symbol)
3075 int i, len = strlen (symbol);
3077 for (i = 0; i < len; ++i)
3078 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3083 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3085 char *name1, *name2, *cached;
3086 int i, j, len, count;
3088 name1 = mono_method_full_name (method, TRUE);
3089 len = strlen (name1);
3090 name2 = malloc (strlen (prefix) + len + 16);
3091 memcpy (name2, prefix, strlen (prefix));
3092 j = strlen (prefix);
3093 for (i = 0; i < len; ++i) {
3094 if (isalnum (name1 [i])) {
3095 name2 [j ++] = name1 [i];
3096 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3098 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3101 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3110 while (g_hash_table_lookup (cache, name2)) {
3111 sprintf (name2 + j, "_%d", count);
3115 cached = g_strdup (name2);
3116 g_hash_table_insert (cache, cached, cached);
3122 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3127 char *debug_sym = NULL;
3129 int func_alignment = AOT_FUNC_ALIGNMENT;
3130 MonoMethodHeader *header;
3132 method = cfg->orig_method;
3133 code = cfg->native_code;
3134 header = cfg->header;
3136 method_index = get_method_index (acfg, method);
3138 /* Make the labels local */
3139 sprintf (symbol, "%s", cfg->asm_symbol);
3141 emit_section_change (acfg, ".text", 0);
3142 emit_alignment (acfg, func_alignment);
3143 emit_label (acfg, symbol);
3145 if (acfg->aot_opts.write_symbols) {
3147 * Write a C style symbol for every method, this has two uses:
3148 * - it works on platforms where the dwarf debugging info is not
3150 * - it allows the setting of breakpoints of aot-ed methods.
3152 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3154 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3155 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3156 emit_label (acfg, debug_sym);
3159 if (cfg->verbose_level > 0)
3160 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3162 acfg->stats.code_size += cfg->code_len;
3164 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3166 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3170 if (acfg->aot_opts.write_symbols) {
3171 emit_symbol_size (acfg, debug_sym, ".");
3175 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3176 emit_label (acfg, symbol);
3182 * Encode PATCH_INFO into its disk representation.
3185 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3189 switch (patch_info->type) {
3190 case MONO_PATCH_INFO_NONE:
3192 case MONO_PATCH_INFO_IMAGE:
3193 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3195 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3196 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3198 case MONO_PATCH_INFO_METHOD_REL:
3199 encode_value ((gint)patch_info->data.offset, p, &p);
3201 case MONO_PATCH_INFO_SWITCH: {
3202 gpointer *table = (gpointer *)patch_info->data.table->table;
3205 encode_value (patch_info->data.table->table_size, p, &p);
3206 for (k = 0; k < patch_info->data.table->table_size; k++)
3207 encode_value ((int)(gssize)table [k], p, &p);
3210 case MONO_PATCH_INFO_METHODCONST:
3211 case MONO_PATCH_INFO_METHOD:
3212 case MONO_PATCH_INFO_METHOD_JUMP:
3213 case MONO_PATCH_INFO_ICALL_ADDR:
3214 case MONO_PATCH_INFO_METHOD_RGCTX:
3215 encode_method_ref (acfg, patch_info->data.method, p, &p);
3217 case MONO_PATCH_INFO_INTERNAL_METHOD:
3218 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3219 guint32 len = strlen (patch_info->data.name);
3221 encode_value (len, p, &p);
3223 memcpy (p, patch_info->data.name, len);
3228 case MONO_PATCH_INFO_LDSTR: {
3229 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3230 guint32 token = patch_info->data.token->token;
3231 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3232 encode_value (image_index, p, &p);
3233 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3236 case MONO_PATCH_INFO_RVA:
3237 case MONO_PATCH_INFO_DECLSEC:
3238 case MONO_PATCH_INFO_LDTOKEN:
3239 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3240 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3241 encode_value (patch_info->data.token->token, p, &p);
3242 encode_value (patch_info->data.token->has_context, p, &p);
3243 if (patch_info->data.token->has_context)
3244 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3246 case MONO_PATCH_INFO_EXC_NAME: {
3247 MonoClass *ex_class;
3250 mono_class_from_name (mono_defaults.exception_class->image,
3251 "System", patch_info->data.target);
3252 g_assert (ex_class);
3253 encode_klass_ref (acfg, ex_class, p, &p);
3256 case MONO_PATCH_INFO_R4:
3257 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3259 case MONO_PATCH_INFO_R8:
3260 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3261 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3263 case MONO_PATCH_INFO_VTABLE:
3264 case MONO_PATCH_INFO_CLASS:
3265 case MONO_PATCH_INFO_IID:
3266 case MONO_PATCH_INFO_ADJUSTED_IID:
3267 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3269 case MONO_PATCH_INFO_CLASS_INIT:
3270 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3271 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3273 case MONO_PATCH_INFO_FIELD:
3274 case MONO_PATCH_INFO_SFLDA:
3275 encode_field_info (acfg, patch_info->data.field, p, &p);
3277 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3279 case MONO_PATCH_INFO_RGCTX_FETCH: {
3280 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3282 encode_method_ref (acfg, entry->method, p, &p);
3283 encode_value (entry->in_mrgctx, p, &p);
3284 encode_value (entry->info_type, p, &p);
3285 encode_value (entry->data->type, p, &p);
3286 encode_patch (acfg, entry->data, p, &p);
3289 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3290 case MONO_PATCH_INFO_MONITOR_ENTER:
3291 case MONO_PATCH_INFO_MONITOR_EXIT:
3292 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3294 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3295 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3296 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3299 g_warning ("unable to handle jump info %d", patch_info->type);
3300 g_assert_not_reached ();
3307 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3310 guint32 pindex, offset;
3311 MonoJumpInfo *patch_info;
3313 encode_value (n_patches, p, &p);
3315 for (pindex = 0; pindex < patches->len; ++pindex) {
3316 patch_info = g_ptr_array_index (patches, pindex);
3318 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3322 offset = get_got_offset (acfg, patch_info);
3323 encode_value (offset, p, &p);
3330 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3334 int pindex, buf_size, n_patches;
3337 MonoJumpInfo *patch_info;
3338 MonoMethodHeader *header;
3339 guint32 method_index;
3341 guint32 first_got_offset;
3343 method = cfg->orig_method;
3344 code = cfg->native_code;
3345 header = mono_method_get_header (method);
3347 method_index = get_method_index (acfg, method);
3349 /* Sort relocations */
3350 patches = g_ptr_array_new ();
3351 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3352 g_ptr_array_add (patches, patch_info);
3353 g_ptr_array_sort (patches, compare_patches);
3355 first_got_offset = acfg->cfgs [method_index]->got_offset;
3357 /**********************/
3358 /* Encode method info */
3359 /**********************/
3361 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3362 p = buf = g_malloc (buf_size);
3364 if (mono_class_get_cctor (method->klass))
3365 encode_klass_ref (acfg, method->klass, p, &p);
3367 /* Not needed when loading the method */
3368 encode_value (0, p, &p);
3371 if (cfg->opt & MONO_OPT_SHARED) {
3372 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3373 for (l = cfg->ldstr_list; l; l = l->next) {
3374 encode_value ((long)l->data, p, &p);
3378 /* Used only in shared mode */
3379 g_assert (!cfg->ldstr_list);
3382 for (pindex = 0; pindex < patches->len; ++pindex) {
3383 patch_info = g_ptr_array_index (patches, pindex);
3385 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3386 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3387 patch_info->type = MONO_PATCH_INFO_NONE;
3392 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3393 /* Stored in a GOT slot initialized at module load time */
3394 patch_info->type = MONO_PATCH_INFO_NONE;
3398 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3399 /* Stored in a GOT slot initialized at module load time */
3400 patch_info->type = MONO_PATCH_INFO_NONE;
3404 if (is_plt_patch (patch_info)) {
3405 /* Calls are made through the PLT */
3406 patch_info->type = MONO_PATCH_INFO_NONE;
3414 g_assert (cfg->has_got_slots);
3416 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3418 acfg->stats.info_size += p - buf;
3420 g_assert (p - buf < buf_size);
3422 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3427 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3429 guint32 cache_index;
3432 /* Reuse the unwind module to canonize and store unwind info entries */
3433 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3435 /* Use +/- 1 to distinguish 0s from missing entries */
3436 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3444 * It would be easier to use assembler symbols, but the caller needs an
3447 offset = acfg->unwind_info_offset;
3448 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3449 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3452 encode_value (encoded_len, p, &p);
3454 acfg->unwind_info_offset += encoded_len + (p - buf);
3460 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3463 int i, k, buf_size, method_index;
3464 guint32 debug_info_size;
3466 MonoMethodHeader *header;
3467 guint8 *p, *buf, *debug_info;
3468 MonoJitInfo *jinfo = cfg->jit_info;
3470 gboolean use_unwind_ops = FALSE;
3471 MonoSeqPointInfo *seq_points;
3473 method = cfg->orig_method;
3474 code = cfg->native_code;
3475 header = cfg->header;
3477 method_index = get_method_index (acfg, method);
3479 if (!acfg->aot_opts.nodebug) {
3480 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3483 debug_info_size = 0;
3486 seq_points = cfg->seq_point_info;
3488 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3489 p = buf = g_malloc (buf_size);
3491 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3492 use_unwind_ops = cfg->unwind_ops != NULL;
3495 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);
3497 encode_value (flags, p, &p);
3499 if (use_unwind_ops) {
3500 guint32 encoded_len;
3504 * This is a duplicate of the data in the .debug_frame section, but that
3505 * section cannot be accessed using the dl interface.
3507 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3508 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3511 encode_value (jinfo->used_regs, p, &p);
3514 /*Encode the number of holes before the number of clauses to make decoding easier*/
3515 if (jinfo->has_try_block_holes) {
3516 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3517 encode_value (table->num_holes, p, &p);
3520 /* Exception table */
3521 if (cfg->compile_llvm) {
3523 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3524 * since the information is only available to llc. Instead, we let llc save the data
3525 * into the LSDA, and read it from there at runtime.
3527 /* The assembly might be CIL stripped so emit the data ourselves */
3528 if (header->num_clauses)
3529 encode_value (header->num_clauses, p, &p);
3531 for (k = 0; k < header->num_clauses; ++k) {
3532 MonoExceptionClause *clause;
3534 clause = &header->clauses [k];
3536 encode_value (clause->flags, p, &p);
3537 if (clause->data.catch_class) {
3538 encode_value (1, p, &p);
3539 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3541 encode_value (0, p, &p);
3544 /* Emit a list of nesting clauses */
3545 for (i = 0; i < header->num_clauses; ++i) {
3547 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3549 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3551 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3552 encode_value (i, p, &p);
3554 encode_value (-1, p, &p);
3557 if (jinfo->num_clauses)
3558 encode_value (jinfo->num_clauses, p, &p);
3560 for (k = 0; k < jinfo->num_clauses; ++k) {
3561 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3563 encode_value (ei->flags, p, &p);
3564 encode_value (ei->exvar_offset, p, &p);
3566 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3567 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3569 if (ei->data.catch_class) {
3570 encode_value (1, p, &p);
3571 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3573 encode_value (0, p, &p);
3577 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3578 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3579 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3583 if (jinfo->has_generic_jit_info) {
3584 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3586 if (!cfg->compile_llvm) {
3587 encode_value (gi->has_this ? 1 : 0, p, &p);
3588 encode_value (gi->this_reg, p, &p);
3589 encode_value (gi->this_offset, p, &p);
3593 * Need to encode jinfo->method too, since it is not equal to 'method'
3594 * when using generic sharing.
3596 encode_method_ref (acfg, jinfo->method, p, &p);
3599 if (jinfo->has_try_block_holes) {
3600 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3601 for (i = 0; i < table->num_holes; ++i) {
3602 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3603 encode_value (hole->clause, p, &p);
3604 encode_value (hole->length, p, &p);
3605 encode_value (hole->offset, p, &p);
3610 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3612 encode_value (seq_points->len, p, &p);
3613 last_il_offset = last_native_offset = 0;
3614 for (i = 0; i < seq_points->len; ++i) {
3615 SeqPoint *sp = &seq_points->seq_points [i];
3616 il_offset = sp->il_offset;
3617 native_offset = sp->native_offset;
3618 encode_value (il_offset - last_il_offset, p, &p);
3619 encode_value (native_offset - last_native_offset, p, &p);
3620 last_il_offset = il_offset;
3621 last_native_offset = native_offset;
3623 encode_value (sp->next_len, p, &p);
3624 for (j = 0; j < sp->next_len; ++j)
3625 encode_value (sp->next [j], p, &p);
3630 g_assert (debug_info_size < buf_size);
3632 encode_value (debug_info_size, p, &p);
3633 if (debug_info_size) {
3634 memcpy (p, debug_info, debug_info_size);
3635 p += debug_info_size;
3636 g_free (debug_info);
3639 acfg->stats.ex_info_size += p - buf;
3641 g_assert (p - buf < buf_size);
3644 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3649 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3651 MonoClass *klass = mono_class_get (acfg->image, token);
3653 int i, buf_size, res;
3654 gboolean no_special_static, cant_encode;
3655 gpointer iter = NULL;
3660 p = buf = g_malloc (buf_size);
3662 /* Mark as unusable */
3663 encode_value (-1, p, &p);
3665 res = add_to_blob (acfg, buf, p - buf);
3671 buf_size = 10240 + (klass->vtable_size * 16);
3672 p = buf = g_malloc (buf_size);
3676 mono_class_init (klass);
3678 mono_class_get_nested_types (klass, &iter);
3679 g_assert (klass->nested_classes_inited);
3681 mono_class_setup_vtable (klass);
3684 * Emit all the information which is required for creating vtables so
3685 * the runtime does not need to create the MonoMethod structures which
3686 * take up a lot of space.
3689 no_special_static = !mono_class_has_special_static_fields (klass);
3691 /* Check whenever we have enough info to encode the vtable */
3692 cant_encode = FALSE;
3693 for (i = 0; i < klass->vtable_size; ++i) {
3694 MonoMethod *cm = klass->vtable [i];
3696 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3700 if (klass->generic_container || cant_encode) {
3701 encode_value (-1, p, &p);
3703 encode_value (klass->vtable_size, p, &p);
3704 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);
3705 if (klass->has_cctor)
3706 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3707 if (klass->has_finalize)
3708 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3710 encode_value (klass->instance_size, p, &p);
3711 encode_value (mono_class_data_size (klass), p, &p);
3712 encode_value (klass->packing_size, p, &p);
3713 encode_value (klass->min_align, p, &p);
3715 for (i = 0; i < klass->vtable_size; ++i) {
3716 MonoMethod *cm = klass->vtable [i];
3719 encode_method_ref (acfg, cm, p, &p);
3721 encode_value (0, p, &p);
3725 acfg->stats.class_info_size += p - buf;
3727 g_assert (p - buf < buf_size);
3728 res = add_to_blob (acfg, buf, p - buf);
3735 * Calls made from AOTed code are routed through a table of jumps similar to the
3736 * ELF PLT (Program Linkage Table). The differences are the following:
3737 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3738 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3739 * jumps. This means the jumps need to be patched when the address of the callee is
3740 * known. Initially the PLT entries jump to code which transfers control to the
3741 * AOT runtime through the first PLT entry.
3744 emit_plt (MonoAotCompile *acfg)
3750 cache = g_hash_table_new (g_str_hash, g_str_equal);
3753 sprintf (symbol, "plt");
3755 emit_section_change (acfg, ".text", 0);
3756 emit_global (acfg, symbol, TRUE);
3757 emit_alignment (acfg, 16);
3758 emit_label (acfg, symbol);
3759 emit_label (acfg, acfg->plt_symbol);
3761 for (i = 0; i < acfg->plt_offset; ++i) {
3763 char *debug_sym = NULL;
3764 MonoPltEntry *plt_entry = NULL;
3769 * The first plt entry is used to transfer code to the AOT loader.
3771 arch_emit_plt_entry (acfg, i);
3775 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3777 sprintf (label, "%s", plt_entry->symbol);
3781 * If the target is directly callable, alias the plt symbol to point to
3783 * FIXME: Use this to simplify emit_and_reloc_code ().
3784 * FIXME: Avoid the got slot.
3785 * FIXME: Add support to the binary writer.
3787 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3788 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3789 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3794 emit_label (acfg, label);
3796 if (acfg->aot_opts.write_symbols) {
3798 case MONO_PATCH_INFO_METHOD:
3799 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3801 case MONO_PATCH_INFO_INTERNAL_METHOD:
3802 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3804 case MONO_PATCH_INFO_CLASS_INIT:
3805 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3806 sanitize_symbol (debug_sym);
3808 case MONO_PATCH_INFO_RGCTX_FETCH:
3809 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3811 case MONO_PATCH_INFO_ICALL_ADDR: {
3812 char *s = get_debug_sym (ji->data.method, "", cache);
3814 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3818 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3819 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3821 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3822 debug_sym = g_strdup_printf ("plt__generic_class_init");
3829 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3830 emit_label (acfg, debug_sym);
3834 arch_emit_plt_entry (acfg, i);
3837 emit_symbol_size (acfg, debug_sym, ".");
3842 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3844 sprintf (symbol, "plt_end");
3845 emit_global (acfg, symbol, TRUE);
3846 emit_label (acfg, symbol);
3848 g_hash_table_destroy (cache);
3851 static G_GNUC_UNUSED void
3852 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3854 char start_symbol [256];
3856 guint32 buf_size, info_offset;
3857 MonoJumpInfo *patch_info;
3868 code_size = info->code_size;
3870 unwind_ops = info->unwind_ops;
3872 #ifdef __native_client_codegen__
3873 mono_nacl_fix_patches (code, ji);
3878 sprintf (start_symbol, "%s", name);
3880 emit_section_change (acfg, ".text", 0);
3881 emit_global (acfg, start_symbol, TRUE);
3882 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
3883 emit_label (acfg, start_symbol);
3885 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3886 emit_label (acfg, symbol);
3889 * The code should access everything through the GOT, so we pass
3892 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3894 emit_symbol_size (acfg, start_symbol, ".");
3898 /* Sort relocations */
3899 patches = g_ptr_array_new ();
3900 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3901 if (patch_info->type != MONO_PATCH_INFO_NONE)
3902 g_ptr_array_add (patches, patch_info);
3903 g_ptr_array_sort (patches, compare_patches);
3905 buf_size = patches->len * 128 + 128;
3906 buf = g_malloc (buf_size);
3909 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3910 g_assert (p - buf < buf_size);
3912 sprintf (symbol, "%s_p", name);
3914 info_offset = add_to_blob (acfg, buf, p - buf);
3916 emit_section_change (acfg, RODATA_SECT, 0);
3917 emit_global (acfg, symbol, FALSE);
3918 emit_label (acfg, symbol);
3920 emit_int32 (acfg, info_offset);
3922 /* Emit debug info */
3926 sprintf (symbol, "%s", name);
3927 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3930 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3935 emit_trampolines (MonoAotCompile *acfg)
3938 int i, tramp_got_offset;
3939 MonoAotTrampoline ntype;
3940 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3945 if (!acfg->aot_opts.full_aot)
3948 g_assert (acfg->image->assembly);
3950 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3951 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3952 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3953 MonoTrampInfo *info;
3956 * Emit the generic trampolines.
3958 * We could save some code by treating the generic trampolines as a wrapper
3959 * method, but that approach has its own complexities, so we choose the simpler
3962 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3963 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
3964 emit_trampoline (acfg, acfg->got_offset, info);
3967 mono_arch_get_nullified_class_init_trampoline (&info);
3968 emit_trampoline (acfg, acfg->got_offset, info);
3969 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
3970 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
3971 emit_trampoline (acfg, acfg->got_offset, info);
3972 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
3973 emit_trampoline (acfg, acfg->got_offset, info);
3976 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
3977 emit_trampoline (acfg, acfg->got_offset, info);
3979 /* Emit the exception related code pieces */
3980 code = mono_arch_get_restore_context (&info, TRUE);
3981 emit_trampoline (acfg, acfg->got_offset, info);
3982 code = mono_arch_get_call_filter (&info, TRUE);
3983 emit_trampoline (acfg, acfg->got_offset, info);
3984 code = mono_arch_get_throw_exception (&info, TRUE);
3985 emit_trampoline (acfg, acfg->got_offset, info);
3986 code = mono_arch_get_rethrow_exception (&info, TRUE);
3987 emit_trampoline (acfg, acfg->got_offset, info);
3988 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
3989 emit_trampoline (acfg, acfg->got_offset, info);
3991 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
3993 GSList *l = mono_arch_get_trampolines (TRUE);
3996 MonoTrampInfo *info = l->data;
3998 emit_trampoline (acfg, acfg->got_offset, info);
4004 for (i = 0; i < 128; ++i) {
4007 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4008 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4009 emit_trampoline (acfg, acfg->got_offset, info);
4011 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4012 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4013 emit_trampoline (acfg, acfg->got_offset, info);
4019 /* delegate_invoke_impl trampolines */
4020 l = mono_arch_get_delegate_invoke_impls ();
4022 MonoTrampInfo *info = l->data;
4024 emit_trampoline (acfg, acfg->got_offset, info);
4029 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4031 /* Emit trampolines which are numerous */
4034 * These include the following:
4035 * - specific trampolines
4036 * - static rgctx invoke trampolines
4038 * These trampolines have the same code, they are parameterized by GOT
4040 * They are defined in this file, in the arch_... routines instead of
4041 * in tramp-<ARCH>.c, since it is easier to do it this way.
4045 * When running in aot-only mode, we can't create specific trampolines at
4046 * runtime, so we create a few, and save them in the AOT file.
4047 * Normal trampolines embed their argument as a literal inside the
4048 * trampoline code, we can't do that here, so instead we embed an offset
4049 * which needs to be added to the trampoline address to get the address of
4050 * the GOT slot which contains the argument value.
4051 * The generated trampolines jump to the generic trampolines using another
4052 * GOT slot, which will be setup by the AOT loader to point to the
4053 * generic trampoline code of the given type.
4057 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4061 emit_section_change (acfg, ".text", 0);
4063 tramp_got_offset = acfg->got_offset;
4065 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4067 case MONO_AOT_TRAMP_SPECIFIC:
4068 sprintf (symbol, "specific_trampolines");
4070 case MONO_AOT_TRAMP_STATIC_RGCTX:
4071 sprintf (symbol, "static_rgctx_trampolines");
4073 case MONO_AOT_TRAMP_IMT_THUNK:
4074 sprintf (symbol, "imt_thunks");
4077 g_assert_not_reached ();
4080 emit_global (acfg, symbol, TRUE);
4081 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4082 emit_label (acfg, symbol);
4084 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4086 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4090 case MONO_AOT_TRAMP_SPECIFIC:
4091 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4092 tramp_got_offset += 2;
4094 case MONO_AOT_TRAMP_STATIC_RGCTX:
4095 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4096 tramp_got_offset += 2;
4098 case MONO_AOT_TRAMP_IMT_THUNK:
4099 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4100 tramp_got_offset += 1;
4103 g_assert_not_reached ();
4105 #ifdef __native_client_codegen__
4106 /* align to avoid 32-byte boundary crossings */
4107 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4110 if (!acfg->trampoline_size [ntype]) {
4111 g_assert (tramp_size);
4112 acfg->trampoline_size [ntype] = tramp_size;
4117 /* Reserve some entries at the end of the GOT for our use */
4118 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4121 acfg->got_offset += acfg->num_trampoline_got_entries;
4125 str_begins_with (const char *str1, const char *str2)
4127 int len = strlen (str2);
4128 return strncmp (str1, str2, len) == 0;
4132 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4134 gchar **args, **ptr;
4136 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4137 for (ptr = args; ptr && *ptr; ptr ++) {
4138 const char *arg = *ptr;
4140 if (str_begins_with (arg, "outfile=")) {
4141 opts->outfile = g_strdup (arg + strlen ("outfile="));
4142 } else if (str_begins_with (arg, "save-temps")) {
4143 opts->save_temps = TRUE;
4144 } else if (str_begins_with (arg, "keep-temps")) {
4145 opts->save_temps = TRUE;
4146 } else if (str_begins_with (arg, "write-symbols")) {
4147 opts->write_symbols = TRUE;
4148 } else if (str_begins_with (arg, "metadata-only")) {
4149 opts->metadata_only = TRUE;
4150 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4151 opts->bind_to_runtime_version = TRUE;
4152 } else if (str_begins_with (arg, "full")) {
4153 opts->full_aot = TRUE;
4154 } else if (str_begins_with (arg, "threads=")) {
4155 opts->nthreads = atoi (arg + strlen ("threads="));
4156 } else if (str_begins_with (arg, "static")) {
4157 opts->static_link = TRUE;
4158 opts->no_dlsym = TRUE;
4159 } else if (str_begins_with (arg, "asmonly")) {
4160 opts->asm_only = TRUE;
4161 } else if (str_begins_with (arg, "asmwriter")) {
4162 opts->asm_writer = TRUE;
4163 } else if (str_begins_with (arg, "nodebug")) {
4164 opts->nodebug = TRUE;
4165 } else if (str_begins_with (arg, "ntrampolines=")) {
4166 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4167 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4168 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4169 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4170 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4171 } else if (str_begins_with (arg, "autoreg")) {
4172 opts->autoreg = TRUE;
4173 } else if (str_begins_with (arg, "tool-prefix=")) {
4174 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4175 } else if (str_begins_with (arg, "soft-debug")) {
4176 opts->soft_debug = TRUE;
4177 } else if (str_begins_with (arg, "print-skipped")) {
4178 opts->print_skipped_methods = TRUE;
4179 } else if (str_begins_with (arg, "stats")) {
4182 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4191 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4193 MonoMethod *method = (MonoMethod*)key;
4194 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4195 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4196 MonoAotCompile *acfg = user_data;
4198 new_ji->image = ji->image;
4199 new_ji->token = ji->token;
4200 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4204 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4206 if (klass->type_token)
4208 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4211 return can_encode_class (acfg, klass->element_class);
4216 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4218 switch (patch_info->type) {
4219 case MONO_PATCH_INFO_METHOD:
4220 case MONO_PATCH_INFO_METHODCONST: {
4221 MonoMethod *method = patch_info->data.method;
4223 if (method->wrapper_type) {
4224 switch (method->wrapper_type) {
4225 case MONO_WRAPPER_NONE:
4226 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4227 case MONO_WRAPPER_XDOMAIN_INVOKE:
4228 case MONO_WRAPPER_STFLD:
4229 case MONO_WRAPPER_LDFLD:
4230 case MONO_WRAPPER_LDFLDA:
4231 case MONO_WRAPPER_LDFLD_REMOTE:
4232 case MONO_WRAPPER_STFLD_REMOTE:
4233 case MONO_WRAPPER_STELEMREF:
4234 case MONO_WRAPPER_ISINST:
4235 case MONO_WRAPPER_PROXY_ISINST:
4236 case MONO_WRAPPER_ALLOC:
4237 case MONO_WRAPPER_REMOTING_INVOKE:
4238 case MONO_WRAPPER_UNKNOWN:
4239 case MONO_WRAPPER_WRITE_BARRIER:
4241 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4242 if (!strcmp (method->name, "ElementAddr"))
4247 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4251 if (!method->token) {
4252 /* The method is part of a constructed type like Int[,].Set (). */
4253 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4254 if (method->klass->rank)
4262 case MONO_PATCH_INFO_VTABLE:
4263 case MONO_PATCH_INFO_CLASS_INIT:
4264 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4265 case MONO_PATCH_INFO_CLASS:
4266 case MONO_PATCH_INFO_IID:
4267 case MONO_PATCH_INFO_ADJUSTED_IID:
4268 if (!can_encode_class (acfg, patch_info->data.klass)) {
4269 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4273 case MONO_PATCH_INFO_RGCTX_FETCH: {
4274 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4276 if (!can_encode_patch (acfg, entry->data))
4288 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4293 * AOT compile a given method.
4294 * This function might be called by multiple threads, so it must be thread-safe.
4297 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4300 MonoJumpInfo *patch_info;
4303 MonoMethod *wrapped;
4305 if (acfg->aot_opts.metadata_only)
4308 mono_acfg_lock (acfg);
4309 index = get_method_index (acfg, method);
4310 mono_acfg_unlock (acfg);
4312 /* fixme: maybe we can also precompile wrapper methods */
4313 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4314 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4315 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4316 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4320 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4323 wrapped = mono_marshal_method_from_wrapper (method);
4324 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4325 // FIXME: The wrapper should be generic too, but it is not
4328 InterlockedIncrement (&acfg->stats.mcount);
4331 if (method->is_generic || method->klass->generic_container) {
4332 InterlockedIncrement (&acfg->stats.genericcount);
4337 //acfg->aot_opts.print_skipped_methods = TRUE;
4340 * Since these methods are the only ones which are compiled with
4341 * AOT support, and they are not used by runtime startup/shutdown code,
4342 * the runtime will not see AOT methods during AOT compilation,so it
4343 * does not need to support them by creating a fake GOT etc.
4345 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4346 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4347 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4348 InterlockedIncrement (&acfg->stats.genericcount);
4351 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4352 /* Let the exception happen at runtime */
4356 if (cfg->disable_aot) {
4357 if (acfg->aot_opts.print_skipped_methods)
4358 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4359 InterlockedIncrement (&acfg->stats.ocount);
4360 mono_destroy_compile (cfg);
4364 /* Nullify patches which need no aot processing */
4365 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4366 switch (patch_info->type) {
4367 case MONO_PATCH_INFO_LABEL:
4368 case MONO_PATCH_INFO_BB:
4369 patch_info->type = MONO_PATCH_INFO_NONE;
4376 /* Collect method->token associations from the cfg */
4377 mono_acfg_lock (acfg);
4378 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4379 mono_acfg_unlock (acfg);
4382 * Check for absolute addresses.
4385 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4386 switch (patch_info->type) {
4387 case MONO_PATCH_INFO_ABS:
4388 /* unable to handle this */
4397 if (acfg->aot_opts.print_skipped_methods)
4398 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4399 InterlockedIncrement (&acfg->stats.abscount);
4400 mono_destroy_compile (cfg);
4404 /* Lock for the rest of the code */
4405 mono_acfg_lock (acfg);
4408 * Check for methods/klasses we can't encode.
4411 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4412 if (!can_encode_patch (acfg, patch_info))
4417 if (acfg->aot_opts.print_skipped_methods)
4418 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4419 acfg->stats.ocount++;
4420 mono_destroy_compile (cfg);
4421 mono_acfg_unlock (acfg);
4425 /* Adds generic instances referenced by this method */
4427 * The depth is used to avoid infinite loops when generic virtual recursion is
4430 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4432 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4433 switch (patch_info->type) {
4434 case MONO_PATCH_INFO_METHOD: {
4435 MonoMethod *m = patch_info->data.method;
4436 if (m->is_inflated) {
4437 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4438 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4439 !method_has_type_vars (m)) {
4440 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4441 if (acfg->aot_opts.full_aot)
4442 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4444 add_extra_method_with_depth (acfg, m, depth + 1);
4447 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4449 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4450 add_extra_method_with_depth (acfg, m, depth + 1);
4453 case MONO_PATCH_INFO_VTABLE: {
4454 MonoClass *klass = patch_info->data.klass;
4456 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4457 add_generic_class_with_depth (acfg, klass, depth + 5);
4466 /* Determine whenever the method has GOT slots */
4467 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4468 switch (patch_info->type) {
4469 case MONO_PATCH_INFO_GOT_OFFSET:
4470 case MONO_PATCH_INFO_NONE:
4471 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4473 case MONO_PATCH_INFO_IMAGE:
4474 /* The assembly is stored in GOT slot 0 */
4475 if (patch_info->data.image != acfg->image)
4476 cfg->has_got_slots = TRUE;
4479 if (!is_plt_patch (patch_info))
4480 cfg->has_got_slots = TRUE;
4485 if (!cfg->has_got_slots)
4486 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4489 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4491 /* Make a copy of the patch info which is in the mempool */
4493 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4495 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4496 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4499 patches = new_patch_info;
4501 patches_end->next = new_patch_info;
4502 patches_end = new_patch_info;
4504 cfg->patch_info = patches;
4506 /* Make a copy of the unwind info */
4508 GSList *l, *unwind_ops;
4512 for (l = cfg->unwind_ops; l; l = l->next) {
4513 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4514 memcpy (op, l->data, sizeof (MonoUnwindOp));
4515 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4517 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4519 /* Make a copy of the argument/local info */
4521 MonoInst **args, **locals;
4522 MonoMethodSignature *sig;
4523 MonoMethodHeader *header;
4526 sig = mono_method_signature (method);
4527 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4528 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4529 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4530 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4534 header = mono_method_get_header (method);
4535 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4536 for (i = 0; i < header->num_locals; ++i) {
4537 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4538 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4540 cfg->locals = locals;
4543 /* Free some fields used by cfg to conserve memory */
4544 mono_mempool_destroy (cfg->mempool);
4545 cfg->mempool = NULL;
4546 g_free (cfg->varinfo);
4547 cfg->varinfo = NULL;
4551 mono_regstate_free (cfg->rs);
4555 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4557 while (index >= acfg->cfgs_size) {
4558 MonoCompile **new_cfgs;
4561 new_size = acfg->cfgs_size * 2;
4562 new_cfgs = g_new0 (MonoCompile*, new_size);
4563 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4564 g_free (acfg->cfgs);
4565 acfg->cfgs = new_cfgs;
4566 acfg->cfgs_size = new_size;
4568 acfg->cfgs [index] = cfg;
4570 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4573 if (cfg->orig_method->wrapper_type)
4574 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4577 mono_acfg_unlock (acfg);
4579 InterlockedIncrement (&acfg->stats.ccount);
4583 compile_thread_main (gpointer *user_data)
4585 MonoDomain *domain = user_data [0];
4586 MonoAotCompile *acfg = user_data [1];
4587 GPtrArray *methods = user_data [2];
4590 mono_thread_attach (domain);
4592 for (i = 0; i < methods->len; ++i)
4593 compile_method (acfg, g_ptr_array_index (methods, i));
4597 load_profile_files (MonoAotCompile *acfg)
4601 int file_index, res, method_index, i;
4608 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4610 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4615 infile = fopen (tmp, "r");
4618 printf ("Using profile data file '%s'\n", tmp);
4623 res = fscanf (infile, "%32s\n", ver);
4624 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4625 printf ("Profile file has wrong version or invalid.\n");
4632 MonoMethodDesc *desc;
4635 if (fgets (name, 1023, infile) == NULL)
4638 /* Kill the newline */
4639 if (strlen (name) > 0)
4640 name [strlen (name) - 1] = '\0';
4642 desc = mono_method_desc_new (name, TRUE);
4644 method = mono_method_desc_search_in_image (desc, acfg->image);
4646 if (method && mono_method_get_token (method)) {
4647 token = mono_method_get_token (method);
4648 method_index = mono_metadata_token_index (token) - 1;
4650 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4651 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4654 //printf ("No method found matching '%s'.\n", name);
4660 /* Add missing methods */
4662 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4663 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4664 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4666 unordered = g_list_reverse (unordered);
4667 if (acfg->method_order)
4668 g_list_last (acfg->method_order)->next = unordered;
4670 acfg->method_order = unordered;
4673 /* Used by the LLVM backend */
4675 mono_aot_get_got_offset (MonoJumpInfo *ji)
4677 return get_got_offset (llvm_acfg, ji);
4681 mono_aot_get_method_name (MonoCompile *cfg)
4683 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4685 return g_strdup_printf ("m_%x", method_index);
4689 mono_aot_get_method_debug_name (MonoCompile *cfg)
4691 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4695 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4697 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4698 MonoPltEntry *plt_entry;
4701 ji->data.target = data;
4703 if (!can_encode_patch (llvm_acfg, ji))
4706 plt_entry = get_plt_entry (llvm_acfg, ji);
4708 return g_strdup_printf (plt_entry->symbol);
4712 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4716 mono_acfg_lock (llvm_acfg);
4717 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4718 mono_acfg_unlock (llvm_acfg);
4728 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4732 emit_llvm_file (MonoAotCompile *acfg)
4734 char *command, *opts;
4736 MonoJumpInfo *patch_info;
4737 const char *llc_extra_args;
4740 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4744 /* Compute the final size of the got */
4745 for (i = 0; i < acfg->nmethods; ++i) {
4746 if (acfg->cfgs [i]) {
4747 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4748 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4749 if (!is_plt_patch (patch_info))
4750 get_got_offset (acfg, patch_info);
4752 get_plt_entry (acfg, patch_info);
4758 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4760 if (acfg->aot_opts.full_aot) {
4764 * Need to add the got entries used by the trampolines.
4765 * This is only a conservative approximation.
4767 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4768 /* For the generic + rgctx trampolines */
4769 acfg->final_got_size += 200;
4770 /* For the specific trampolines */
4771 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4772 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4777 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4780 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4781 * a lot of time, and doesn't seem to save much space.
4782 * The following optimizations cannot be enabled:
4784 * - 'jump-threading' changes our blockaddress references to int constants.
4785 * The opt list below was produced by taking the output of:
4786 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4787 * then removing tailcallelim + the global opts, and adding a second gvn.
4789 opts = g_strdup ("-instcombine -simplifycfg");
4790 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");
4792 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4793 printf ("Executing opt: %s\n", command);
4794 if (system (command) != 0) {
4800 #if !LLVM_CHECK_VERSION(2, 8)
4801 /* LLVM 2.8 removed the -f flag ??? */
4802 llc_extra_args = "-f";
4804 llc_extra_args = "";
4806 command = g_strdup_printf ("llc %s %s -relocation-model=pic -unwind-tables -o %s temp.opt.bc", LLC_TARGET_ARGS, llc_extra_args, acfg->tmpfname);
4808 printf ("Executing llc: %s\n", command);
4810 if (system (command) != 0) {
4817 emit_code (MonoAotCompile *acfg)
4821 char end_symbol [256];
4824 #if defined(TARGET_POWERPC64)
4825 sprintf (symbol, ".Lgot_addr");
4826 emit_section_change (acfg, ".text", 0);
4827 emit_alignment (acfg, 8);
4828 emit_label (acfg, symbol);
4829 emit_pointer (acfg, acfg->got_symbol);
4833 * This global symbol is used to compute the address of each method using the
4834 * code_offsets array. It is also used to compute the memory ranges occupied by
4835 * AOT code, so it must be equal to the address of the first emitted method.
4837 sprintf (symbol, "methods");
4838 emit_section_change (acfg, ".text", 0);
4839 emit_global (acfg, symbol, TRUE);
4840 emit_alignment (acfg, 8);
4842 for (i = 0; i < acfg->nmethods; ++i) {
4843 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4844 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4848 if (i == acfg->nmethods)
4849 /* No LLVM compiled methods */
4850 emit_label (acfg, symbol);
4852 emit_label (acfg, symbol);
4856 * Emit some padding so the local symbol for the first method doesn't have the
4857 * same address as 'methods'.
4859 emit_zero_bytes (acfg, 16);
4861 for (l = acfg->method_order; l != NULL; l = l->next) {
4865 i = GPOINTER_TO_UINT (l->data);
4867 cfg = acfg->cfgs [i];
4872 method = cfg->orig_method;
4874 /* Emit unbox trampoline */
4875 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4876 char call_target [256];
4878 if (!method->wrapper_type && !method->is_inflated) {
4879 g_assert (method->token);
4880 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4882 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4885 emit_section_change (acfg, ".text", 0);
4886 #ifdef __native_client_codegen__
4887 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4889 emit_global (acfg, symbol, TRUE);
4890 emit_label (acfg, symbol);
4892 sprintf (call_target, "%s", cfg->asm_symbol);
4894 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4897 if (cfg->compile_llvm)
4898 acfg->stats.llvm_count ++;
4900 emit_method_code (acfg, cfg);
4903 sprintf (symbol, "methods_end");
4904 emit_section_change (acfg, ".text", 0);
4905 emit_global (acfg, symbol, FALSE);
4906 emit_alignment (acfg, 8);
4907 emit_label (acfg, symbol);
4909 sprintf (symbol, "code_offsets");
4910 emit_section_change (acfg, RODATA_SECT, 1);
4911 emit_global (acfg, symbol, FALSE);
4912 emit_alignment (acfg, 8);
4913 emit_label (acfg, symbol);
4915 acfg->stats.offsets_size += acfg->nmethods * 4;
4917 sprintf (end_symbol, "methods");
4918 for (i = 0; i < acfg->nmethods; ++i) {
4919 if (acfg->cfgs [i]) {
4920 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4922 emit_int32 (acfg, 0xffffffff);
4929 emit_info (MonoAotCompile *acfg)
4936 offsets = g_new0 (gint32, acfg->nmethods);
4938 for (l = acfg->method_order; l != NULL; l = l->next) {
4939 i = GPOINTER_TO_UINT (l->data);
4941 if (acfg->cfgs [i]) {
4942 emit_method_info (acfg, acfg->cfgs [i]);
4943 offsets [i] = acfg->cfgs [i]->method_info_offset;
4949 sprintf (symbol, "method_info_offsets");
4950 emit_section_change (acfg, RODATA_SECT, 1);
4951 emit_global (acfg, symbol, FALSE);
4952 emit_alignment (acfg, 8);
4953 emit_label (acfg, symbol);
4955 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4960 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4962 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4963 #define mix(a,b,c) { \
4964 a -= c; a ^= rot(c, 4); c += b; \
4965 b -= a; b ^= rot(a, 6); a += c; \
4966 c -= b; c ^= rot(b, 8); b += a; \
4967 a -= c; a ^= rot(c,16); c += b; \
4968 b -= a; b ^= rot(a,19); a += c; \
4969 c -= b; c ^= rot(b, 4); b += a; \
4971 #define final(a,b,c) { \
4972 c ^= b; c -= rot(b,14); \
4973 a ^= c; a -= rot(c,11); \
4974 b ^= a; b -= rot(a,25); \
4975 c ^= b; c -= rot(b,16); \
4976 a ^= c; a -= rot(c,4); \
4977 b ^= a; b -= rot(a,14); \
4978 c ^= b; c -= rot(b,24); \
4982 mono_aot_type_hash (MonoType *t1)
4984 guint hash = t1->type;
4986 hash |= t1->byref << 6; /* do not collide with t1->type values */
4988 case MONO_TYPE_VALUETYPE:
4989 case MONO_TYPE_CLASS:
4990 case MONO_TYPE_SZARRAY:
4991 /* check if the distribution is good enough */
4992 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4994 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4995 case MONO_TYPE_ARRAY:
4996 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4997 case MONO_TYPE_GENERICINST:
4998 return ((hash << 5) - hash) ^ 0;
5004 * mono_aot_method_hash:
5006 * Return a hash code for methods which only depends on metadata.
5009 mono_aot_method_hash (MonoMethod *method)
5011 MonoMethodSignature *sig;
5015 guint32 *hashes_start, *hashes;
5018 /* Similar to the hash in mono_method_get_imt_slot () */
5020 sig = mono_method_signature (method);
5022 hashes_count = sig->param_count + 5;
5023 hashes_start = malloc (hashes_count * sizeof (guint32));
5024 hashes = hashes_start;
5026 /* Some wrappers are assigned to random classes */
5027 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5028 klass = method->klass;
5030 klass = mono_defaults.object_class;
5032 if (!method->wrapper_type) {
5033 char *full_name = mono_type_full_name (&klass->byval_arg);
5035 hashes [0] = mono_metadata_str_hash (full_name);
5039 hashes [0] = mono_metadata_str_hash (klass->name);
5040 hashes [1] = mono_metadata_str_hash (klass->name_space);
5042 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5043 /* The method name includes a stringified pointer */
5046 hashes [2] = mono_metadata_str_hash (method->name);
5047 hashes [3] = method->wrapper_type;
5048 hashes [4] = mono_aot_type_hash (sig->ret);
5049 for (i = 0; i < sig->param_count; i++) {
5050 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
5053 /* Setup internal state */
5054 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5056 /* Handle most of the hashes */
5057 while (hashes_count > 3) {
5066 /* Handle the last 3 hashes (all the case statements fall through) */
5067 switch (hashes_count) {
5068 case 3 : c += hashes [2];
5069 case 2 : b += hashes [1];
5070 case 1 : a += hashes [0];
5072 case 0: /* nothing left to add */
5076 free (hashes_start);
5085 * mono_aot_wrapper_name:
5087 * Return a string which uniqely identifies the given wrapper method.
5090 mono_aot_wrapper_name (MonoMethod *method)
5092 char *name, *tmpsig, *klass_desc;
5094 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5096 switch (method->wrapper_type) {
5097 case MONO_WRAPPER_RUNTIME_INVOKE:
5098 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5099 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5101 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5104 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5105 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5106 g_free (klass_desc);
5116 * mono_aot_get_array_helper_from_wrapper;
5118 * Get the helper method in Array called by an array wrapper method.
5121 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5125 MonoGenericContext ctx;
5126 MonoType *args [16];
5127 char *mname, *iname, *s, *s2, *helper_name = NULL;
5129 prefix = "System.Collections.Generic";
5130 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5131 s2 = strstr (s, "`1.");
5137 //printf ("X: %s %s\n", iname, mname);
5139 if (!strcmp (iname, "IList"))
5140 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5142 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5143 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5145 g_free (helper_name);
5148 if (m->is_generic) {
5149 memset (&ctx, 0, sizeof (ctx));
5150 args [0] = &method->klass->element_class->byval_arg;
5151 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5152 m = mono_class_inflate_generic_method (m, &ctx);
5158 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5160 typedef struct HashEntry {
5161 guint32 key, value, index;
5162 struct HashEntry *next;
5166 * emit_extra_methods:
5168 * Emit methods which are not in the METHOD table, like wrappers.
5171 emit_extra_methods (MonoAotCompile *acfg)
5173 int i, table_size, buf_size;
5176 guint32 *info_offsets;
5179 HashEntry *entry, *new_entry;
5180 int nmethods, max_chain_length;
5183 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5185 /* Emit method info */
5187 for (i = 0; i < acfg->extra_methods->len; ++i) {
5188 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5189 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5196 p = buf = g_malloc (buf_size);
5200 method = cfg->method_to_register;
5203 if (method->wrapper_type) {
5205 * We encode some wrappers using their name, since encoding them
5206 * directly would be difficult. This also avoids creating the wrapper
5207 * methods at runtime, since they are not needed anyway.
5209 switch (method->wrapper_type) {
5210 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5211 case MONO_WRAPPER_SYNCHRONIZED:
5212 /* encode_method_ref () can handle these */
5214 case MONO_WRAPPER_RUNTIME_INVOKE:
5215 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5216 /* Direct wrapper, encode normally */
5220 name = mono_aot_wrapper_name (method);
5226 encode_value (1, p, &p);
5227 encode_value (method->wrapper_type, p, &p);
5228 strcpy ((char*)p, name);
5229 p += strlen (name ) + 1;
5232 encode_value (0, p, &p);
5233 encode_method_ref (acfg, method, p, &p);
5236 g_assert ((p - buf) < buf_size);
5238 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5243 * Construct a chained hash table for mapping indexes in extra_method_info to
5246 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5247 table = g_ptr_array_sized_new (table_size);
5248 for (i = 0; i < table_size; ++i)
5249 g_ptr_array_add (table, NULL);
5250 chain_lengths = g_new0 (int, table_size);
5251 max_chain_length = 0;
5252 for (i = 0; i < acfg->extra_methods->len; ++i) {
5253 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5254 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5260 key = info_offsets [i];
5261 value = get_method_index (acfg, method);
5263 hash = mono_aot_method_hash (method) % table_size;
5265 chain_lengths [hash] ++;
5266 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5268 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5269 new_entry->key = key;
5270 new_entry->value = value;
5272 entry = g_ptr_array_index (table, hash);
5273 if (entry == NULL) {
5274 new_entry->index = hash;
5275 g_ptr_array_index (table, hash) = new_entry;
5278 entry = entry->next;
5280 entry->next = new_entry;
5281 new_entry->index = table->len;
5282 g_ptr_array_add (table, new_entry);
5286 //printf ("MAX: %d\n", max_chain_length);
5288 /* Emit the table */
5289 sprintf (symbol, "extra_method_table");
5290 emit_section_change (acfg, RODATA_SECT, 0);
5291 emit_global (acfg, symbol, FALSE);
5292 emit_alignment (acfg, 8);
5293 emit_label (acfg, symbol);
5295 emit_int32 (acfg, table_size);
5296 for (i = 0; i < table->len; ++i) {
5297 HashEntry *entry = g_ptr_array_index (table, i);
5299 if (entry == NULL) {
5300 emit_int32 (acfg, 0);
5301 emit_int32 (acfg, 0);
5302 emit_int32 (acfg, 0);
5304 //g_assert (entry->key > 0);
5305 emit_int32 (acfg, entry->key);
5306 emit_int32 (acfg, entry->value);
5308 emit_int32 (acfg, entry->next->index);
5310 emit_int32 (acfg, 0);
5315 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5316 * This is used by mono_aot_find_jit_info ().
5318 sprintf (symbol, "extra_method_info_offsets");
5319 emit_section_change (acfg, RODATA_SECT, 0);
5320 emit_global (acfg, symbol, FALSE);
5321 emit_alignment (acfg, 8);
5322 emit_label (acfg, symbol);
5324 emit_int32 (acfg, acfg->extra_methods->len);
5325 for (i = 0; i < acfg->extra_methods->len; ++i) {
5326 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5328 emit_int32 (acfg, get_method_index (acfg, method));
5329 emit_int32 (acfg, info_offsets [i]);
5334 emit_exception_info (MonoAotCompile *acfg)
5340 offsets = g_new0 (gint32, acfg->nmethods);
5341 for (i = 0; i < acfg->nmethods; ++i) {
5342 if (acfg->cfgs [i]) {
5343 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5344 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5350 sprintf (symbol, "ex_info_offsets");
5351 emit_section_change (acfg, RODATA_SECT, 1);
5352 emit_global (acfg, symbol, FALSE);
5353 emit_alignment (acfg, 8);
5354 emit_label (acfg, symbol);
5356 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5361 emit_unwind_info (MonoAotCompile *acfg)
5367 * The unwind info contains a lot of duplicates so we emit each unique
5368 * entry once, and only store the offset from the start of the table in the
5372 sprintf (symbol, "unwind_info");
5373 emit_section_change (acfg, RODATA_SECT, 1);
5374 emit_alignment (acfg, 8);
5375 emit_label (acfg, symbol);
5376 emit_global (acfg, symbol, FALSE);
5378 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5379 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5380 guint8 *unwind_info;
5381 guint32 unwind_info_len;
5385 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5388 encode_value (unwind_info_len, p, &p);
5389 emit_bytes (acfg, buf, p - buf);
5390 emit_bytes (acfg, unwind_info, unwind_info_len);
5392 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5397 emit_class_info (MonoAotCompile *acfg)
5403 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5404 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5405 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5407 sprintf (symbol, "class_info_offsets");
5408 emit_section_change (acfg, RODATA_SECT, 1);
5409 emit_global (acfg, symbol, FALSE);
5410 emit_alignment (acfg, 8);
5411 emit_label (acfg, symbol);
5413 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5417 typedef struct ClassNameTableEntry {
5418 guint32 token, index;
5419 struct ClassNameTableEntry *next;
5420 } ClassNameTableEntry;
5423 emit_class_name_table (MonoAotCompile *acfg)
5426 guint32 token, hash;
5431 ClassNameTableEntry *entry, *new_entry;
5434 * Construct a chained hash table for mapping class names to typedef tokens.
5436 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5437 table = g_ptr_array_sized_new (table_size);
5438 for (i = 0; i < table_size; ++i)
5439 g_ptr_array_add (table, NULL);
5440 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5441 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5442 klass = mono_class_get (acfg->image, token);
5445 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5446 hash = mono_metadata_str_hash (full_name) % table_size;
5449 /* FIXME: Allocate from the mempool */
5450 new_entry = g_new0 (ClassNameTableEntry, 1);
5451 new_entry->token = token;
5453 entry = g_ptr_array_index (table, hash);
5454 if (entry == NULL) {
5455 new_entry->index = hash;
5456 g_ptr_array_index (table, hash) = new_entry;
5459 entry = entry->next;
5461 entry->next = new_entry;
5462 new_entry->index = table->len;
5463 g_ptr_array_add (table, new_entry);
5467 /* Emit the table */
5468 sprintf (symbol, "class_name_table");
5469 emit_section_change (acfg, RODATA_SECT, 0);
5470 emit_global (acfg, symbol, FALSE);
5471 emit_alignment (acfg, 8);
5472 emit_label (acfg, symbol);
5474 /* FIXME: Optimize memory usage */
5475 g_assert (table_size < 65000);
5476 emit_int16 (acfg, table_size);
5477 g_assert (table->len < 65000);
5478 for (i = 0; i < table->len; ++i) {
5479 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5481 if (entry == NULL) {
5482 emit_int16 (acfg, 0);
5483 emit_int16 (acfg, 0);
5485 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5487 emit_int16 (acfg, entry->next->index);
5489 emit_int16 (acfg, 0);
5495 emit_image_table (MonoAotCompile *acfg)
5501 * The image table is small but referenced in a lot of places.
5502 * So we emit it at once, and reference its elements by an index.
5505 sprintf (symbol, "mono_image_table");
5506 emit_section_change (acfg, RODATA_SECT, 1);
5507 emit_global (acfg, symbol, FALSE);
5508 emit_alignment (acfg, 8);
5509 emit_label (acfg, symbol);
5511 emit_int32 (acfg, acfg->image_table->len);
5512 for (i = 0; i < acfg->image_table->len; i++) {
5513 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5514 MonoAssemblyName *aname = &image->assembly->aname;
5516 /* FIXME: Support multi-module assemblies */
5517 g_assert (image->assembly->image == image);
5519 emit_string (acfg, image->assembly_name);
5520 emit_string (acfg, image->guid);
5521 emit_string (acfg, aname->culture ? aname->culture : "");
5522 emit_string (acfg, (const char*)aname->public_key_token);
5524 emit_alignment (acfg, 8);
5525 emit_int32 (acfg, aname->flags);
5526 emit_int32 (acfg, aname->major);
5527 emit_int32 (acfg, aname->minor);
5528 emit_int32 (acfg, aname->build);
5529 emit_int32 (acfg, aname->revision);
5534 emit_got_info (MonoAotCompile *acfg)
5537 int i, first_plt_got_patch, buf_size;
5539 guint32 *got_info_offsets;
5541 /* Add the patches needed by the PLT to the GOT */
5542 acfg->plt_got_offset_base = acfg->got_offset;
5543 first_plt_got_patch = acfg->got_patches->len;
5544 for (i = 1; i < acfg->plt_offset; ++i) {
5545 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5547 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5550 acfg->got_offset += acfg->plt_offset;
5554 * - optimize offsets table.
5555 * - reduce number of exported symbols.
5556 * - emit info for a klass only once.
5557 * - determine when a method uses a GOT slot which is guaranteed to be already
5559 * - clean up and document the code.
5560 * - use String.Empty in class libs.
5563 /* Encode info required to decode shared GOT entries */
5564 buf_size = acfg->got_patches->len * 128;
5565 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5566 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5567 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5569 if (acfg->plt_offset)
5570 acfg->plt_got_info_offsets [0] = 0;
5571 for (i = 0; i < acfg->got_patches->len; ++i) {
5572 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5576 encode_value (ji->type, p, &p);
5577 encode_patch (acfg, ji, p, &p);
5579 g_assert (p - buf <= buf_size);
5580 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5582 if (i >= first_plt_got_patch)
5583 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5584 acfg->stats.got_info_size += p - buf;
5587 /* Emit got_info_offsets table */
5588 sprintf (symbol, "got_info_offsets");
5589 emit_section_change (acfg, RODATA_SECT, 1);
5590 emit_global (acfg, symbol, FALSE);
5591 emit_alignment (acfg, 8);
5592 emit_label (acfg, symbol);
5594 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5595 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5599 emit_got (MonoAotCompile *acfg)
5604 /* Don't make GOT global so accesses to it don't need relocations */
5605 sprintf (symbol, "%s", acfg->got_symbol);
5606 emit_section_change (acfg, ".bss", 0);
5607 emit_alignment (acfg, 8);
5608 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5609 emit_label (acfg, symbol);
5610 if (acfg->got_offset > 0)
5611 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5613 sprintf (symbol, "got_end");
5614 emit_label (acfg, symbol);
5617 sprintf (symbol, "mono_aot_got_addr");
5618 emit_section_change (acfg, ".data", 0);
5619 emit_global (acfg, symbol, FALSE);
5620 emit_alignment (acfg, 8);
5621 emit_label (acfg, symbol);
5622 emit_pointer (acfg, acfg->got_symbol);
5625 typedef struct GlobalsTableEntry {
5626 guint32 value, index;
5627 struct GlobalsTableEntry *next;
5628 } GlobalsTableEntry;
5631 emit_globals_table (MonoAotCompile *acfg)
5637 GlobalsTableEntry *entry, *new_entry;
5640 * Construct a chained hash table for mapping global names to their index in
5641 * the globals table.
5643 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5644 table = g_ptr_array_sized_new (table_size);
5645 for (i = 0; i < table_size; ++i)
5646 g_ptr_array_add (table, NULL);
5647 for (i = 0; i < acfg->globals->len; ++i) {
5648 char *name = g_ptr_array_index (acfg->globals, i);
5650 hash = mono_metadata_str_hash (name) % table_size;
5652 /* FIXME: Allocate from the mempool */
5653 new_entry = g_new0 (GlobalsTableEntry, 1);
5654 new_entry->value = i;
5656 entry = g_ptr_array_index (table, hash);
5657 if (entry == NULL) {
5658 new_entry->index = hash;
5659 g_ptr_array_index (table, hash) = new_entry;
5662 entry = entry->next;
5664 entry->next = new_entry;
5665 new_entry->index = table->len;
5666 g_ptr_array_add (table, new_entry);
5670 /* Emit the table */
5671 sprintf (symbol, ".Lglobals_hash");
5672 emit_section_change (acfg, RODATA_SECT, 0);
5673 emit_alignment (acfg, 8);
5674 emit_label (acfg, symbol);
5676 /* FIXME: Optimize memory usage */
5677 g_assert (table_size < 65000);
5678 emit_int16 (acfg, table_size);
5679 for (i = 0; i < table->len; ++i) {
5680 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5682 if (entry == NULL) {
5683 emit_int16 (acfg, 0);
5684 emit_int16 (acfg, 0);
5686 emit_int16 (acfg, entry->value + 1);
5688 emit_int16 (acfg, entry->next->index);
5690 emit_int16 (acfg, 0);
5694 /* Emit the names */
5695 for (i = 0; i < acfg->globals->len; ++i) {
5696 char *name = g_ptr_array_index (acfg->globals, i);
5698 sprintf (symbol, "name_%d", i);
5699 emit_section_change (acfg, RODATA_SECT, 1);
5700 emit_label (acfg, symbol);
5701 emit_string (acfg, name);
5704 /* Emit the globals table */
5705 sprintf (symbol, ".Lglobals");
5706 emit_section_change (acfg, ".data", 0);
5707 /* This is not a global, since it is accessed by the init function */
5708 emit_alignment (acfg, 8);
5709 emit_label (acfg, symbol);
5711 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5712 emit_pointer (acfg, symbol);
5714 for (i = 0; i < acfg->globals->len; ++i) {
5715 char *name = g_ptr_array_index (acfg->globals, i);
5717 sprintf (symbol, "name_%d", i);
5718 emit_pointer (acfg, symbol);
5720 sprintf (symbol, "%s", name);
5721 emit_pointer (acfg, symbol);
5723 /* Null terminate the table */
5724 emit_int32 (acfg, 0);
5725 emit_int32 (acfg, 0);
5729 emit_globals (MonoAotCompile *acfg)
5733 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5735 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5737 if (acfg->aot_opts.bind_to_runtime_version) {
5738 build_info = mono_get_runtime_build_info ();
5739 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5740 g_free (build_info);
5742 emit_string_symbol (acfg, "mono_runtime_version", "");
5746 * When static linking, we emit a global which will point to the symbol table.
5748 if (acfg->aot_opts.static_link) {
5752 /* Emit a string holding the assembly name */
5753 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5755 emit_globals_table (acfg);
5758 * Emit a global symbol which can be passed by an embedding app to
5759 * mono_aot_register_module ().
5761 #if defined(__MACH__) && !defined(__native_client_codegen__)
5762 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5764 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5767 /* Get rid of characters which cannot occur in symbols */
5769 for (p = symbol; *p; ++p) {
5770 if (!(isalnum (*p) || *p == '_'))
5773 acfg->static_linking_symbol = g_strdup (symbol);
5774 emit_global_inner (acfg, symbol, FALSE);
5775 emit_alignment (acfg, 8);
5776 emit_label (acfg, symbol);
5777 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5778 emit_pointer (acfg, symbol);
5783 emit_autoreg (MonoAotCompile *acfg)
5788 * Emit a function into the .ctor section which will be called by the ELF
5789 * loader to register this module with the runtime.
5791 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5794 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5796 arch_emit_autoreg (acfg, symbol);
5802 emit_mem_end (MonoAotCompile *acfg)
5806 sprintf (symbol, "mem_end");
5807 emit_section_change (acfg, ".text", 1);
5808 emit_global (acfg, symbol, FALSE);
5809 emit_alignment (acfg, 8);
5810 emit_label (acfg, symbol);
5814 * Emit a structure containing all the information not stored elsewhere.
5817 emit_file_info (MonoAotCompile *acfg)
5822 const char *gc_name;
5825 * The managed allocators are GC specific, so can't use an AOT image created by one GC
5828 gc_name = mono_gc_get_gc_name ();
5829 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
5831 sprintf (symbol, "mono_aot_file_info");
5832 emit_section_change (acfg, ".data", 0);
5833 emit_alignment (acfg, 8);
5834 emit_label (acfg, symbol);
5835 emit_global (acfg, symbol, FALSE);
5837 /* The data emitted here must match MonoAotFileInfo. */
5838 emit_int32 (acfg, acfg->plt_got_offset_base);
5839 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5840 emit_int32 (acfg, acfg->plt_offset);
5841 emit_int32 (acfg, acfg->nmethods);
5842 emit_int32 (acfg, acfg->flags);
5843 emit_int32 (acfg, acfg->opts);
5844 emit_int32 (acfg, gc_name_offset);
5846 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5847 emit_int32 (acfg, acfg->num_trampolines [i]);
5848 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5849 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5850 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5851 emit_int32 (acfg, acfg->trampoline_size [i]);
5855 emit_blob (MonoAotCompile *acfg)
5859 sprintf (symbol, "blob");
5860 emit_section_change (acfg, RODATA_SECT, 1);
5861 emit_global (acfg, symbol, FALSE);
5862 emit_alignment (acfg, 8);
5863 emit_label (acfg, symbol);
5865 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5869 emit_dwarf_info (MonoAotCompile *acfg)
5871 #ifdef EMIT_DWARF_INFO
5873 char symbol [128], symbol2 [128];
5875 /* DIEs for methods */
5876 for (i = 0; i < acfg->nmethods; ++i) {
5877 MonoCompile *cfg = acfg->cfgs [i];
5882 // FIXME: LLVM doesn't define .Lme_...
5883 if (cfg->compile_llvm)
5886 sprintf (symbol, "%s", cfg->asm_symbol);
5887 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5889 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 ()));
5895 collect_methods (MonoAotCompile *acfg)
5898 MonoImage *image = acfg->image;
5900 /* Collect methods */
5901 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5903 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5905 method = mono_get_method (acfg->image, token, NULL);
5908 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5912 /* Load all methods eagerly to skip the slower lazy loading code */
5913 mono_class_setup_methods (method->klass);
5915 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5916 /* Compile the wrapper instead */
5917 /* We do this here instead of add_wrappers () because it is easy to do it here */
5918 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5922 /* FIXME: Some mscorlib methods don't have debug info */
5924 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5925 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5926 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5927 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5928 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5929 if (!mono_debug_lookup_method (method)) {
5930 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5937 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5938 add_method_with_index (acfg, method, i, FALSE);
5939 acfg->method_index ++;
5942 add_generic_instances (acfg);
5944 if (acfg->aot_opts.full_aot)
5945 add_wrappers (acfg);
5949 compile_methods (MonoAotCompile *acfg)
5953 if (acfg->aot_opts.nthreads > 0) {
5958 gpointer *user_data;
5959 MonoMethod **methods;
5961 methods_len = acfg->methods->len;
5963 len = acfg->methods->len / acfg->aot_opts.nthreads;
5966 * Partition the list of methods into fragments, and hand it to threads to
5969 threads = g_ptr_array_new ();
5970 /* Make a copy since acfg->methods is modified by compile_method () */
5971 methods = g_new0 (MonoMethod*, methods_len);
5972 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5973 for (i = 0; i < methods_len; ++i)
5974 methods [i] = g_ptr_array_index (acfg->methods, i);
5976 while (i < methods_len) {
5977 frag = g_ptr_array_new ();
5978 for (j = 0; j < len; ++j) {
5979 if (i < methods_len) {
5980 g_ptr_array_add (frag, methods [i]);
5985 user_data = g_new0 (gpointer, 3);
5986 user_data [0] = mono_domain_get ();
5987 user_data [1] = acfg;
5988 user_data [2] = frag;
5990 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5991 g_ptr_array_add (threads, handle);
5995 for (i = 0; i < threads->len; ++i) {
5996 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6002 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6003 for (i = methods_len; i < acfg->methods->len; ++i) {
6004 /* This can new methods to acfg->methods */
6005 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6010 compile_asm (MonoAotCompile *acfg)
6012 char *command, *objfile;
6013 char *outfile_name, *tmp_outfile_name;
6014 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6016 #if defined(TARGET_AMD64)
6017 #define AS_OPTIONS "--64"
6018 #elif defined(TARGET_POWERPC64)
6019 #define AS_OPTIONS "-a64 -mppc64"
6020 #define LD_OPTIONS "-m elf64ppc"
6021 #elif defined(sparc) && SIZEOF_VOID_P == 8
6022 #define AS_OPTIONS "-xarch=v9"
6024 #define AS_OPTIONS ""
6027 #ifdef __native_client_codegen__
6028 #define AS_NAME "nacl-as"
6030 #define AS_NAME "as"
6034 #define LD_OPTIONS ""
6038 #define EH_LD_OPTIONS "--eh-frame-hdr"
6040 #define EH_LD_OPTIONS ""
6043 if (acfg->aot_opts.asm_only) {
6044 printf ("Output file: '%s'.\n", acfg->tmpfname);
6045 if (acfg->aot_opts.static_link)
6046 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6050 if (acfg->aot_opts.static_link) {
6051 if (acfg->aot_opts.outfile)
6052 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6054 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6056 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6058 command = g_strdup_printf ("%s%s %s %s -o %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->tmpfname, objfile);
6059 printf ("Executing the native assembler: %s\n", command);
6060 if (system (command) != 0) {
6068 if (acfg->aot_opts.static_link) {
6069 printf ("Output file: '%s'.\n", objfile);
6070 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6075 if (acfg->aot_opts.outfile)
6076 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6078 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6080 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6083 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6084 #elif defined(__ppc__) && defined(__MACH__)
6085 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6086 #elif defined(HOST_WIN32)
6087 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6089 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6091 printf ("Executing the native linker: %s\n", command);
6092 if (system (command) != 0) {
6093 g_free (tmp_outfile_name);
6094 g_free (outfile_name);
6102 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6103 printf ("Stripping the binary: %s\n", com);
6107 #if defined(TARGET_ARM) && !defined(__MACH__)
6109 * gas generates 'mapping symbols' each time code and data is mixed, which
6110 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6112 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6113 printf ("Stripping the binary: %s\n", command);
6114 if (system (command) != 0) {
6115 g_free (tmp_outfile_name);
6116 g_free (outfile_name);
6123 rename (tmp_outfile_name, outfile_name);
6125 g_free (tmp_outfile_name);
6126 g_free (outfile_name);
6129 if (acfg->aot_opts.save_temps)
6130 printf ("Retained input file.\n");
6132 unlink (acfg->tmpfname);
6137 static MonoAotCompile*
6138 acfg_create (MonoAssembly *ass, guint32 opts)
6140 MonoImage *image = ass->image;
6141 MonoAotCompile *acfg;
6144 acfg = g_new0 (MonoAotCompile, 1);
6145 acfg->methods = g_ptr_array_new ();
6146 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6147 acfg->method_depth = g_hash_table_new (NULL, NULL);
6148 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6149 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6150 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6151 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6152 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6153 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6154 acfg->got_patches = g_ptr_array_new ();
6155 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6156 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6157 acfg->image_hash = g_hash_table_new (NULL, NULL);
6158 acfg->image_table = g_ptr_array_new ();
6159 acfg->globals = g_ptr_array_new ();
6160 acfg->image = image;
6162 acfg->mempool = mono_mempool_new ();
6163 acfg->extra_methods = g_ptr_array_new ();
6164 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6165 acfg->unwind_ops = g_ptr_array_new ();
6166 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6167 InitializeCriticalSection (&acfg->mutex);
6173 acfg_free (MonoAotCompile *acfg)
6177 img_writer_destroy (acfg->w);
6178 for (i = 0; i < acfg->nmethods; ++i)
6180 g_free (acfg->cfgs [i]);
6181 g_free (acfg->cfgs);
6182 g_free (acfg->static_linking_symbol);
6183 g_free (acfg->got_symbol);
6184 g_free (acfg->plt_symbol);
6185 g_ptr_array_free (acfg->methods, TRUE);
6186 g_ptr_array_free (acfg->got_patches, TRUE);
6187 g_ptr_array_free (acfg->image_table, TRUE);
6188 g_ptr_array_free (acfg->globals, TRUE);
6189 g_ptr_array_free (acfg->unwind_ops, TRUE);
6190 g_hash_table_destroy (acfg->method_indexes);
6191 g_hash_table_destroy (acfg->method_depth);
6192 g_hash_table_destroy (acfg->plt_offset_to_entry);
6193 g_hash_table_destroy (acfg->patch_to_plt_entry);
6194 g_hash_table_destroy (acfg->patch_to_got_offset);
6195 g_hash_table_destroy (acfg->method_to_cfg);
6196 g_hash_table_destroy (acfg->token_info_hash);
6197 g_hash_table_destroy (acfg->image_hash);
6198 g_hash_table_destroy (acfg->unwind_info_offsets);
6199 g_hash_table_destroy (acfg->method_label_hash);
6200 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6201 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6202 g_free (acfg->patch_to_got_offset_by_type);
6203 mono_mempool_destroy (acfg->mempool);
6208 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6210 MonoImage *image = ass->image;
6212 MonoAotCompile *acfg;
6213 char *outfile_name, *tmp_outfile_name, *p;
6217 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6219 acfg = acfg_create (ass, opts);
6221 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6222 acfg->aot_opts.write_symbols = TRUE;
6223 acfg->aot_opts.ntrampolines = 1024;
6224 acfg->aot_opts.nrgctx_trampolines = 1024;
6225 acfg->aot_opts.nimt_trampolines = 128;
6227 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6229 if (acfg->aot_opts.static_link)
6230 acfg->aot_opts.autoreg = TRUE;
6232 //acfg->aot_opts.print_skipped_methods = TRUE;
6234 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6235 if (acfg->aot_opts.full_aot) {
6236 printf ("--aot=full is not supported on this platform.\n");
6241 if (acfg->aot_opts.static_link)
6242 acfg->aot_opts.asm_writer = TRUE;
6244 if (acfg->aot_opts.soft_debug) {
6245 MonoDebugOptions *opt = mini_get_debug_options ();
6247 opt->mdb_optimizations = TRUE;
6248 opt->gen_seq_points = TRUE;
6250 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6251 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6258 acfg->aot_opts.asm_writer = TRUE;
6259 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6262 if (acfg->aot_opts.full_aot)
6263 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6265 load_profile_files (acfg);
6267 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6268 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6269 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6271 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6273 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6274 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6276 /* Get rid of characters which cannot occur in symbols */
6277 for (p = acfg->got_symbol_base; *p; ++p) {
6278 if (!(isalnum (*p) || *p == '_'))
6281 for (p = acfg->plt_symbol; *p; ++p) {
6282 if (!(isalnum (*p) || *p == '_'))
6286 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6289 * The prefix LLVM likes to put in front of symbol names on darwin.
6290 * The mach-os specs require this for globals, but LLVM puts them in front of all
6291 * symbols. We need to handle this, since we need to refer to LLVM generated
6294 acfg->llvm_label_prefix = "";
6296 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6298 acfg->method_index = 1;
6300 collect_methods (acfg);
6302 acfg->cfgs_size = acfg->methods->len + 32;
6303 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6305 /* PLT offset 0 is reserved for the PLT trampoline */
6306 acfg->plt_offset = 1;
6310 mono_llvm_create_aot_module (acfg->got_symbol_base);
6313 /* GOT offset 0 is reserved for the address of the current assembly */
6317 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6318 ji->type = MONO_PATCH_INFO_IMAGE;
6319 ji->data.image = acfg->image;
6321 get_got_offset (acfg, ji);
6323 /* Slot 1 is reserved for the mscorlib got addr */
6324 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6325 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6326 get_got_offset (acfg, ji);
6328 /* This is very common */
6329 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6330 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6331 get_got_offset (acfg, ji);
6336 compile_methods (acfg);
6340 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6346 if (acfg->aot_opts.asm_only) {
6347 if (acfg->aot_opts.outfile)
6348 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6350 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6352 acfg->tmpfname = g_strdup ("temp.s");
6356 emit_llvm_file (acfg);
6359 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6360 if (acfg->aot_opts.outfile)
6361 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6363 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6366 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6367 * it might be in another file system so the rename () won't work.
6369 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6371 acfg->fp = fopen (tmp_outfile_name, "w");
6373 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6377 acfg->w = img_writer_create (acfg->fp, TRUE);
6378 acfg->use_bin_writer = TRUE;
6381 /* Append to the .s file created by llvm */
6382 /* FIXME: Use multiple files instead */
6383 acfg->fp = fopen (acfg->tmpfname, "a+");
6385 if (acfg->aot_opts.asm_only) {
6386 if (acfg->aot_opts.outfile)
6387 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6389 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6390 acfg->fp = fopen (acfg->tmpfname, "w+");
6392 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6393 acfg->fp = fdopen (i, "w+");
6395 g_assert (acfg->fp);
6397 acfg->w = img_writer_create (acfg->fp, FALSE);
6399 tmp_outfile_name = NULL;
6400 outfile_name = NULL;
6403 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6405 /* Compute symbols for methods */
6406 for (i = 0; i < acfg->nmethods; ++i) {
6407 if (acfg->cfgs [i]) {
6408 MonoCompile *cfg = acfg->cfgs [i];
6409 int method_index = get_method_index (acfg, cfg->orig_method);
6411 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6415 if (!acfg->aot_opts.nodebug)
6416 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6418 img_writer_emit_start (acfg->w);
6421 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6427 emit_extra_methods (acfg);
6429 emit_trampolines (acfg);
6431 emit_class_name_table (acfg);
6433 emit_got_info (acfg);
6435 emit_exception_info (acfg);
6437 emit_unwind_info (acfg);
6439 emit_class_info (acfg);
6443 emit_image_table (acfg);
6447 emit_file_info (acfg);
6451 emit_globals (acfg);
6453 emit_autoreg (acfg);
6456 emit_dwarf_info (acfg);
6457 mono_dwarf_writer_close (acfg->dwarf);
6460 emit_mem_end (acfg);
6464 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6467 g_assert (acfg->got_offset <= acfg->final_got_size);
6469 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);
6472 res = img_writer_emit_writeout (acfg->w);
6477 if (acfg->use_bin_writer) {
6478 int err = rename (tmp_outfile_name, outfile_name);
6481 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6485 res = compile_asm (acfg);
6492 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6494 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);
6495 if (acfg->stats.genericcount)
6496 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6497 if (acfg->stats.abscount)
6498 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6499 if (acfg->stats.lmfcount)
6500 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6501 if (acfg->stats.ocount)
6502 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6504 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6505 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);
6506 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6508 if (acfg->aot_opts.stats) {
6511 printf ("GOT slot distribution:\n");
6512 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6513 if (acfg->stats.got_slot_types [i])
6514 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6517 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);
6529 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)