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:
3197 case MONO_PATCH_INFO_METHOD_REL:
3198 encode_value ((gint)patch_info->data.offset, p, &p);
3200 case MONO_PATCH_INFO_SWITCH: {
3201 gpointer *table = (gpointer *)patch_info->data.table->table;
3204 encode_value (patch_info->data.table->table_size, p, &p);
3205 for (k = 0; k < patch_info->data.table->table_size; k++)
3206 encode_value ((int)(gssize)table [k], p, &p);
3209 case MONO_PATCH_INFO_METHODCONST:
3210 case MONO_PATCH_INFO_METHOD:
3211 case MONO_PATCH_INFO_METHOD_JUMP:
3212 case MONO_PATCH_INFO_ICALL_ADDR:
3213 case MONO_PATCH_INFO_METHOD_RGCTX:
3214 encode_method_ref (acfg, patch_info->data.method, p, &p);
3216 case MONO_PATCH_INFO_INTERNAL_METHOD:
3217 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3218 guint32 len = strlen (patch_info->data.name);
3220 encode_value (len, p, &p);
3222 memcpy (p, patch_info->data.name, len);
3227 case MONO_PATCH_INFO_LDSTR: {
3228 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3229 guint32 token = patch_info->data.token->token;
3230 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3231 encode_value (image_index, p, &p);
3232 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3235 case MONO_PATCH_INFO_RVA:
3236 case MONO_PATCH_INFO_DECLSEC:
3237 case MONO_PATCH_INFO_LDTOKEN:
3238 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3239 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3240 encode_value (patch_info->data.token->token, p, &p);
3241 encode_value (patch_info->data.token->has_context, p, &p);
3242 if (patch_info->data.token->has_context)
3243 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3245 case MONO_PATCH_INFO_EXC_NAME: {
3246 MonoClass *ex_class;
3249 mono_class_from_name (mono_defaults.exception_class->image,
3250 "System", patch_info->data.target);
3251 g_assert (ex_class);
3252 encode_klass_ref (acfg, ex_class, p, &p);
3255 case MONO_PATCH_INFO_R4:
3256 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3258 case MONO_PATCH_INFO_R8:
3259 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3260 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3262 case MONO_PATCH_INFO_VTABLE:
3263 case MONO_PATCH_INFO_CLASS:
3264 case MONO_PATCH_INFO_IID:
3265 case MONO_PATCH_INFO_ADJUSTED_IID:
3266 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3268 case MONO_PATCH_INFO_CLASS_INIT:
3269 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3270 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3272 case MONO_PATCH_INFO_FIELD:
3273 case MONO_PATCH_INFO_SFLDA:
3274 encode_field_info (acfg, patch_info->data.field, p, &p);
3276 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3278 case MONO_PATCH_INFO_RGCTX_FETCH: {
3279 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3281 encode_method_ref (acfg, entry->method, p, &p);
3282 encode_value (entry->in_mrgctx, p, &p);
3283 encode_value (entry->info_type, p, &p);
3284 encode_value (entry->data->type, p, &p);
3285 encode_patch (acfg, entry->data, p, &p);
3288 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3289 case MONO_PATCH_INFO_MONITOR_ENTER:
3290 case MONO_PATCH_INFO_MONITOR_EXIT:
3291 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3293 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3294 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3295 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3298 g_warning ("unable to handle jump info %d", patch_info->type);
3299 g_assert_not_reached ();
3306 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3309 guint32 pindex, offset;
3310 MonoJumpInfo *patch_info;
3312 encode_value (n_patches, p, &p);
3314 for (pindex = 0; pindex < patches->len; ++pindex) {
3315 patch_info = g_ptr_array_index (patches, pindex);
3317 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3321 offset = get_got_offset (acfg, patch_info);
3322 encode_value (offset, p, &p);
3329 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3333 int pindex, buf_size, n_patches;
3336 MonoJumpInfo *patch_info;
3337 MonoMethodHeader *header;
3338 guint32 method_index;
3340 guint32 first_got_offset;
3342 method = cfg->orig_method;
3343 code = cfg->native_code;
3344 header = mono_method_get_header (method);
3346 method_index = get_method_index (acfg, method);
3348 /* Sort relocations */
3349 patches = g_ptr_array_new ();
3350 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3351 g_ptr_array_add (patches, patch_info);
3352 g_ptr_array_sort (patches, compare_patches);
3354 first_got_offset = acfg->cfgs [method_index]->got_offset;
3356 /**********************/
3357 /* Encode method info */
3358 /**********************/
3360 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3361 p = buf = g_malloc (buf_size);
3363 if (mono_class_get_cctor (method->klass))
3364 encode_klass_ref (acfg, method->klass, p, &p);
3366 /* Not needed when loading the method */
3367 encode_value (0, p, &p);
3370 if (cfg->opt & MONO_OPT_SHARED) {
3371 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3372 for (l = cfg->ldstr_list; l; l = l->next) {
3373 encode_value ((long)l->data, p, &p);
3377 /* Used only in shared mode */
3378 g_assert (!cfg->ldstr_list);
3381 for (pindex = 0; pindex < patches->len; ++pindex) {
3382 patch_info = g_ptr_array_index (patches, pindex);
3384 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3385 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3386 patch_info->type = MONO_PATCH_INFO_NONE;
3391 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3392 /* Stored in a GOT slot initialized at module load time */
3393 patch_info->type = MONO_PATCH_INFO_NONE;
3397 if (is_plt_patch (patch_info)) {
3398 /* Calls are made through the PLT */
3399 patch_info->type = MONO_PATCH_INFO_NONE;
3407 g_assert (cfg->has_got_slots);
3409 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3411 acfg->stats.info_size += p - buf;
3413 g_assert (p - buf < buf_size);
3415 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3420 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3422 guint32 cache_index;
3425 /* Reuse the unwind module to canonize and store unwind info entries */
3426 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3428 /* Use +/- 1 to distinguish 0s from missing entries */
3429 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3437 * It would be easier to use assembler symbols, but the caller needs an
3440 offset = acfg->unwind_info_offset;
3441 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3442 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3445 encode_value (encoded_len, p, &p);
3447 acfg->unwind_info_offset += encoded_len + (p - buf);
3453 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3456 int i, k, buf_size, method_index;
3457 guint32 debug_info_size;
3459 MonoMethodHeader *header;
3460 guint8 *p, *buf, *debug_info;
3461 MonoJitInfo *jinfo = cfg->jit_info;
3463 gboolean use_unwind_ops = FALSE;
3464 MonoSeqPointInfo *seq_points;
3466 method = cfg->orig_method;
3467 code = cfg->native_code;
3468 header = cfg->header;
3470 method_index = get_method_index (acfg, method);
3472 if (!acfg->aot_opts.nodebug) {
3473 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3476 debug_info_size = 0;
3479 seq_points = cfg->seq_point_info;
3481 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3482 p = buf = g_malloc (buf_size);
3484 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3485 use_unwind_ops = cfg->unwind_ops != NULL;
3488 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);
3490 encode_value (flags, p, &p);
3492 if (use_unwind_ops) {
3493 guint32 encoded_len;
3497 * This is a duplicate of the data in the .debug_frame section, but that
3498 * section cannot be accessed using the dl interface.
3500 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3501 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3504 encode_value (jinfo->used_regs, p, &p);
3507 /*Encode the number of holes before the number of clauses to make decoding easier*/
3508 if (jinfo->has_try_block_holes) {
3509 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3510 encode_value (table->num_holes, p, &p);
3513 /* Exception table */
3514 if (cfg->compile_llvm) {
3516 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3517 * since the information is only available to llc. Instead, we let llc save the data
3518 * into the LSDA, and read it from there at runtime.
3520 /* The assembly might be CIL stripped so emit the data ourselves */
3521 if (header->num_clauses)
3522 encode_value (header->num_clauses, p, &p);
3524 for (k = 0; k < header->num_clauses; ++k) {
3525 MonoExceptionClause *clause;
3527 clause = &header->clauses [k];
3529 encode_value (clause->flags, p, &p);
3530 if (clause->data.catch_class) {
3531 encode_value (1, p, &p);
3532 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3534 encode_value (0, p, &p);
3537 /* Emit a list of nesting clauses */
3538 for (i = 0; i < header->num_clauses; ++i) {
3540 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3542 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3544 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3545 encode_value (i, p, &p);
3547 encode_value (-1, p, &p);
3550 if (jinfo->num_clauses)
3551 encode_value (jinfo->num_clauses, p, &p);
3553 for (k = 0; k < jinfo->num_clauses; ++k) {
3554 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3556 encode_value (ei->flags, p, &p);
3557 encode_value (ei->exvar_offset, p, &p);
3559 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3560 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3562 if (ei->data.catch_class) {
3563 encode_value (1, p, &p);
3564 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3566 encode_value (0, p, &p);
3570 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3571 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3572 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3576 if (jinfo->has_generic_jit_info) {
3577 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3579 if (!cfg->compile_llvm) {
3580 encode_value (gi->has_this ? 1 : 0, p, &p);
3581 encode_value (gi->this_reg, p, &p);
3582 encode_value (gi->this_offset, p, &p);
3586 * Need to encode jinfo->method too, since it is not equal to 'method'
3587 * when using generic sharing.
3589 encode_method_ref (acfg, jinfo->method, p, &p);
3592 if (jinfo->has_try_block_holes) {
3593 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3594 for (i = 0; i < table->num_holes; ++i) {
3595 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3596 encode_value (hole->clause, p, &p);
3597 encode_value (hole->length, p, &p);
3598 encode_value (hole->offset, p, &p);
3603 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3605 encode_value (seq_points->len, p, &p);
3606 last_il_offset = last_native_offset = 0;
3607 for (i = 0; i < seq_points->len; ++i) {
3608 SeqPoint *sp = &seq_points->seq_points [i];
3609 il_offset = sp->il_offset;
3610 native_offset = sp->native_offset;
3611 encode_value (il_offset - last_il_offset, p, &p);
3612 encode_value (native_offset - last_native_offset, p, &p);
3613 last_il_offset = il_offset;
3614 last_native_offset = native_offset;
3616 encode_value (sp->next_len, p, &p);
3617 for (j = 0; j < sp->next_len; ++j)
3618 encode_value (sp->next [j], p, &p);
3623 g_assert (debug_info_size < buf_size);
3625 encode_value (debug_info_size, p, &p);
3626 if (debug_info_size) {
3627 memcpy (p, debug_info, debug_info_size);
3628 p += debug_info_size;
3629 g_free (debug_info);
3632 acfg->stats.ex_info_size += p - buf;
3634 g_assert (p - buf < buf_size);
3637 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3642 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3644 MonoClass *klass = mono_class_get (acfg->image, token);
3646 int i, buf_size, res;
3647 gboolean no_special_static, cant_encode;
3648 gpointer iter = NULL;
3653 p = buf = g_malloc (buf_size);
3655 /* Mark as unusable */
3656 encode_value (-1, p, &p);
3658 res = add_to_blob (acfg, buf, p - buf);
3664 buf_size = 10240 + (klass->vtable_size * 16);
3665 p = buf = g_malloc (buf_size);
3669 mono_class_init (klass);
3671 mono_class_get_nested_types (klass, &iter);
3672 g_assert (klass->nested_classes_inited);
3674 mono_class_setup_vtable (klass);
3677 * Emit all the information which is required for creating vtables so
3678 * the runtime does not need to create the MonoMethod structures which
3679 * take up a lot of space.
3682 no_special_static = !mono_class_has_special_static_fields (klass);
3684 /* Check whenever we have enough info to encode the vtable */
3685 cant_encode = FALSE;
3686 for (i = 0; i < klass->vtable_size; ++i) {
3687 MonoMethod *cm = klass->vtable [i];
3689 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3693 if (klass->generic_container || cant_encode) {
3694 encode_value (-1, p, &p);
3696 encode_value (klass->vtable_size, p, &p);
3697 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);
3698 if (klass->has_cctor)
3699 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3700 if (klass->has_finalize)
3701 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3703 encode_value (klass->instance_size, p, &p);
3704 encode_value (mono_class_data_size (klass), p, &p);
3705 encode_value (klass->packing_size, p, &p);
3706 encode_value (klass->min_align, p, &p);
3708 for (i = 0; i < klass->vtable_size; ++i) {
3709 MonoMethod *cm = klass->vtable [i];
3712 encode_method_ref (acfg, cm, p, &p);
3714 encode_value (0, p, &p);
3718 acfg->stats.class_info_size += p - buf;
3720 g_assert (p - buf < buf_size);
3721 res = add_to_blob (acfg, buf, p - buf);
3728 * Calls made from AOTed code are routed through a table of jumps similar to the
3729 * ELF PLT (Program Linkage Table). The differences are the following:
3730 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3731 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3732 * jumps. This means the jumps need to be patched when the address of the callee is
3733 * known. Initially the PLT entries jump to code which transfers control to the
3734 * AOT runtime through the first PLT entry.
3737 emit_plt (MonoAotCompile *acfg)
3743 cache = g_hash_table_new (g_str_hash, g_str_equal);
3746 sprintf (symbol, "plt");
3748 emit_section_change (acfg, ".text", 0);
3749 emit_global (acfg, symbol, TRUE);
3750 emit_alignment (acfg, 16);
3751 emit_label (acfg, symbol);
3752 emit_label (acfg, acfg->plt_symbol);
3754 for (i = 0; i < acfg->plt_offset; ++i) {
3756 char *debug_sym = NULL;
3757 MonoPltEntry *plt_entry = NULL;
3762 * The first plt entry is used to transfer code to the AOT loader.
3764 arch_emit_plt_entry (acfg, i);
3768 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3770 sprintf (label, "%s", plt_entry->symbol);
3774 * If the target is directly callable, alias the plt symbol to point to
3776 * FIXME: Use this to simplify emit_and_reloc_code ().
3777 * FIXME: Avoid the got slot.
3778 * FIXME: Add support to the binary writer.
3780 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3781 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3782 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3787 emit_label (acfg, label);
3789 if (acfg->aot_opts.write_symbols) {
3791 case MONO_PATCH_INFO_METHOD:
3792 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3794 case MONO_PATCH_INFO_INTERNAL_METHOD:
3795 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3797 case MONO_PATCH_INFO_CLASS_INIT:
3798 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3799 sanitize_symbol (debug_sym);
3801 case MONO_PATCH_INFO_RGCTX_FETCH:
3802 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3804 case MONO_PATCH_INFO_ICALL_ADDR: {
3805 char *s = get_debug_sym (ji->data.method, "", cache);
3807 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3811 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3812 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3814 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3815 debug_sym = g_strdup_printf ("plt__generic_class_init");
3822 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3823 emit_label (acfg, debug_sym);
3827 arch_emit_plt_entry (acfg, i);
3830 emit_symbol_size (acfg, debug_sym, ".");
3835 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3837 sprintf (symbol, "plt_end");
3838 emit_global (acfg, symbol, TRUE);
3839 emit_label (acfg, symbol);
3841 g_hash_table_destroy (cache);
3844 static G_GNUC_UNUSED void
3845 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3847 char start_symbol [256];
3849 guint32 buf_size, info_offset;
3850 MonoJumpInfo *patch_info;
3861 code_size = info->code_size;
3863 unwind_ops = info->unwind_ops;
3865 #ifdef __native_client_codegen__
3866 mono_nacl_fix_patches (code, ji);
3871 sprintf (start_symbol, "%s", name);
3873 emit_section_change (acfg, ".text", 0);
3874 emit_global (acfg, start_symbol, TRUE);
3875 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
3876 emit_label (acfg, start_symbol);
3878 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3879 emit_label (acfg, symbol);
3882 * The code should access everything through the GOT, so we pass
3885 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3887 emit_symbol_size (acfg, start_symbol, ".");
3891 /* Sort relocations */
3892 patches = g_ptr_array_new ();
3893 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3894 if (patch_info->type != MONO_PATCH_INFO_NONE)
3895 g_ptr_array_add (patches, patch_info);
3896 g_ptr_array_sort (patches, compare_patches);
3898 buf_size = patches->len * 128 + 128;
3899 buf = g_malloc (buf_size);
3902 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3903 g_assert (p - buf < buf_size);
3905 sprintf (symbol, "%s_p", name);
3907 info_offset = add_to_blob (acfg, buf, p - buf);
3909 emit_section_change (acfg, RODATA_SECT, 0);
3910 emit_global (acfg, symbol, FALSE);
3911 emit_label (acfg, symbol);
3913 emit_int32 (acfg, info_offset);
3915 /* Emit debug info */
3919 sprintf (symbol, "%s", name);
3920 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3923 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3928 emit_trampolines (MonoAotCompile *acfg)
3931 int i, tramp_got_offset;
3932 MonoAotTrampoline ntype;
3933 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3938 if (!acfg->aot_opts.full_aot)
3941 g_assert (acfg->image->assembly);
3943 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3944 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3945 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3946 MonoTrampInfo *info;
3949 * Emit the generic trampolines.
3951 * We could save some code by treating the generic trampolines as a wrapper
3952 * method, but that approach has its own complexities, so we choose the simpler
3955 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3956 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
3957 emit_trampoline (acfg, acfg->got_offset, info);
3960 mono_arch_get_nullified_class_init_trampoline (&info);
3961 emit_trampoline (acfg, acfg->got_offset, info);
3962 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
3963 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
3964 emit_trampoline (acfg, acfg->got_offset, info);
3965 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
3966 emit_trampoline (acfg, acfg->got_offset, info);
3969 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
3970 emit_trampoline (acfg, acfg->got_offset, info);
3972 /* Emit the exception related code pieces */
3973 code = mono_arch_get_restore_context (&info, TRUE);
3974 emit_trampoline (acfg, acfg->got_offset, info);
3975 code = mono_arch_get_call_filter (&info, TRUE);
3976 emit_trampoline (acfg, acfg->got_offset, info);
3977 code = mono_arch_get_throw_exception (&info, TRUE);
3978 emit_trampoline (acfg, acfg->got_offset, info);
3979 code = mono_arch_get_rethrow_exception (&info, TRUE);
3980 emit_trampoline (acfg, acfg->got_offset, info);
3981 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
3982 emit_trampoline (acfg, acfg->got_offset, info);
3984 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
3986 GSList *l = mono_arch_get_trampolines (TRUE);
3989 MonoTrampInfo *info = l->data;
3991 emit_trampoline (acfg, acfg->got_offset, info);
3997 for (i = 0; i < 128; ++i) {
4000 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4001 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4002 emit_trampoline (acfg, acfg->got_offset, info);
4004 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4005 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4006 emit_trampoline (acfg, acfg->got_offset, info);
4012 /* delegate_invoke_impl trampolines */
4013 l = mono_arch_get_delegate_invoke_impls ();
4015 MonoTrampInfo *info = l->data;
4017 emit_trampoline (acfg, acfg->got_offset, info);
4022 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4024 /* Emit trampolines which are numerous */
4027 * These include the following:
4028 * - specific trampolines
4029 * - static rgctx invoke trampolines
4031 * These trampolines have the same code, they are parameterized by GOT
4033 * They are defined in this file, in the arch_... routines instead of
4034 * in tramp-<ARCH>.c, since it is easier to do it this way.
4038 * When running in aot-only mode, we can't create specific trampolines at
4039 * runtime, so we create a few, and save them in the AOT file.
4040 * Normal trampolines embed their argument as a literal inside the
4041 * trampoline code, we can't do that here, so instead we embed an offset
4042 * which needs to be added to the trampoline address to get the address of
4043 * the GOT slot which contains the argument value.
4044 * The generated trampolines jump to the generic trampolines using another
4045 * GOT slot, which will be setup by the AOT loader to point to the
4046 * generic trampoline code of the given type.
4050 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4054 emit_section_change (acfg, ".text", 0);
4056 tramp_got_offset = acfg->got_offset;
4058 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4060 case MONO_AOT_TRAMP_SPECIFIC:
4061 sprintf (symbol, "specific_trampolines");
4063 case MONO_AOT_TRAMP_STATIC_RGCTX:
4064 sprintf (symbol, "static_rgctx_trampolines");
4066 case MONO_AOT_TRAMP_IMT_THUNK:
4067 sprintf (symbol, "imt_thunks");
4070 g_assert_not_reached ();
4073 emit_global (acfg, symbol, TRUE);
4074 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4075 emit_label (acfg, symbol);
4077 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4079 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4083 case MONO_AOT_TRAMP_SPECIFIC:
4084 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4085 tramp_got_offset += 2;
4087 case MONO_AOT_TRAMP_STATIC_RGCTX:
4088 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4089 tramp_got_offset += 2;
4091 case MONO_AOT_TRAMP_IMT_THUNK:
4092 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4093 tramp_got_offset += 1;
4096 g_assert_not_reached ();
4098 #ifdef __native_client_codegen__
4099 /* align to avoid 32-byte boundary crossings */
4100 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4103 if (!acfg->trampoline_size [ntype]) {
4104 g_assert (tramp_size);
4105 acfg->trampoline_size [ntype] = tramp_size;
4110 /* Reserve some entries at the end of the GOT for our use */
4111 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4114 acfg->got_offset += acfg->num_trampoline_got_entries;
4118 str_begins_with (const char *str1, const char *str2)
4120 int len = strlen (str2);
4121 return strncmp (str1, str2, len) == 0;
4125 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4127 gchar **args, **ptr;
4129 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4130 for (ptr = args; ptr && *ptr; ptr ++) {
4131 const char *arg = *ptr;
4133 if (str_begins_with (arg, "outfile=")) {
4134 opts->outfile = g_strdup (arg + strlen ("outfile="));
4135 } else if (str_begins_with (arg, "save-temps")) {
4136 opts->save_temps = TRUE;
4137 } else if (str_begins_with (arg, "keep-temps")) {
4138 opts->save_temps = TRUE;
4139 } else if (str_begins_with (arg, "write-symbols")) {
4140 opts->write_symbols = TRUE;
4141 } else if (str_begins_with (arg, "metadata-only")) {
4142 opts->metadata_only = TRUE;
4143 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4144 opts->bind_to_runtime_version = TRUE;
4145 } else if (str_begins_with (arg, "full")) {
4146 opts->full_aot = TRUE;
4147 } else if (str_begins_with (arg, "threads=")) {
4148 opts->nthreads = atoi (arg + strlen ("threads="));
4149 } else if (str_begins_with (arg, "static")) {
4150 opts->static_link = TRUE;
4151 opts->no_dlsym = TRUE;
4152 } else if (str_begins_with (arg, "asmonly")) {
4153 opts->asm_only = TRUE;
4154 } else if (str_begins_with (arg, "asmwriter")) {
4155 opts->asm_writer = TRUE;
4156 } else if (str_begins_with (arg, "nodebug")) {
4157 opts->nodebug = TRUE;
4158 } else if (str_begins_with (arg, "ntrampolines=")) {
4159 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4160 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4161 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4162 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4163 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4164 } else if (str_begins_with (arg, "autoreg")) {
4165 opts->autoreg = TRUE;
4166 } else if (str_begins_with (arg, "tool-prefix=")) {
4167 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4168 } else if (str_begins_with (arg, "soft-debug")) {
4169 opts->soft_debug = TRUE;
4170 } else if (str_begins_with (arg, "print-skipped")) {
4171 opts->print_skipped_methods = TRUE;
4172 } else if (str_begins_with (arg, "stats")) {
4175 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4184 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4186 MonoMethod *method = (MonoMethod*)key;
4187 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4188 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4189 MonoAotCompile *acfg = user_data;
4191 new_ji->image = ji->image;
4192 new_ji->token = ji->token;
4193 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4197 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4199 if (klass->type_token)
4201 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4204 return can_encode_class (acfg, klass->element_class);
4209 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4211 switch (patch_info->type) {
4212 case MONO_PATCH_INFO_METHOD:
4213 case MONO_PATCH_INFO_METHODCONST: {
4214 MonoMethod *method = patch_info->data.method;
4216 if (method->wrapper_type) {
4217 switch (method->wrapper_type) {
4218 case MONO_WRAPPER_NONE:
4219 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4220 case MONO_WRAPPER_XDOMAIN_INVOKE:
4221 case MONO_WRAPPER_STFLD:
4222 case MONO_WRAPPER_LDFLD:
4223 case MONO_WRAPPER_LDFLDA:
4224 case MONO_WRAPPER_LDFLD_REMOTE:
4225 case MONO_WRAPPER_STFLD_REMOTE:
4226 case MONO_WRAPPER_STELEMREF:
4227 case MONO_WRAPPER_ISINST:
4228 case MONO_WRAPPER_PROXY_ISINST:
4229 case MONO_WRAPPER_ALLOC:
4230 case MONO_WRAPPER_REMOTING_INVOKE:
4231 case MONO_WRAPPER_UNKNOWN:
4232 case MONO_WRAPPER_WRITE_BARRIER:
4234 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4235 if (!strcmp (method->name, "ElementAddr"))
4240 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4244 if (!method->token) {
4245 /* The method is part of a constructed type like Int[,].Set (). */
4246 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4247 if (method->klass->rank)
4255 case MONO_PATCH_INFO_VTABLE:
4256 case MONO_PATCH_INFO_CLASS_INIT:
4257 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4258 case MONO_PATCH_INFO_CLASS:
4259 case MONO_PATCH_INFO_IID:
4260 case MONO_PATCH_INFO_ADJUSTED_IID:
4261 if (!can_encode_class (acfg, patch_info->data.klass)) {
4262 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4266 case MONO_PATCH_INFO_RGCTX_FETCH: {
4267 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4269 if (!can_encode_patch (acfg, entry->data))
4281 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4286 * AOT compile a given method.
4287 * This function might be called by multiple threads, so it must be thread-safe.
4290 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4293 MonoJumpInfo *patch_info;
4296 MonoMethod *wrapped;
4298 if (acfg->aot_opts.metadata_only)
4301 mono_acfg_lock (acfg);
4302 index = get_method_index (acfg, method);
4303 mono_acfg_unlock (acfg);
4305 /* fixme: maybe we can also precompile wrapper methods */
4306 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4307 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4308 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4309 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4313 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4316 wrapped = mono_marshal_method_from_wrapper (method);
4317 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4318 // FIXME: The wrapper should be generic too, but it is not
4321 InterlockedIncrement (&acfg->stats.mcount);
4324 if (method->is_generic || method->klass->generic_container) {
4325 InterlockedIncrement (&acfg->stats.genericcount);
4330 //acfg->aot_opts.print_skipped_methods = TRUE;
4333 * Since these methods are the only ones which are compiled with
4334 * AOT support, and they are not used by runtime startup/shutdown code,
4335 * the runtime will not see AOT methods during AOT compilation,so it
4336 * does not need to support them by creating a fake GOT etc.
4338 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4339 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4340 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4341 InterlockedIncrement (&acfg->stats.genericcount);
4344 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4345 /* Let the exception happen at runtime */
4349 if (cfg->disable_aot) {
4350 if (acfg->aot_opts.print_skipped_methods)
4351 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4352 InterlockedIncrement (&acfg->stats.ocount);
4353 mono_destroy_compile (cfg);
4357 /* Nullify patches which need no aot processing */
4358 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4359 switch (patch_info->type) {
4360 case MONO_PATCH_INFO_LABEL:
4361 case MONO_PATCH_INFO_BB:
4362 patch_info->type = MONO_PATCH_INFO_NONE;
4369 /* Collect method->token associations from the cfg */
4370 mono_acfg_lock (acfg);
4371 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4372 mono_acfg_unlock (acfg);
4375 * Check for absolute addresses.
4378 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4379 switch (patch_info->type) {
4380 case MONO_PATCH_INFO_ABS:
4381 /* unable to handle this */
4390 if (acfg->aot_opts.print_skipped_methods)
4391 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4392 InterlockedIncrement (&acfg->stats.abscount);
4393 mono_destroy_compile (cfg);
4397 /* Lock for the rest of the code */
4398 mono_acfg_lock (acfg);
4401 * Check for methods/klasses we can't encode.
4404 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4405 if (!can_encode_patch (acfg, patch_info))
4410 if (acfg->aot_opts.print_skipped_methods)
4411 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4412 acfg->stats.ocount++;
4413 mono_destroy_compile (cfg);
4414 mono_acfg_unlock (acfg);
4418 /* Adds generic instances referenced by this method */
4420 * The depth is used to avoid infinite loops when generic virtual recursion is
4423 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4425 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4426 switch (patch_info->type) {
4427 case MONO_PATCH_INFO_METHOD: {
4428 MonoMethod *m = patch_info->data.method;
4429 if (m->is_inflated) {
4430 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4431 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4432 !method_has_type_vars (m)) {
4433 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4434 if (acfg->aot_opts.full_aot)
4435 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4437 add_extra_method_with_depth (acfg, m, depth + 1);
4440 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4442 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4443 add_extra_method_with_depth (acfg, m, depth + 1);
4446 case MONO_PATCH_INFO_VTABLE: {
4447 MonoClass *klass = patch_info->data.klass;
4449 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4450 add_generic_class_with_depth (acfg, klass, depth + 5);
4459 /* Determine whenever the method has GOT slots */
4460 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4461 switch (patch_info->type) {
4462 case MONO_PATCH_INFO_GOT_OFFSET:
4463 case MONO_PATCH_INFO_NONE:
4465 case MONO_PATCH_INFO_IMAGE:
4466 /* The assembly is stored in GOT slot 0 */
4467 if (patch_info->data.image != acfg->image)
4468 cfg->has_got_slots = TRUE;
4471 if (!is_plt_patch (patch_info))
4472 cfg->has_got_slots = TRUE;
4477 if (!cfg->has_got_slots)
4478 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4481 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4483 /* Make a copy of the patch info which is in the mempool */
4485 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4487 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4488 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4491 patches = new_patch_info;
4493 patches_end->next = new_patch_info;
4494 patches_end = new_patch_info;
4496 cfg->patch_info = patches;
4498 /* Make a copy of the unwind info */
4500 GSList *l, *unwind_ops;
4504 for (l = cfg->unwind_ops; l; l = l->next) {
4505 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4506 memcpy (op, l->data, sizeof (MonoUnwindOp));
4507 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4509 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4511 /* Make a copy of the argument/local info */
4513 MonoInst **args, **locals;
4514 MonoMethodSignature *sig;
4515 MonoMethodHeader *header;
4518 sig = mono_method_signature (method);
4519 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4520 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4521 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4522 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4526 header = mono_method_get_header (method);
4527 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4528 for (i = 0; i < header->num_locals; ++i) {
4529 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4530 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4532 cfg->locals = locals;
4535 /* Free some fields used by cfg to conserve memory */
4536 mono_mempool_destroy (cfg->mempool);
4537 cfg->mempool = NULL;
4538 g_free (cfg->varinfo);
4539 cfg->varinfo = NULL;
4543 mono_regstate_free (cfg->rs);
4547 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4549 while (index >= acfg->cfgs_size) {
4550 MonoCompile **new_cfgs;
4553 new_size = acfg->cfgs_size * 2;
4554 new_cfgs = g_new0 (MonoCompile*, new_size);
4555 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4556 g_free (acfg->cfgs);
4557 acfg->cfgs = new_cfgs;
4558 acfg->cfgs_size = new_size;
4560 acfg->cfgs [index] = cfg;
4562 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4565 if (cfg->orig_method->wrapper_type)
4566 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4569 mono_acfg_unlock (acfg);
4571 InterlockedIncrement (&acfg->stats.ccount);
4575 compile_thread_main (gpointer *user_data)
4577 MonoDomain *domain = user_data [0];
4578 MonoAotCompile *acfg = user_data [1];
4579 GPtrArray *methods = user_data [2];
4582 mono_thread_attach (domain);
4584 for (i = 0; i < methods->len; ++i)
4585 compile_method (acfg, g_ptr_array_index (methods, i));
4589 load_profile_files (MonoAotCompile *acfg)
4593 int file_index, res, method_index, i;
4600 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4602 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4607 infile = fopen (tmp, "r");
4610 printf ("Using profile data file '%s'\n", tmp);
4615 res = fscanf (infile, "%32s\n", ver);
4616 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4617 printf ("Profile file has wrong version or invalid.\n");
4624 MonoMethodDesc *desc;
4627 if (fgets (name, 1023, infile) == NULL)
4630 /* Kill the newline */
4631 if (strlen (name) > 0)
4632 name [strlen (name) - 1] = '\0';
4634 desc = mono_method_desc_new (name, TRUE);
4636 method = mono_method_desc_search_in_image (desc, acfg->image);
4638 if (method && mono_method_get_token (method)) {
4639 token = mono_method_get_token (method);
4640 method_index = mono_metadata_token_index (token) - 1;
4642 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4643 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4646 //printf ("No method found matching '%s'.\n", name);
4652 /* Add missing methods */
4654 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4655 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4656 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4658 unordered = g_list_reverse (unordered);
4659 if (acfg->method_order)
4660 g_list_last (acfg->method_order)->next = unordered;
4662 acfg->method_order = unordered;
4665 /* Used by the LLVM backend */
4667 mono_aot_get_got_offset (MonoJumpInfo *ji)
4669 return get_got_offset (llvm_acfg, ji);
4673 mono_aot_get_method_name (MonoCompile *cfg)
4675 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4677 return g_strdup_printf ("m_%x", method_index);
4681 mono_aot_get_method_debug_name (MonoCompile *cfg)
4683 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4687 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4689 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4690 MonoPltEntry *plt_entry;
4693 ji->data.target = data;
4695 if (!can_encode_patch (llvm_acfg, ji))
4698 plt_entry = get_plt_entry (llvm_acfg, ji);
4700 return g_strdup_printf (plt_entry->symbol);
4704 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4708 mono_acfg_lock (llvm_acfg);
4709 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4710 mono_acfg_unlock (llvm_acfg);
4720 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4724 emit_llvm_file (MonoAotCompile *acfg)
4726 char *command, *opts;
4728 MonoJumpInfo *patch_info;
4729 const char *llc_extra_args;
4732 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4736 /* Compute the final size of the got */
4737 for (i = 0; i < acfg->nmethods; ++i) {
4738 if (acfg->cfgs [i]) {
4739 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4740 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4741 if (!is_plt_patch (patch_info))
4742 get_got_offset (acfg, patch_info);
4744 get_plt_entry (acfg, patch_info);
4750 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4752 if (acfg->aot_opts.full_aot) {
4756 * Need to add the got entries used by the trampolines.
4757 * This is only a conservative approximation.
4759 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4760 /* For the generic + rgctx trampolines */
4761 acfg->final_got_size += 200;
4762 /* For the specific trampolines */
4763 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4764 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4769 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4772 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4773 * a lot of time, and doesn't seem to save much space.
4774 * The following optimizations cannot be enabled:
4776 * - 'jump-threading' changes our blockaddress references to int constants.
4777 * The opt list below was produced by taking the output of:
4778 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4779 * then removing tailcallelim + the global opts, and adding a second gvn.
4781 opts = g_strdup ("-instcombine -simplifycfg");
4782 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");
4784 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4785 printf ("Executing opt: %s\n", command);
4786 if (system (command) != 0) {
4792 #if !LLVM_CHECK_VERSION(2, 8)
4793 /* LLVM 2.8 removed the -f flag ??? */
4794 llc_extra_args = "-f";
4796 llc_extra_args = "";
4798 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);
4800 printf ("Executing llc: %s\n", command);
4802 if (system (command) != 0) {
4809 emit_code (MonoAotCompile *acfg)
4813 char end_symbol [256];
4816 #if defined(TARGET_POWERPC64)
4817 sprintf (symbol, ".Lgot_addr");
4818 emit_section_change (acfg, ".text", 0);
4819 emit_alignment (acfg, 8);
4820 emit_label (acfg, symbol);
4821 emit_pointer (acfg, acfg->got_symbol);
4825 * This global symbol is used to compute the address of each method using the
4826 * code_offsets array. It is also used to compute the memory ranges occupied by
4827 * AOT code, so it must be equal to the address of the first emitted method.
4829 sprintf (symbol, "methods");
4830 emit_section_change (acfg, ".text", 0);
4831 emit_global (acfg, symbol, TRUE);
4832 emit_alignment (acfg, 8);
4834 for (i = 0; i < acfg->nmethods; ++i) {
4835 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4836 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4840 if (i == acfg->nmethods)
4841 /* No LLVM compiled methods */
4842 emit_label (acfg, symbol);
4844 emit_label (acfg, symbol);
4848 * Emit some padding so the local symbol for the first method doesn't have the
4849 * same address as 'methods'.
4851 emit_zero_bytes (acfg, 16);
4853 for (l = acfg->method_order; l != NULL; l = l->next) {
4857 i = GPOINTER_TO_UINT (l->data);
4859 cfg = acfg->cfgs [i];
4864 method = cfg->orig_method;
4866 /* Emit unbox trampoline */
4867 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4868 char call_target [256];
4870 if (!method->wrapper_type && !method->is_inflated) {
4871 g_assert (method->token);
4872 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4874 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4877 emit_section_change (acfg, ".text", 0);
4878 #ifdef __native_client_codegen__
4879 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4881 emit_global (acfg, symbol, TRUE);
4882 emit_label (acfg, symbol);
4884 sprintf (call_target, "%s", cfg->asm_symbol);
4886 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4889 if (cfg->compile_llvm)
4890 acfg->stats.llvm_count ++;
4892 emit_method_code (acfg, cfg);
4895 sprintf (symbol, "methods_end");
4896 emit_section_change (acfg, ".text", 0);
4897 emit_global (acfg, symbol, FALSE);
4898 emit_alignment (acfg, 8);
4899 emit_label (acfg, symbol);
4901 sprintf (symbol, "code_offsets");
4902 emit_section_change (acfg, RODATA_SECT, 1);
4903 emit_global (acfg, symbol, FALSE);
4904 emit_alignment (acfg, 8);
4905 emit_label (acfg, symbol);
4907 acfg->stats.offsets_size += acfg->nmethods * 4;
4909 sprintf (end_symbol, "methods");
4910 for (i = 0; i < acfg->nmethods; ++i) {
4911 if (acfg->cfgs [i]) {
4912 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4914 emit_int32 (acfg, 0xffffffff);
4921 emit_info (MonoAotCompile *acfg)
4928 offsets = g_new0 (gint32, acfg->nmethods);
4930 for (l = acfg->method_order; l != NULL; l = l->next) {
4931 i = GPOINTER_TO_UINT (l->data);
4933 if (acfg->cfgs [i]) {
4934 emit_method_info (acfg, acfg->cfgs [i]);
4935 offsets [i] = acfg->cfgs [i]->method_info_offset;
4941 sprintf (symbol, "method_info_offsets");
4942 emit_section_change (acfg, RODATA_SECT, 1);
4943 emit_global (acfg, symbol, FALSE);
4944 emit_alignment (acfg, 8);
4945 emit_label (acfg, symbol);
4947 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4952 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4954 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4955 #define mix(a,b,c) { \
4956 a -= c; a ^= rot(c, 4); c += b; \
4957 b -= a; b ^= rot(a, 6); a += c; \
4958 c -= b; c ^= rot(b, 8); b += a; \
4959 a -= c; a ^= rot(c,16); c += b; \
4960 b -= a; b ^= rot(a,19); a += c; \
4961 c -= b; c ^= rot(b, 4); b += a; \
4963 #define final(a,b,c) { \
4964 c ^= b; c -= rot(b,14); \
4965 a ^= c; a -= rot(c,11); \
4966 b ^= a; b -= rot(a,25); \
4967 c ^= b; c -= rot(b,16); \
4968 a ^= c; a -= rot(c,4); \
4969 b ^= a; b -= rot(a,14); \
4970 c ^= b; c -= rot(b,24); \
4974 mono_aot_type_hash (MonoType *t1)
4976 guint hash = t1->type;
4978 hash |= t1->byref << 6; /* do not collide with t1->type values */
4980 case MONO_TYPE_VALUETYPE:
4981 case MONO_TYPE_CLASS:
4982 case MONO_TYPE_SZARRAY:
4983 /* check if the distribution is good enough */
4984 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4986 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4987 case MONO_TYPE_ARRAY:
4988 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4989 case MONO_TYPE_GENERICINST:
4990 return ((hash << 5) - hash) ^ 0;
4996 * mono_aot_method_hash:
4998 * Return a hash code for methods which only depends on metadata.
5001 mono_aot_method_hash (MonoMethod *method)
5003 MonoMethodSignature *sig;
5007 guint32 *hashes_start, *hashes;
5010 /* Similar to the hash in mono_method_get_imt_slot () */
5012 sig = mono_method_signature (method);
5014 hashes_count = sig->param_count + 5;
5015 hashes_start = malloc (hashes_count * sizeof (guint32));
5016 hashes = hashes_start;
5018 /* Some wrappers are assigned to random classes */
5019 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5020 klass = method->klass;
5022 klass = mono_defaults.object_class;
5024 if (!method->wrapper_type) {
5025 char *full_name = mono_type_full_name (&klass->byval_arg);
5027 hashes [0] = mono_metadata_str_hash (full_name);
5031 hashes [0] = mono_metadata_str_hash (klass->name);
5032 hashes [1] = mono_metadata_str_hash (klass->name_space);
5034 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5035 /* The method name includes a stringified pointer */
5038 hashes [2] = mono_metadata_str_hash (method->name);
5039 hashes [3] = method->wrapper_type;
5040 hashes [4] = mono_aot_type_hash (sig->ret);
5041 for (i = 0; i < sig->param_count; i++) {
5042 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
5045 /* Setup internal state */
5046 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5048 /* Handle most of the hashes */
5049 while (hashes_count > 3) {
5058 /* Handle the last 3 hashes (all the case statements fall through) */
5059 switch (hashes_count) {
5060 case 3 : c += hashes [2];
5061 case 2 : b += hashes [1];
5062 case 1 : a += hashes [0];
5064 case 0: /* nothing left to add */
5068 free (hashes_start);
5077 * mono_aot_wrapper_name:
5079 * Return a string which uniqely identifies the given wrapper method.
5082 mono_aot_wrapper_name (MonoMethod *method)
5084 char *name, *tmpsig, *klass_desc;
5086 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5088 switch (method->wrapper_type) {
5089 case MONO_WRAPPER_RUNTIME_INVOKE:
5090 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5091 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5093 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5096 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5097 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5098 g_free (klass_desc);
5108 * mono_aot_get_array_helper_from_wrapper;
5110 * Get the helper method in Array called by an array wrapper method.
5113 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5117 MonoGenericContext ctx;
5118 MonoType *args [16];
5119 char *mname, *iname, *s, *s2, *helper_name = NULL;
5121 prefix = "System.Collections.Generic";
5122 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5123 s2 = strstr (s, "`1.");
5129 //printf ("X: %s %s\n", iname, mname);
5131 if (!strcmp (iname, "IList"))
5132 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5134 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5135 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5137 g_free (helper_name);
5140 if (m->is_generic) {
5141 memset (&ctx, 0, sizeof (ctx));
5142 args [0] = &method->klass->element_class->byval_arg;
5143 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5144 m = mono_class_inflate_generic_method (m, &ctx);
5150 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5152 typedef struct HashEntry {
5153 guint32 key, value, index;
5154 struct HashEntry *next;
5158 * emit_extra_methods:
5160 * Emit methods which are not in the METHOD table, like wrappers.
5163 emit_extra_methods (MonoAotCompile *acfg)
5165 int i, table_size, buf_size;
5168 guint32 *info_offsets;
5171 HashEntry *entry, *new_entry;
5172 int nmethods, max_chain_length;
5175 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5177 /* Emit method info */
5179 for (i = 0; i < acfg->extra_methods->len; ++i) {
5180 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5181 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5188 p = buf = g_malloc (buf_size);
5192 method = cfg->method_to_register;
5195 if (method->wrapper_type) {
5197 * We encode some wrappers using their name, since encoding them
5198 * directly would be difficult. This also avoids creating the wrapper
5199 * methods at runtime, since they are not needed anyway.
5201 switch (method->wrapper_type) {
5202 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5203 case MONO_WRAPPER_SYNCHRONIZED:
5204 /* encode_method_ref () can handle these */
5206 case MONO_WRAPPER_RUNTIME_INVOKE:
5207 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5208 /* Direct wrapper, encode normally */
5212 name = mono_aot_wrapper_name (method);
5218 encode_value (1, p, &p);
5219 encode_value (method->wrapper_type, p, &p);
5220 strcpy ((char*)p, name);
5221 p += strlen (name ) + 1;
5224 encode_value (0, p, &p);
5225 encode_method_ref (acfg, method, p, &p);
5228 g_assert ((p - buf) < buf_size);
5230 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5235 * Construct a chained hash table for mapping indexes in extra_method_info to
5238 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5239 table = g_ptr_array_sized_new (table_size);
5240 for (i = 0; i < table_size; ++i)
5241 g_ptr_array_add (table, NULL);
5242 chain_lengths = g_new0 (int, table_size);
5243 max_chain_length = 0;
5244 for (i = 0; i < acfg->extra_methods->len; ++i) {
5245 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5246 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5252 key = info_offsets [i];
5253 value = get_method_index (acfg, method);
5255 hash = mono_aot_method_hash (method) % table_size;
5257 chain_lengths [hash] ++;
5258 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5260 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5261 new_entry->key = key;
5262 new_entry->value = value;
5264 entry = g_ptr_array_index (table, hash);
5265 if (entry == NULL) {
5266 new_entry->index = hash;
5267 g_ptr_array_index (table, hash) = new_entry;
5270 entry = entry->next;
5272 entry->next = new_entry;
5273 new_entry->index = table->len;
5274 g_ptr_array_add (table, new_entry);
5278 //printf ("MAX: %d\n", max_chain_length);
5280 /* Emit the table */
5281 sprintf (symbol, "extra_method_table");
5282 emit_section_change (acfg, RODATA_SECT, 0);
5283 emit_global (acfg, symbol, FALSE);
5284 emit_alignment (acfg, 8);
5285 emit_label (acfg, symbol);
5287 emit_int32 (acfg, table_size);
5288 for (i = 0; i < table->len; ++i) {
5289 HashEntry *entry = g_ptr_array_index (table, i);
5291 if (entry == NULL) {
5292 emit_int32 (acfg, 0);
5293 emit_int32 (acfg, 0);
5294 emit_int32 (acfg, 0);
5296 //g_assert (entry->key > 0);
5297 emit_int32 (acfg, entry->key);
5298 emit_int32 (acfg, entry->value);
5300 emit_int32 (acfg, entry->next->index);
5302 emit_int32 (acfg, 0);
5307 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5308 * This is used by mono_aot_find_jit_info ().
5310 sprintf (symbol, "extra_method_info_offsets");
5311 emit_section_change (acfg, RODATA_SECT, 0);
5312 emit_global (acfg, symbol, FALSE);
5313 emit_alignment (acfg, 8);
5314 emit_label (acfg, symbol);
5316 emit_int32 (acfg, acfg->extra_methods->len);
5317 for (i = 0; i < acfg->extra_methods->len; ++i) {
5318 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5320 emit_int32 (acfg, get_method_index (acfg, method));
5321 emit_int32 (acfg, info_offsets [i]);
5326 emit_exception_info (MonoAotCompile *acfg)
5332 offsets = g_new0 (gint32, acfg->nmethods);
5333 for (i = 0; i < acfg->nmethods; ++i) {
5334 if (acfg->cfgs [i]) {
5335 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5336 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5342 sprintf (symbol, "ex_info_offsets");
5343 emit_section_change (acfg, RODATA_SECT, 1);
5344 emit_global (acfg, symbol, FALSE);
5345 emit_alignment (acfg, 8);
5346 emit_label (acfg, symbol);
5348 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5353 emit_unwind_info (MonoAotCompile *acfg)
5359 * The unwind info contains a lot of duplicates so we emit each unique
5360 * entry once, and only store the offset from the start of the table in the
5364 sprintf (symbol, "unwind_info");
5365 emit_section_change (acfg, RODATA_SECT, 1);
5366 emit_alignment (acfg, 8);
5367 emit_label (acfg, symbol);
5368 emit_global (acfg, symbol, FALSE);
5370 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5371 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5372 guint8 *unwind_info;
5373 guint32 unwind_info_len;
5377 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5380 encode_value (unwind_info_len, p, &p);
5381 emit_bytes (acfg, buf, p - buf);
5382 emit_bytes (acfg, unwind_info, unwind_info_len);
5384 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5389 emit_class_info (MonoAotCompile *acfg)
5395 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5396 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5397 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5399 sprintf (symbol, "class_info_offsets");
5400 emit_section_change (acfg, RODATA_SECT, 1);
5401 emit_global (acfg, symbol, FALSE);
5402 emit_alignment (acfg, 8);
5403 emit_label (acfg, symbol);
5405 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5409 typedef struct ClassNameTableEntry {
5410 guint32 token, index;
5411 struct ClassNameTableEntry *next;
5412 } ClassNameTableEntry;
5415 emit_class_name_table (MonoAotCompile *acfg)
5418 guint32 token, hash;
5423 ClassNameTableEntry *entry, *new_entry;
5426 * Construct a chained hash table for mapping class names to typedef tokens.
5428 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5429 table = g_ptr_array_sized_new (table_size);
5430 for (i = 0; i < table_size; ++i)
5431 g_ptr_array_add (table, NULL);
5432 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5433 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5434 klass = mono_class_get (acfg->image, token);
5437 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5438 hash = mono_metadata_str_hash (full_name) % table_size;
5441 /* FIXME: Allocate from the mempool */
5442 new_entry = g_new0 (ClassNameTableEntry, 1);
5443 new_entry->token = token;
5445 entry = g_ptr_array_index (table, hash);
5446 if (entry == NULL) {
5447 new_entry->index = hash;
5448 g_ptr_array_index (table, hash) = new_entry;
5451 entry = entry->next;
5453 entry->next = new_entry;
5454 new_entry->index = table->len;
5455 g_ptr_array_add (table, new_entry);
5459 /* Emit the table */
5460 sprintf (symbol, "class_name_table");
5461 emit_section_change (acfg, RODATA_SECT, 0);
5462 emit_global (acfg, symbol, FALSE);
5463 emit_alignment (acfg, 8);
5464 emit_label (acfg, symbol);
5466 /* FIXME: Optimize memory usage */
5467 g_assert (table_size < 65000);
5468 emit_int16 (acfg, table_size);
5469 g_assert (table->len < 65000);
5470 for (i = 0; i < table->len; ++i) {
5471 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5473 if (entry == NULL) {
5474 emit_int16 (acfg, 0);
5475 emit_int16 (acfg, 0);
5477 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5479 emit_int16 (acfg, entry->next->index);
5481 emit_int16 (acfg, 0);
5487 emit_image_table (MonoAotCompile *acfg)
5493 * The image table is small but referenced in a lot of places.
5494 * So we emit it at once, and reference its elements by an index.
5497 sprintf (symbol, "mono_image_table");
5498 emit_section_change (acfg, RODATA_SECT, 1);
5499 emit_global (acfg, symbol, FALSE);
5500 emit_alignment (acfg, 8);
5501 emit_label (acfg, symbol);
5503 emit_int32 (acfg, acfg->image_table->len);
5504 for (i = 0; i < acfg->image_table->len; i++) {
5505 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5506 MonoAssemblyName *aname = &image->assembly->aname;
5508 /* FIXME: Support multi-module assemblies */
5509 g_assert (image->assembly->image == image);
5511 emit_string (acfg, image->assembly_name);
5512 emit_string (acfg, image->guid);
5513 emit_string (acfg, aname->culture ? aname->culture : "");
5514 emit_string (acfg, (const char*)aname->public_key_token);
5516 emit_alignment (acfg, 8);
5517 emit_int32 (acfg, aname->flags);
5518 emit_int32 (acfg, aname->major);
5519 emit_int32 (acfg, aname->minor);
5520 emit_int32 (acfg, aname->build);
5521 emit_int32 (acfg, aname->revision);
5526 emit_got_info (MonoAotCompile *acfg)
5529 int i, first_plt_got_patch, buf_size;
5531 guint32 *got_info_offsets;
5533 /* Add the patches needed by the PLT to the GOT */
5534 acfg->plt_got_offset_base = acfg->got_offset;
5535 first_plt_got_patch = acfg->got_patches->len;
5536 for (i = 1; i < acfg->plt_offset; ++i) {
5537 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5539 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5542 acfg->got_offset += acfg->plt_offset;
5546 * - optimize offsets table.
5547 * - reduce number of exported symbols.
5548 * - emit info for a klass only once.
5549 * - determine when a method uses a GOT slot which is guaranteed to be already
5551 * - clean up and document the code.
5552 * - use String.Empty in class libs.
5555 /* Encode info required to decode shared GOT entries */
5556 buf_size = acfg->got_patches->len * 128;
5557 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5558 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5559 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5561 if (acfg->plt_offset)
5562 acfg->plt_got_info_offsets [0] = 0;
5563 for (i = 0; i < acfg->got_patches->len; ++i) {
5564 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5568 encode_value (ji->type, p, &p);
5569 encode_patch (acfg, ji, p, &p);
5571 g_assert (p - buf <= buf_size);
5572 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5574 if (i >= first_plt_got_patch)
5575 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5576 acfg->stats.got_info_size += p - buf;
5579 /* Emit got_info_offsets table */
5580 sprintf (symbol, "got_info_offsets");
5581 emit_section_change (acfg, RODATA_SECT, 1);
5582 emit_global (acfg, symbol, FALSE);
5583 emit_alignment (acfg, 8);
5584 emit_label (acfg, symbol);
5586 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5587 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5591 emit_got (MonoAotCompile *acfg)
5596 /* Don't make GOT global so accesses to it don't need relocations */
5597 sprintf (symbol, "%s", acfg->got_symbol);
5598 emit_section_change (acfg, ".bss", 0);
5599 emit_alignment (acfg, 8);
5600 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5601 emit_label (acfg, symbol);
5602 if (acfg->got_offset > 0)
5603 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5605 sprintf (symbol, "got_end");
5606 emit_label (acfg, symbol);
5609 sprintf (symbol, "mono_aot_got_addr");
5610 emit_section_change (acfg, ".data", 0);
5611 emit_global (acfg, symbol, FALSE);
5612 emit_alignment (acfg, 8);
5613 emit_label (acfg, symbol);
5614 emit_pointer (acfg, acfg->got_symbol);
5617 typedef struct GlobalsTableEntry {
5618 guint32 value, index;
5619 struct GlobalsTableEntry *next;
5620 } GlobalsTableEntry;
5623 emit_globals_table (MonoAotCompile *acfg)
5629 GlobalsTableEntry *entry, *new_entry;
5632 * Construct a chained hash table for mapping global names to their index in
5633 * the globals table.
5635 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5636 table = g_ptr_array_sized_new (table_size);
5637 for (i = 0; i < table_size; ++i)
5638 g_ptr_array_add (table, NULL);
5639 for (i = 0; i < acfg->globals->len; ++i) {
5640 char *name = g_ptr_array_index (acfg->globals, i);
5642 hash = mono_metadata_str_hash (name) % table_size;
5644 /* FIXME: Allocate from the mempool */
5645 new_entry = g_new0 (GlobalsTableEntry, 1);
5646 new_entry->value = i;
5648 entry = g_ptr_array_index (table, hash);
5649 if (entry == NULL) {
5650 new_entry->index = hash;
5651 g_ptr_array_index (table, hash) = new_entry;
5654 entry = entry->next;
5656 entry->next = new_entry;
5657 new_entry->index = table->len;
5658 g_ptr_array_add (table, new_entry);
5662 /* Emit the table */
5663 sprintf (symbol, ".Lglobals_hash");
5664 emit_section_change (acfg, RODATA_SECT, 0);
5665 emit_alignment (acfg, 8);
5666 emit_label (acfg, symbol);
5668 /* FIXME: Optimize memory usage */
5669 g_assert (table_size < 65000);
5670 emit_int16 (acfg, table_size);
5671 for (i = 0; i < table->len; ++i) {
5672 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5674 if (entry == NULL) {
5675 emit_int16 (acfg, 0);
5676 emit_int16 (acfg, 0);
5678 emit_int16 (acfg, entry->value + 1);
5680 emit_int16 (acfg, entry->next->index);
5682 emit_int16 (acfg, 0);
5686 /* Emit the names */
5687 for (i = 0; i < acfg->globals->len; ++i) {
5688 char *name = g_ptr_array_index (acfg->globals, i);
5690 sprintf (symbol, "name_%d", i);
5691 emit_section_change (acfg, RODATA_SECT, 1);
5692 emit_label (acfg, symbol);
5693 emit_string (acfg, name);
5696 /* Emit the globals table */
5697 sprintf (symbol, ".Lglobals");
5698 emit_section_change (acfg, ".data", 0);
5699 /* This is not a global, since it is accessed by the init function */
5700 emit_alignment (acfg, 8);
5701 emit_label (acfg, symbol);
5703 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5704 emit_pointer (acfg, symbol);
5706 for (i = 0; i < acfg->globals->len; ++i) {
5707 char *name = g_ptr_array_index (acfg->globals, i);
5709 sprintf (symbol, "name_%d", i);
5710 emit_pointer (acfg, symbol);
5712 sprintf (symbol, "%s", name);
5713 emit_pointer (acfg, symbol);
5715 /* Null terminate the table */
5716 emit_int32 (acfg, 0);
5717 emit_int32 (acfg, 0);
5721 emit_globals (MonoAotCompile *acfg)
5725 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5727 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5729 if (acfg->aot_opts.bind_to_runtime_version) {
5730 build_info = mono_get_runtime_build_info ();
5731 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5732 g_free (build_info);
5734 emit_string_symbol (acfg, "mono_runtime_version", "");
5738 * When static linking, we emit a global which will point to the symbol table.
5740 if (acfg->aot_opts.static_link) {
5744 /* Emit a string holding the assembly name */
5745 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5747 emit_globals_table (acfg);
5750 * Emit a global symbol which can be passed by an embedding app to
5751 * mono_aot_register_module ().
5753 #if defined(__MACH__) && !defined(__native_client_codegen__)
5754 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5756 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5759 /* Get rid of characters which cannot occur in symbols */
5761 for (p = symbol; *p; ++p) {
5762 if (!(isalnum (*p) || *p == '_'))
5765 acfg->static_linking_symbol = g_strdup (symbol);
5766 emit_global_inner (acfg, symbol, FALSE);
5767 emit_alignment (acfg, 8);
5768 emit_label (acfg, symbol);
5769 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5770 emit_pointer (acfg, symbol);
5775 emit_autoreg (MonoAotCompile *acfg)
5780 * Emit a function into the .ctor section which will be called by the ELF
5781 * loader to register this module with the runtime.
5783 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5786 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5788 arch_emit_autoreg (acfg, symbol);
5794 emit_mem_end (MonoAotCompile *acfg)
5798 sprintf (symbol, "mem_end");
5799 emit_section_change (acfg, ".text", 1);
5800 emit_global (acfg, symbol, FALSE);
5801 emit_alignment (acfg, 8);
5802 emit_label (acfg, symbol);
5806 * Emit a structure containing all the information not stored elsewhere.
5809 emit_file_info (MonoAotCompile *acfg)
5814 const char *gc_name;
5817 * The managed allocators are GC specific, so can't use an AOT image created by one GC
5820 gc_name = mono_gc_get_gc_name ();
5821 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
5823 sprintf (symbol, "mono_aot_file_info");
5824 emit_section_change (acfg, ".data", 0);
5825 emit_alignment (acfg, 8);
5826 emit_label (acfg, symbol);
5827 emit_global (acfg, symbol, FALSE);
5829 /* The data emitted here must match MonoAotFileInfo. */
5830 emit_int32 (acfg, acfg->plt_got_offset_base);
5831 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5832 emit_int32 (acfg, acfg->plt_offset);
5833 emit_int32 (acfg, acfg->nmethods);
5834 emit_int32 (acfg, acfg->flags);
5835 emit_int32 (acfg, acfg->opts);
5836 emit_int32 (acfg, gc_name_offset);
5838 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5839 emit_int32 (acfg, acfg->num_trampolines [i]);
5840 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5841 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5842 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5843 emit_int32 (acfg, acfg->trampoline_size [i]);
5847 emit_blob (MonoAotCompile *acfg)
5851 sprintf (symbol, "blob");
5852 emit_section_change (acfg, RODATA_SECT, 1);
5853 emit_global (acfg, symbol, FALSE);
5854 emit_alignment (acfg, 8);
5855 emit_label (acfg, symbol);
5857 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5861 emit_dwarf_info (MonoAotCompile *acfg)
5863 #ifdef EMIT_DWARF_INFO
5865 char symbol [128], symbol2 [128];
5867 /* DIEs for methods */
5868 for (i = 0; i < acfg->nmethods; ++i) {
5869 MonoCompile *cfg = acfg->cfgs [i];
5874 // FIXME: LLVM doesn't define .Lme_...
5875 if (cfg->compile_llvm)
5878 sprintf (symbol, "%s", cfg->asm_symbol);
5879 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5881 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 ()));
5887 collect_methods (MonoAotCompile *acfg)
5890 MonoImage *image = acfg->image;
5892 /* Collect methods */
5893 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5895 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5897 method = mono_get_method (acfg->image, token, NULL);
5900 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5904 /* Load all methods eagerly to skip the slower lazy loading code */
5905 mono_class_setup_methods (method->klass);
5907 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5908 /* Compile the wrapper instead */
5909 /* We do this here instead of add_wrappers () because it is easy to do it here */
5910 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5914 /* FIXME: Some mscorlib methods don't have debug info */
5916 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5917 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5918 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5919 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5920 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5921 if (!mono_debug_lookup_method (method)) {
5922 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5929 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5930 add_method_with_index (acfg, method, i, FALSE);
5931 acfg->method_index ++;
5934 add_generic_instances (acfg);
5936 if (acfg->aot_opts.full_aot)
5937 add_wrappers (acfg);
5941 compile_methods (MonoAotCompile *acfg)
5945 if (acfg->aot_opts.nthreads > 0) {
5950 gpointer *user_data;
5951 MonoMethod **methods;
5953 methods_len = acfg->methods->len;
5955 len = acfg->methods->len / acfg->aot_opts.nthreads;
5958 * Partition the list of methods into fragments, and hand it to threads to
5961 threads = g_ptr_array_new ();
5962 /* Make a copy since acfg->methods is modified by compile_method () */
5963 methods = g_new0 (MonoMethod*, methods_len);
5964 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5965 for (i = 0; i < methods_len; ++i)
5966 methods [i] = g_ptr_array_index (acfg->methods, i);
5968 while (i < methods_len) {
5969 frag = g_ptr_array_new ();
5970 for (j = 0; j < len; ++j) {
5971 if (i < methods_len) {
5972 g_ptr_array_add (frag, methods [i]);
5977 user_data = g_new0 (gpointer, 3);
5978 user_data [0] = mono_domain_get ();
5979 user_data [1] = acfg;
5980 user_data [2] = frag;
5982 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5983 g_ptr_array_add (threads, handle);
5987 for (i = 0; i < threads->len; ++i) {
5988 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5994 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5995 for (i = methods_len; i < acfg->methods->len; ++i) {
5996 /* This can new methods to acfg->methods */
5997 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6002 compile_asm (MonoAotCompile *acfg)
6004 char *command, *objfile;
6005 char *outfile_name, *tmp_outfile_name;
6006 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6008 #if defined(TARGET_AMD64)
6009 #define AS_OPTIONS "--64"
6010 #elif defined(TARGET_POWERPC64)
6011 #define AS_OPTIONS "-a64 -mppc64"
6012 #define LD_OPTIONS "-m elf64ppc"
6013 #elif defined(sparc) && SIZEOF_VOID_P == 8
6014 #define AS_OPTIONS "-xarch=v9"
6016 #define AS_OPTIONS ""
6019 #ifdef __native_client_codegen__
6020 #define AS_NAME "nacl-as"
6022 #define AS_NAME "as"
6026 #define LD_OPTIONS ""
6030 #define EH_LD_OPTIONS "--eh-frame-hdr"
6032 #define EH_LD_OPTIONS ""
6035 if (acfg->aot_opts.asm_only) {
6036 printf ("Output file: '%s'.\n", acfg->tmpfname);
6037 if (acfg->aot_opts.static_link)
6038 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6042 if (acfg->aot_opts.static_link) {
6043 if (acfg->aot_opts.outfile)
6044 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6046 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6048 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6050 command = g_strdup_printf ("%s%s %s %s -o %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->tmpfname, objfile);
6051 printf ("Executing the native assembler: %s\n", command);
6052 if (system (command) != 0) {
6060 if (acfg->aot_opts.static_link) {
6061 printf ("Output file: '%s'.\n", objfile);
6062 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6067 if (acfg->aot_opts.outfile)
6068 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6070 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6072 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6075 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6076 #elif defined(__ppc__) && defined(__MACH__)
6077 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6078 #elif defined(HOST_WIN32)
6079 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6081 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6083 printf ("Executing the native linker: %s\n", command);
6084 if (system (command) != 0) {
6085 g_free (tmp_outfile_name);
6086 g_free (outfile_name);
6094 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6095 printf ("Stripping the binary: %s\n", com);
6099 #if defined(TARGET_ARM) && !defined(__MACH__)
6101 * gas generates 'mapping symbols' each time code and data is mixed, which
6102 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6104 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6105 printf ("Stripping the binary: %s\n", command);
6106 if (system (command) != 0) {
6107 g_free (tmp_outfile_name);
6108 g_free (outfile_name);
6115 rename (tmp_outfile_name, outfile_name);
6117 g_free (tmp_outfile_name);
6118 g_free (outfile_name);
6121 if (acfg->aot_opts.save_temps)
6122 printf ("Retained input file.\n");
6124 unlink (acfg->tmpfname);
6129 static MonoAotCompile*
6130 acfg_create (MonoAssembly *ass, guint32 opts)
6132 MonoImage *image = ass->image;
6133 MonoAotCompile *acfg;
6136 acfg = g_new0 (MonoAotCompile, 1);
6137 acfg->methods = g_ptr_array_new ();
6138 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6139 acfg->method_depth = g_hash_table_new (NULL, NULL);
6140 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6141 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6142 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6143 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6144 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6145 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6146 acfg->got_patches = g_ptr_array_new ();
6147 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6148 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6149 acfg->image_hash = g_hash_table_new (NULL, NULL);
6150 acfg->image_table = g_ptr_array_new ();
6151 acfg->globals = g_ptr_array_new ();
6152 acfg->image = image;
6154 acfg->mempool = mono_mempool_new ();
6155 acfg->extra_methods = g_ptr_array_new ();
6156 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6157 acfg->unwind_ops = g_ptr_array_new ();
6158 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6159 InitializeCriticalSection (&acfg->mutex);
6165 acfg_free (MonoAotCompile *acfg)
6169 img_writer_destroy (acfg->w);
6170 for (i = 0; i < acfg->nmethods; ++i)
6172 g_free (acfg->cfgs [i]);
6173 g_free (acfg->cfgs);
6174 g_free (acfg->static_linking_symbol);
6175 g_free (acfg->got_symbol);
6176 g_free (acfg->plt_symbol);
6177 g_ptr_array_free (acfg->methods, TRUE);
6178 g_ptr_array_free (acfg->got_patches, TRUE);
6179 g_ptr_array_free (acfg->image_table, TRUE);
6180 g_ptr_array_free (acfg->globals, TRUE);
6181 g_ptr_array_free (acfg->unwind_ops, TRUE);
6182 g_hash_table_destroy (acfg->method_indexes);
6183 g_hash_table_destroy (acfg->method_depth);
6184 g_hash_table_destroy (acfg->plt_offset_to_entry);
6185 g_hash_table_destroy (acfg->patch_to_plt_entry);
6186 g_hash_table_destroy (acfg->patch_to_got_offset);
6187 g_hash_table_destroy (acfg->method_to_cfg);
6188 g_hash_table_destroy (acfg->token_info_hash);
6189 g_hash_table_destroy (acfg->image_hash);
6190 g_hash_table_destroy (acfg->unwind_info_offsets);
6191 g_hash_table_destroy (acfg->method_label_hash);
6192 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6193 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6194 g_free (acfg->patch_to_got_offset_by_type);
6195 mono_mempool_destroy (acfg->mempool);
6200 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6202 MonoImage *image = ass->image;
6204 MonoAotCompile *acfg;
6205 char *outfile_name, *tmp_outfile_name, *p;
6209 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6211 acfg = acfg_create (ass, opts);
6213 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6214 acfg->aot_opts.write_symbols = TRUE;
6215 acfg->aot_opts.ntrampolines = 1024;
6216 acfg->aot_opts.nrgctx_trampolines = 1024;
6217 acfg->aot_opts.nimt_trampolines = 128;
6219 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6221 if (acfg->aot_opts.static_link)
6222 acfg->aot_opts.autoreg = TRUE;
6224 //acfg->aot_opts.print_skipped_methods = TRUE;
6226 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6227 if (acfg->aot_opts.full_aot) {
6228 printf ("--aot=full is not supported on this platform.\n");
6233 if (acfg->aot_opts.static_link)
6234 acfg->aot_opts.asm_writer = TRUE;
6236 if (acfg->aot_opts.soft_debug) {
6237 MonoDebugOptions *opt = mini_get_debug_options ();
6239 opt->mdb_optimizations = TRUE;
6240 opt->gen_seq_points = TRUE;
6242 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6243 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6250 acfg->aot_opts.asm_writer = TRUE;
6251 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6254 if (acfg->aot_opts.full_aot)
6255 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6257 load_profile_files (acfg);
6259 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6260 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6261 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6263 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6265 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6266 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6268 /* Get rid of characters which cannot occur in symbols */
6269 for (p = acfg->got_symbol_base; *p; ++p) {
6270 if (!(isalnum (*p) || *p == '_'))
6273 for (p = acfg->plt_symbol; *p; ++p) {
6274 if (!(isalnum (*p) || *p == '_'))
6278 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6281 * The prefix LLVM likes to put in front of symbol names on darwin.
6282 * The mach-os specs require this for globals, but LLVM puts them in front of all
6283 * symbols. We need to handle this, since we need to refer to LLVM generated
6286 acfg->llvm_label_prefix = "";
6288 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6290 acfg->method_index = 1;
6292 collect_methods (acfg);
6294 acfg->cfgs_size = acfg->methods->len + 32;
6295 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6297 /* PLT offset 0 is reserved for the PLT trampoline */
6298 acfg->plt_offset = 1;
6302 mono_llvm_create_aot_module (acfg->got_symbol_base);
6305 /* GOT offset 0 is reserved for the address of the current assembly */
6309 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6310 ji->type = MONO_PATCH_INFO_IMAGE;
6311 ji->data.image = acfg->image;
6313 get_got_offset (acfg, ji);
6315 /* Slot 1 is reserved for the mscorlib got addr */
6316 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6317 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6318 get_got_offset (acfg, ji);
6323 compile_methods (acfg);
6327 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6333 if (acfg->aot_opts.asm_only) {
6334 if (acfg->aot_opts.outfile)
6335 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6337 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6339 acfg->tmpfname = g_strdup ("temp.s");
6343 emit_llvm_file (acfg);
6346 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6347 if (acfg->aot_opts.outfile)
6348 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6350 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6353 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6354 * it might be in another file system so the rename () won't work.
6356 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6358 acfg->fp = fopen (tmp_outfile_name, "w");
6360 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6364 acfg->w = img_writer_create (acfg->fp, TRUE);
6365 acfg->use_bin_writer = TRUE;
6368 /* Append to the .s file created by llvm */
6369 /* FIXME: Use multiple files instead */
6370 acfg->fp = fopen (acfg->tmpfname, "a+");
6372 if (acfg->aot_opts.asm_only) {
6373 if (acfg->aot_opts.outfile)
6374 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6376 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6377 acfg->fp = fopen (acfg->tmpfname, "w+");
6379 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6380 acfg->fp = fdopen (i, "w+");
6382 g_assert (acfg->fp);
6384 acfg->w = img_writer_create (acfg->fp, FALSE);
6386 tmp_outfile_name = NULL;
6387 outfile_name = NULL;
6390 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6392 /* Compute symbols for methods */
6393 for (i = 0; i < acfg->nmethods; ++i) {
6394 if (acfg->cfgs [i]) {
6395 MonoCompile *cfg = acfg->cfgs [i];
6396 int method_index = get_method_index (acfg, cfg->orig_method);
6398 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6402 if (!acfg->aot_opts.nodebug)
6403 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6405 img_writer_emit_start (acfg->w);
6408 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6414 emit_extra_methods (acfg);
6416 emit_trampolines (acfg);
6418 emit_class_name_table (acfg);
6420 emit_got_info (acfg);
6422 emit_exception_info (acfg);
6424 emit_unwind_info (acfg);
6426 emit_class_info (acfg);
6430 emit_image_table (acfg);
6434 emit_file_info (acfg);
6438 emit_globals (acfg);
6440 emit_autoreg (acfg);
6443 emit_dwarf_info (acfg);
6444 mono_dwarf_writer_close (acfg->dwarf);
6447 emit_mem_end (acfg);
6451 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6454 g_assert (acfg->got_offset <= acfg->final_got_size);
6456 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);
6459 res = img_writer_emit_writeout (acfg->w);
6464 if (acfg->use_bin_writer) {
6465 int err = rename (tmp_outfile_name, outfile_name);
6468 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6472 res = compile_asm (acfg);
6479 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6481 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);
6482 if (acfg->stats.genericcount)
6483 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6484 if (acfg->stats.abscount)
6485 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6486 if (acfg->stats.lmfcount)
6487 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6488 if (acfg->stats.ocount)
6489 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6491 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6492 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);
6493 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6495 if (acfg->aot_opts.stats) {
6498 printf ("GOT slot distribution:\n");
6499 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6500 if (acfg->stats.got_slot_types [i])
6501 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6504 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);
6516 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)