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__)
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 static G_GNUC_UNUSED void
334 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
336 img_writer_emit_global (acfg->w, name, func);
340 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
342 if (acfg->aot_opts.no_dlsym) {
343 g_ptr_array_add (acfg->globals, g_strdup (name));
344 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
346 img_writer_emit_global (acfg->w, name, func);
351 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
353 img_writer_emit_symbol_size (acfg->w, name, end_label);
357 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
359 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
360 emit_global (acfg, name, FALSE);
361 img_writer_emit_label (acfg->w, name);
362 img_writer_emit_string (acfg->w, value);
365 static G_GNUC_UNUSED void
366 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
369 guint8 b = value & 0x7f;
371 if (value != 0) /* more bytes to come */
377 static G_GNUC_UNUSED void
378 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
381 gboolean negative = (value < 0);
388 /* the following is unnecessary if the
389 * implementation of >>= uses an arithmetic rather
390 * than logical shift for a signed left operand
394 value |= - ((gint64)1 <<(size - 7));
395 /* sign bit of byte is second high order bit (0x40) */
396 if ((value == 0 && !(byte & 0x40)) ||
397 (value == -1 && (byte & 0x40)))
401 emit_byte (acfg, byte);
405 static G_GNUC_UNUSED void
406 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
411 guint8 b = value & 0x7f;
413 if (value != 0) /* more bytes to come */
421 static G_GNUC_UNUSED void
422 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
425 gboolean negative = (value < 0);
433 /* the following is unnecessary if the
434 * implementation of >>= uses an arithmetic rather
435 * than logical shift for a signed left operand
439 value |= - (1 <<(size - 7));
440 /* sign bit of byte is second high order bit (0x40) */
441 if ((value == 0 && !(byte & 0x40)) ||
442 (value == -1 && (byte & 0x40)))
452 /* ARCHITECTURE SPECIFIC CODE */
454 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
455 #define EMIT_DWARF_INFO 1
458 #if defined(TARGET_ARM)
459 #define AOT_FUNC_ALIGNMENT 4
461 #define AOT_FUNC_ALIGNMENT 16
464 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
465 #define PPC_LD_OP "ld"
466 #define PPC_LDX_OP "ldx"
468 #define PPC_LD_OP "lwz"
469 #define PPC_LDX_OP "lwzx"
475 #define LLVM_LABEL_PREFIX "_"
477 #define LLVM_LABEL_PREFIX ""
482 #define LLC_TARGET_ARGS "-march=arm -mattr=+v6 -mtriple=arm-apple-darwin"
484 //#define LLC_TARGET_ARGS "-march=arm -mtriple=arm-linux-gnueabi -soft-float"
486 #define LLC_TARGET_ARGS ""
490 * arch_emit_direct_call:
492 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
496 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
498 #if defined(TARGET_X86) || defined(TARGET_AMD64)
499 /* Need to make sure this is exactly 5 bytes long */
500 emit_byte (acfg, '\xe8');
501 emit_symbol_diff (acfg, target, ".", -4);
503 #elif defined(TARGET_ARM)
504 if (acfg->use_bin_writer) {
511 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
512 emit_bytes (acfg, buf, 4);
514 img_writer_emit_unset_mode (acfg->w);
515 fprintf (acfg->fp, "bl %s\n", target);
518 #elif defined(TARGET_POWERPC)
519 if (acfg->use_bin_writer) {
520 g_assert_not_reached ();
522 img_writer_emit_unset_mode (acfg->w);
523 fprintf (acfg->fp, "bl %s\n", target);
527 g_assert_not_reached ();
533 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
535 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
536 * in in the 2. slot of every GOT, and require every method to place the GOT
537 * address in r30, even when it doesn't access the GOT otherwise. This way,
538 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
543 * PPC64 uses function descriptors which greatly complicate all code, since
544 * these are used very inconsistently in the runtime. Some functions like
545 * mono_compile_method () return ftn descriptors, while others like the
546 * trampoline creation functions do not.
547 * We assume that all GOT slots contain function descriptors, and create
548 * descriptors in aot-runtime.c when needed.
549 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
550 * from function descriptors, we could do the same, but it would require
551 * rewriting all the ppc/aot code to handle function descriptors properly.
552 * So instead, we use the same approach as on PPC32.
553 * This is a horrible mess, but fixing it would probably lead to an even bigger
559 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
562 #ifdef MONO_ARCH_AOT_SUPPORTED
564 * arch_emit_got_offset:
566 * The memory pointed to by CODE should hold native code for computing the GOT
567 * address. Emit this code while patching it with the offset between code and
568 * the GOT. CODE_SIZE is set to the number of bytes emitted.
571 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
573 #if defined(TARGET_POWERPC64)
574 g_assert (!acfg->use_bin_writer);
575 img_writer_emit_unset_mode (acfg->w);
577 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
578 * unsupported relocations. So we store the got address into the .Lgot_addr
579 * symbol which is in the text segment, compute its address, and load it.
581 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
582 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
583 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
584 fprintf (acfg->fp, "add 30, 30, 0\n");
585 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
586 acfg->label_generator ++;
588 #elif defined(TARGET_POWERPC)
589 g_assert (!acfg->use_bin_writer);
590 img_writer_emit_unset_mode (acfg->w);
591 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
592 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
593 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
594 acfg->label_generator ++;
597 guint32 offset = mono_arch_get_patch_offset (code);
598 emit_bytes (acfg, code, offset);
599 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
601 *code_size = offset + 4;
606 * arch_emit_got_access:
608 * The memory pointed to by CODE should hold native code for loading a GOT
609 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
610 * CODE_SIZE is set to the number of bytes emitted.
613 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
615 /* Emit beginning of instruction */
616 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
618 /* Emit the offset */
620 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
621 *code_size = mono_arch_get_patch_offset (code) + 4;
622 #elif defined(TARGET_X86)
623 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
624 *code_size = mono_arch_get_patch_offset (code) + 4;
625 #elif defined(TARGET_ARM)
626 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
627 *code_size = mono_arch_get_patch_offset (code) + 4;
628 #elif defined(TARGET_POWERPC)
634 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
635 g_assert (code - buf == 8);
636 emit_bytes (acfg, buf, code - buf);
637 *code_size = code - buf;
640 g_assert_not_reached ();
647 * arch_emit_plt_entry:
649 * Emit code for the PLT entry with index INDEX.
652 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
654 #if defined(TARGET_X86)
655 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
657 /* jmp *<offset>(%ebx) */
658 emit_byte (acfg, 0xff);
659 emit_byte (acfg, 0xa3);
660 emit_int32 (acfg, offset);
661 /* Used by mono_aot_get_plt_info_offset */
662 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
663 #elif defined(TARGET_AMD64)
665 * We can't emit jumps because they are 32 bits only so they can't be patched.
666 * So we make indirect calls through GOT entries which are patched by the AOT
667 * loader to point to .Lpd entries.
669 /* jmpq *<offset>(%rip) */
670 emit_byte (acfg, '\xff');
671 emit_byte (acfg, '\x25');
672 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
673 /* Used by mono_aot_get_plt_info_offset */
674 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
675 #elif defined(TARGET_ARM)
680 * - optimize OP_AOTCONST implementation
681 * - optimize the PLT entries
682 * - optimize SWITCH AOT implementation
685 if (acfg->use_bin_writer && FALSE) {
686 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
687 /* We only emit 1 relocation since we implement it ourselves anyway */
688 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
689 /* FIXME: A 2 instruction encoding is sufficient in most cases */
690 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
691 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
692 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
693 emit_bytes (acfg, buf, code - buf);
694 /* Used by mono_aot_get_plt_info_offset */
695 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
697 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
698 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
699 emit_bytes (acfg, buf, code - buf);
700 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
701 /* Used by mono_aot_get_plt_info_offset */
702 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
705 * The plt_got_info_offset is computed automatically by
706 * mono_aot_get_plt_info_offset (), so no need to save it here.
708 #elif defined(TARGET_POWERPC)
709 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
711 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
712 g_assert (!acfg->use_bin_writer);
713 img_writer_emit_unset_mode (acfg->w);
714 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
715 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
716 fprintf (acfg->fp, "add 11, 11, 30\n");
717 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
718 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
719 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
720 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
722 fprintf (acfg->fp, "mtctr 11\n");
723 fprintf (acfg->fp, "bctr\n");
724 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
726 g_assert_not_reached ();
731 * arch_emit_specific_trampoline:
733 * Emit code for a specific trampoline. OFFSET is the offset of the first of
734 * two GOT slots which contain the generic trampoline address and the trampoline
735 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
738 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
741 * The trampolines created here are variations of the specific
742 * trampolines created in mono_arch_create_specific_trampoline (). The
744 * - the generic trampoline address is taken from a got slot.
745 * - the offset of the got slot where the trampoline argument is stored
746 * is embedded in the instruction stream, and the generic trampoline
747 * can load the argument by loading the offset, adding it to the
748 * address of the trampoline to get the address of the got slot, and
749 * loading the argument from there.
750 * - all the trampolines should be of the same length.
752 #if defined(TARGET_AMD64)
753 /* This should be exactly 16 bytes long */
755 /* call *<offset>(%rip) */
756 emit_byte (acfg, '\x41');
757 emit_byte (acfg, '\xff');
758 emit_byte (acfg, '\x15');
759 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
760 /* This should be relative to the start of the trampoline */
761 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
762 emit_zero_bytes (acfg, 5);
763 #elif defined(TARGET_ARM)
767 /* This should be exactly 20 bytes long */
770 ARM_PUSH (code, 0x5fff);
771 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
772 /* Load the value from the GOT */
773 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
775 ARM_BLX_REG (code, ARMREG_R1);
777 g_assert (code - buf == 16);
780 emit_bytes (acfg, buf, code - buf);
782 * Only one offset is needed, since the second one would be equal to the
785 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
786 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
787 #elif defined(TARGET_POWERPC)
794 g_assert (!acfg->use_bin_writer);
797 * PPC has no ip relative addressing, so we need to compute the address
798 * of the mscorlib got. That is slow and complex, so instead, we store it
799 * in the second got slot of every aot image. The caller already computed
800 * the address of its got and placed it into r30.
802 img_writer_emit_unset_mode (acfg->w);
803 /* Load mscorlib got address */
804 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
805 /* Load generic trampoline address */
806 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
807 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
808 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
809 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
810 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
812 fprintf (acfg->fp, "mtctr 11\n");
813 /* Load trampoline argument */
814 /* On ppc, we pass it normally to the generic trampoline */
815 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
816 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
817 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
818 /* Branch to generic trampoline */
819 fprintf (acfg->fp, "bctr\n");
821 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
822 *tramp_size = 10 * 4;
826 #elif defined(TARGET_X86)
830 /* Similar to the PPC code above */
832 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
834 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
835 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
836 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
840 /* Load mscorlib got address */
841 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
842 /* Push trampoline argument */
843 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
844 /* Load generic trampoline address */
845 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
846 /* Branch to generic trampoline */
847 x86_jump_reg (code, X86_ECX);
849 emit_bytes (acfg, buf, code - buf);
852 g_assert (code - buf == *tramp_size);
854 g_assert_not_reached ();
859 * arch_emit_unbox_trampoline:
861 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
862 * CALL_TARGET is the symbol pointing to the native code of METHOD.
865 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
867 #if defined(TARGET_AMD64)
872 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
874 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
876 emit_bytes (acfg, buf, code - buf);
878 emit_byte (acfg, '\xe9');
879 emit_symbol_diff (acfg, call_target, ".", -4);
880 #elif defined(TARGET_X86)
887 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
889 emit_bytes (acfg, buf, code - buf);
892 emit_byte (acfg, '\xe9');
893 emit_symbol_diff (acfg, call_target, ".", -4);
894 #elif defined(TARGET_ARM)
900 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
902 emit_bytes (acfg, buf, code - buf);
904 if (acfg->use_bin_writer) {
911 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
912 emit_bytes (acfg, buf, 4);
914 fprintf (acfg->fp, "\n\tb %s\n", call_target);
916 #elif defined(TARGET_POWERPC)
919 g_assert (!acfg->use_bin_writer);
921 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
922 fprintf (acfg->fp, "\n\tb %s\n", call_target);
924 g_assert_not_reached ();
929 * arch_emit_static_rgctx_trampoline:
931 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
932 * two GOT slots which contain the rgctx argument, and the method to jump to.
933 * TRAMP_SIZE is set to the size of the emitted trampoline.
934 * These kinds of trampolines cannot be enumerated statically, since there could
935 * be one trampoline per method instantiation, so we emit the same code for all
936 * trampolines, and parameterize them using two GOT slots.
939 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
941 #if defined(TARGET_AMD64)
942 /* This should be exactly 13 bytes long */
945 /* mov <OFFSET>(%rip), %r10 */
946 emit_byte (acfg, '\x4d');
947 emit_byte (acfg, '\x8b');
948 emit_byte (acfg, '\x15');
949 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
951 /* jmp *<offset>(%rip) */
952 emit_byte (acfg, '\xff');
953 emit_byte (acfg, '\x25');
954 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
955 #elif defined(TARGET_ARM)
959 /* This should be exactly 24 bytes long */
962 /* Load rgctx value */
963 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
964 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
965 /* Load branch addr + branch */
966 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
967 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
969 g_assert (code - buf == 16);
972 emit_bytes (acfg, buf, code - buf);
973 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
974 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
975 #elif defined(TARGET_POWERPC)
982 g_assert (!acfg->use_bin_writer);
985 * PPC has no ip relative addressing, so we need to compute the address
986 * of the mscorlib got. That is slow and complex, so instead, we store it
987 * in the second got slot of every aot image. The caller already computed
988 * the address of its got and placed it into r30.
990 img_writer_emit_unset_mode (acfg->w);
991 /* Load mscorlib got address */
992 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
994 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
995 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
996 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
997 /* Load target address */
998 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
999 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1000 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1001 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1002 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1003 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1005 fprintf (acfg->fp, "mtctr 11\n");
1006 /* Branch to the target address */
1007 fprintf (acfg->fp, "bctr\n");
1009 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1010 *tramp_size = 11 * 4;
1012 *tramp_size = 9 * 4;
1015 #elif defined(TARGET_X86)
1019 /* Similar to the PPC code above */
1021 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1024 /* Load mscorlib got address */
1025 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1027 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1028 /* Branch to the target address */
1029 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1031 emit_bytes (acfg, buf, code - buf);
1034 g_assert (code - buf == *tramp_size);
1036 g_assert_not_reached ();
1041 * arch_emit_imt_thunk:
1043 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1044 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1045 * key is the IMT key, and ptr holds the address of a memory location holding
1046 * the address to branch to if the IMT arg matches the key. The array is
1047 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1049 * TRAMP_SIZE is set to the size of the emitted trampoline.
1052 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1054 #if defined(TARGET_AMD64)
1058 code = buf = g_malloc (256);
1060 /* FIXME: Optimize this, i.e. use binary search etc. */
1061 /* Maybe move the body into a separate function (slower, but much smaller) */
1063 /* R11 is a free register */
1066 amd64_alu_membase_imm (code, X86_CMP, AMD64_R11, 0, 0);
1068 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1071 amd64_alu_membase_reg (code, X86_CMP, AMD64_R11, 0, MONO_ARCH_IMT_REG);
1073 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1076 amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, 2 * sizeof (gpointer));
1077 amd64_jump_code (code, labels [0]);
1080 mono_amd64_patch (labels [2], code);
1081 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, sizeof (gpointer), 8);
1082 amd64_jump_membase (code, AMD64_R11, 0);
1086 mono_amd64_patch (labels [1], code);
1087 x86_breakpoint (code);
1089 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 12345678, 8);
1091 /* mov <OFFSET>(%rip), %r11 */
1092 emit_byte (acfg, '\x4d');
1093 emit_byte (acfg, '\x8b');
1094 emit_byte (acfg, '\x1d');
1095 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1097 emit_bytes (acfg, buf, code - buf);
1099 *tramp_size = code - buf + 7;
1100 #elif defined(TARGET_X86)
1104 code = buf = g_malloc (256);
1106 /* Allocate a temporary stack slot */
1107 x86_push_reg (code, X86_EAX);
1109 x86_push_reg (code, X86_EAX);
1111 /* Load mscorlib got address */
1112 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1114 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1117 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1119 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1122 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1124 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1127 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1128 x86_jump_code (code, labels [0]);
1131 mono_x86_patch (labels [2], code);
1132 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1133 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1134 /* Save the target address to the temporary stack location */
1135 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1137 x86_pop_reg (code, X86_EAX);
1138 /* Jump to the target address */
1143 mono_x86_patch (labels [1], code);
1144 x86_breakpoint (code);
1146 emit_bytes (acfg, buf, code - buf);
1148 *tramp_size = code - buf;
1149 #elif defined(TARGET_ARM)
1151 guint8 *code, *code2, *labels [16];
1155 /* The IMT method is in v5 */
1157 /* Need at least two free registers, plus a slot for storing the pc */
1158 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1160 /* Load the parameter from the GOT */
1161 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1162 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1165 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1166 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1168 ARM_B_COND (code, ARMCOND_EQ, 0);
1170 /* End-of-loop check */
1171 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1173 ARM_B_COND (code, ARMCOND_EQ, 0);
1176 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1179 arm_patch (labels [4], labels [1]);
1182 arm_patch (labels [2], code);
1183 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1184 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1185 /* Save it to the third stack slot */
1186 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1187 /* Restore the registers and branch */
1188 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1191 arm_patch (labels [3], code);
1196 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1198 emit_bytes (acfg, buf, code - buf);
1199 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1201 *tramp_size = code - buf + 4;
1202 #elif defined(TARGET_POWERPC)
1204 guint8 *code, *labels [16];
1208 /* Load the mscorlib got address */
1209 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1210 /* Load the parameter from the GOT */
1211 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1212 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1214 /* Load and check key */
1216 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1217 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1219 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1221 /* End-of-loop check */
1222 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1224 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1227 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1230 mono_ppc_patch (labels [4], labels [1]);
1233 mono_ppc_patch (labels [2], code);
1234 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1235 /* r11 now contains the value of the vtable slot */
1236 /* this is not a function descriptor on ppc64 */
1237 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1238 ppc_mtctr (code, ppc_r11);
1239 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1242 mono_ppc_patch (labels [3], code);
1246 *tramp_size = code - buf;
1248 emit_bytes (acfg, buf, code - buf);
1250 g_assert_not_reached ();
1255 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1257 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1258 /* Based on code generated by gcc */
1259 img_writer_emit_unset_mode (acfg->w);
1262 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1263 ".section .ctors,\"aw\",@progbits\n"
1267 ".section .opd,\"aw\"\n"
1270 ".long .%s,.TOC.@tocbase32\n"
1273 ".type .%s,@function\n"
1275 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1277 ".section .ctors,\"aw\",@progbits\n"
1281 ".section .opd,\"aw\"\n"
1284 ".long .%1$s,.TOC.@tocbase32\n"
1285 ".size %1$s,.-%1$s\n"
1287 ".type .%1$s,@function\n"
1289 ".%1$s:\n", symbol);
1300 "lis 3, .Lglobals@h\n"
1301 "ori 3, 3, .Lglobals@l\n"
1302 "bl .mono_aot_register_module\n"
1310 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1312 ".size .%s,.-.%s\n", symbol, symbol);
1315 ".size .%1$s,.-.%1$s\n", symbol);
1321 /* END OF ARCH SPECIFIC CODE */
1324 mono_get_field_token (MonoClassField *field)
1326 MonoClass *klass = field->parent;
1329 for (i = 0; i < klass->field.count; ++i) {
1330 if (field == &klass->fields [i])
1331 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1334 g_assert_not_reached ();
1339 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1343 //printf ("ENCODE: %d 0x%x.\n", value, value);
1346 * Same encoding as the one used in the metadata, extended to handle values
1347 * greater than 0x1fffffff.
1349 if ((value >= 0) && (value <= 127))
1351 else if ((value >= 0) && (value <= 16383)) {
1352 p [0] = 0x80 | (value >> 8);
1353 p [1] = value & 0xff;
1355 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1356 p [0] = (value >> 24) | 0xc0;
1357 p [1] = (value >> 16) & 0xff;
1358 p [2] = (value >> 8) & 0xff;
1359 p [3] = value & 0xff;
1364 p [1] = (value >> 24) & 0xff;
1365 p [2] = (value >> 16) & 0xff;
1366 p [3] = (value >> 8) & 0xff;
1367 p [4] = value & 0xff;
1375 stream_init (MonoDynamicStream *sh)
1378 sh->alloc_size = 4096;
1379 sh->data = g_malloc (4096);
1381 /* So offsets are > 0 */
1386 make_room_in_stream (MonoDynamicStream *stream, int size)
1388 if (size <= stream->alloc_size)
1391 while (stream->alloc_size <= size) {
1392 if (stream->alloc_size < 4096)
1393 stream->alloc_size = 4096;
1395 stream->alloc_size *= 2;
1398 stream->data = g_realloc (stream->data, stream->alloc_size);
1402 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1406 make_room_in_stream (stream, stream->index + len);
1407 memcpy (stream->data + stream->index, data, len);
1408 idx = stream->index;
1409 stream->index += len;
1416 * Add data to the binary blob inside the aot image. Returns the offset inside the
1417 * blob where the data was stored.
1420 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1422 if (acfg->blob.alloc_size == 0)
1423 stream_init (&acfg->blob);
1425 return add_stream_data (&acfg->blob, (char*)data, data_len);
1429 * emit_offset_table:
1431 * Emit a table of increasing offsets in a compact form using differential encoding.
1432 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1433 * group size, the more compact the table becomes, but the slower it becomes to compute
1434 * a given entry. Returns the size of the table.
1437 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1439 gint32 current_offset;
1440 int i, buf_size, ngroups, index_entry_size;
1442 guint32 *index_offsets;
1444 ngroups = (noffsets + (group_size - 1)) / group_size;
1446 index_offsets = g_new0 (guint32, ngroups);
1448 buf_size = noffsets * 4;
1449 p = buf = g_malloc0 (buf_size);
1452 for (i = 0; i < noffsets; ++i) {
1453 //printf ("D: %d -> %d\n", i, offsets [i]);
1454 if ((i % group_size) == 0) {
1455 index_offsets [i / group_size] = p - buf;
1456 /* Emit the full value for these entries */
1457 encode_value (offsets [i], p, &p);
1459 /* The offsets are allowed to be non-increasing */
1460 //g_assert (offsets [i] >= current_offset);
1461 encode_value (offsets [i] - current_offset, p, &p);
1463 current_offset = offsets [i];
1466 if (ngroups && index_offsets [ngroups - 1] < 65000)
1467 index_entry_size = 2;
1469 index_entry_size = 4;
1471 /* Emit the header */
1472 emit_int32 (acfg, noffsets);
1473 emit_int32 (acfg, group_size);
1474 emit_int32 (acfg, ngroups);
1475 emit_int32 (acfg, index_entry_size);
1477 /* Emit the index */
1478 for (i = 0; i < ngroups; ++i) {
1479 if (index_entry_size == 2)
1480 emit_int16 (acfg, index_offsets [i]);
1482 emit_int32 (acfg, index_offsets [i]);
1486 emit_bytes (acfg, buf, p - buf);
1488 return (int)(p - buf) + (ngroups * 4);
1492 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1496 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1500 index = g_hash_table_size (cfg->image_hash);
1501 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1502 g_ptr_array_add (cfg->image_table, image);
1508 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1511 MonoClass *k = NULL;
1513 /* FIXME: Search referenced images as well */
1514 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1515 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1520 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1521 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1527 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1532 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1533 * standard metadata encoding.
1536 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1540 if (klass->generic_class) {
1542 g_assert (klass->type_token);
1544 /* Find a typespec for a class if possible */
1545 token = find_typespec_for_class (acfg, klass);
1547 encode_value (token, p, &p);
1548 encode_value (get_image_index (acfg, acfg->image), p, &p);
1550 MonoClass *gclass = klass->generic_class->container_class;
1551 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1554 /* Encode it ourselves */
1556 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1557 encode_value (MONO_TYPE_GENERICINST, p, &p);
1558 encode_klass_ref (acfg, gclass, p, &p);
1559 encode_value (inst->type_argc, p, &p);
1560 for (i = 0; i < inst->type_argc; ++i)
1561 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1563 } else if (klass->type_token) {
1564 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1565 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1566 encode_value (get_image_index (acfg, klass->image), p, &p);
1567 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1568 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1569 g_assert (container);
1572 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1573 encode_value (klass->byval_arg.type, p, &p);
1575 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1577 encode_value (container->is_method, p, &p);
1578 if (container->is_method)
1579 encode_method_ref (acfg, container->owner.method, p, &p);
1581 encode_klass_ref (acfg, container->owner.klass, p, &p);
1584 g_assert (klass->rank > 0);
1585 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1586 encode_value (get_image_index (acfg, klass->image), p, &p);
1587 encode_value (klass->rank, p, &p);
1588 encode_klass_ref (acfg, klass->element_class, p, &p);
1594 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1596 guint32 token = mono_get_field_token (field);
1599 encode_klass_ref (cfg, field->parent, p, &p);
1600 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1601 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1606 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1610 MonoGenericInst *inst;
1612 /* Encode the context */
1613 inst = context->class_inst;
1614 encode_value (inst ? 1 : 0, p, &p);
1616 encode_value (inst->type_argc, p, &p);
1617 for (i = 0; i < inst->type_argc; ++i)
1618 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1620 inst = context->method_inst;
1621 encode_value (inst ? 1 : 0, p, &p);
1623 encode_value (inst->type_argc, p, &p);
1624 for (i = 0; i < inst->type_argc; ++i)
1625 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1631 #define MAX_IMAGE_INDEX 250
1634 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1636 guint32 image_index = get_image_index (acfg, method->klass->image);
1637 guint32 token = method->token;
1638 MonoJumpInfoToken *ji;
1643 * The encoding for most methods is as follows:
1644 * - image index encoded as a leb128
1645 * - token index encoded as a leb128
1646 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1647 * types of method encodings.
1650 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1652 /* Mark methods which can't use aot trampolines because they need the further
1653 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1655 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1656 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1657 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1660 * Some wrapper methods are shared using their signature, encode their
1661 * stringified signature instead.
1662 * FIXME: Optimize disk usage
1665 if (method->wrapper_type) {
1666 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1667 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1668 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1669 name = mono_aot_wrapper_name (method);
1670 } else if (mono_marshal_method_from_wrapper (method) != method) {
1671 /* Direct wrapper, encode it normally */
1673 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1676 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1677 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1678 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1680 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1681 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1682 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1684 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1685 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1686 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1692 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1693 strcpy ((char*)p, name);
1694 p += strlen (name) + 1;
1696 } else if (method->wrapper_type) {
1697 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1699 encode_value (method->wrapper_type, p, &p);
1701 switch (method->wrapper_type) {
1702 case MONO_WRAPPER_REMOTING_INVOKE:
1703 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1704 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1707 m = mono_marshal_method_from_wrapper (method);
1709 encode_method_ref (acfg, m, p, &p);
1712 case MONO_WRAPPER_PROXY_ISINST:
1713 case MONO_WRAPPER_LDFLD:
1714 case MONO_WRAPPER_LDFLDA:
1715 case MONO_WRAPPER_STFLD:
1716 case MONO_WRAPPER_ISINST: {
1717 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1718 encode_klass_ref (acfg, proxy_class, p, &p);
1721 case MONO_WRAPPER_LDFLD_REMOTE:
1722 case MONO_WRAPPER_STFLD_REMOTE:
1724 case MONO_WRAPPER_ALLOC: {
1725 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1727 g_assert (info->alloc_type != -1);
1728 encode_value (info->alloc_type, p, &p);
1731 case MONO_WRAPPER_WRITE_BARRIER:
1733 case MONO_WRAPPER_STELEMREF:
1735 case MONO_WRAPPER_UNKNOWN:
1736 if (strcmp (method->name, "FastMonitorEnter") == 0)
1737 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1738 else if (strcmp (method->name, "FastMonitorExit") == 0)
1739 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1741 g_assert_not_reached ();
1743 case MONO_WRAPPER_SYNCHRONIZED:
1744 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1745 case MONO_WRAPPER_RUNTIME_INVOKE: {
1748 m = mono_marshal_method_from_wrapper (method);
1750 g_assert (m != method);
1751 encode_method_ref (acfg, m, p, &p);
1754 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1755 if (!strcmp (method->name, "ElementAddr")) {
1756 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1759 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1760 encode_value (info->rank, p, &p);
1761 encode_value (info->elem_size, p, &p);
1763 g_assert_not_reached ();
1767 g_assert_not_reached ();
1769 } else if (mono_method_signature (method)->is_inflated) {
1771 * This is a generic method, find the original token which referenced it and
1773 * Obtain the token from information recorded by the JIT.
1775 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1777 image_index = get_image_index (acfg, ji->image);
1778 g_assert (image_index < MAX_IMAGE_INDEX);
1781 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1782 encode_value (image_index, p, &p);
1783 encode_value (token, p, &p);
1785 MonoMethod *declaring;
1786 MonoGenericContext *context = mono_method_get_context (method);
1788 g_assert (method->is_inflated);
1789 declaring = ((MonoMethodInflated*)method)->declaring;
1792 * This might be a non-generic method of a generic instance, which
1793 * doesn't have a token since the reference is generated by the JIT
1794 * like Nullable:Box/Unbox, or by generic sharing.
1797 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1798 /* Encode the klass */
1799 encode_klass_ref (acfg, method->klass, p, &p);
1800 /* Encode the method */
1801 image_index = get_image_index (acfg, method->klass->image);
1802 g_assert (image_index < MAX_IMAGE_INDEX);
1803 g_assert (declaring->token);
1804 token = declaring->token;
1805 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1806 encode_value (image_index, p, &p);
1807 encode_value (token, p, &p);
1808 encode_generic_context (acfg, context, p, &p);
1810 } else if (token == 0) {
1811 /* This might be a method of a constructed type like int[,].Set */
1812 /* Obtain the token from information recorded by the JIT */
1813 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1815 image_index = get_image_index (acfg, ji->image);
1816 g_assert (image_index < MAX_IMAGE_INDEX);
1819 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1820 encode_value (image_index, p, &p);
1821 encode_value (token, p, &p);
1824 g_assert (method->klass->rank);
1826 /* Encode directly */
1827 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1828 encode_klass_ref (acfg, method->klass, p, &p);
1829 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1830 encode_value (0, p, &p);
1831 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1832 encode_value (1, p, &p);
1833 else if (!strcmp (method->name, "Get"))
1834 encode_value (2, p, &p);
1835 else if (!strcmp (method->name, "Address"))
1836 encode_value (3, p, &p);
1837 else if (!strcmp (method->name, "Set"))
1838 encode_value (4, p, &p);
1840 g_assert_not_reached ();
1843 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1844 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1850 compare_patches (gconstpointer a, gconstpointer b)
1854 i = (*(MonoJumpInfo**)a)->ip.i;
1855 j = (*(MonoJumpInfo**)b)->ip.i;
1866 static G_GNUC_UNUSED char*
1867 patch_to_string (MonoJumpInfo *patch_info)
1871 str = g_string_new ("");
1873 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
1875 switch (patch_info->type) {
1876 case MONO_PATCH_INFO_VTABLE:
1877 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
1882 g_string_append_printf (str, ")");
1883 return g_string_free (str, FALSE);
1889 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1892 static inline gboolean
1893 is_plt_patch (MonoJumpInfo *patch_info)
1895 switch (patch_info->type) {
1896 case MONO_PATCH_INFO_METHOD:
1897 case MONO_PATCH_INFO_INTERNAL_METHOD:
1898 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1899 case MONO_PATCH_INFO_ICALL_ADDR:
1900 case MONO_PATCH_INFO_CLASS_INIT:
1901 case MONO_PATCH_INFO_RGCTX_FETCH:
1902 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1903 case MONO_PATCH_INFO_MONITOR_ENTER:
1904 case MONO_PATCH_INFO_MONITOR_EXIT:
1905 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1915 * Return the symbol identifying the plt entry PLT_OFFSET.
1918 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
1922 * The Apple linker reorganizes object files, so it doesn't like branches to local
1923 * labels, since those have no relocations.
1925 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
1927 return g_strdup_printf ("%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
1934 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
1936 static MonoPltEntry*
1937 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1941 if (!is_plt_patch (patch_info))
1944 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
1946 // FIXME: This breaks the calculation of final_got_size
1947 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1949 * Allocate a separate PLT slot for each such patch, since some plt
1950 * entries will refer to the method itself, and some will refer to the
1957 MonoJumpInfo *new_ji;
1959 g_assert (!acfg->final_got_size);
1961 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1963 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
1964 res->plt_offset = acfg->plt_offset;
1966 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
1968 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
1970 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
1972 acfg->plt_offset ++;
1981 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1982 * JI could be found if it exists, otherwise allocates a new one.
1985 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1989 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1991 return got_offset - 1;
1993 got_offset = acfg->got_offset;
1994 acfg->got_offset ++;
1996 if (acfg->final_got_size)
1997 g_assert (got_offset < acfg->final_got_size);
1999 acfg->stats.got_slots ++;
2000 acfg->stats.got_slot_types [ji->type] ++;
2002 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2003 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2004 g_ptr_array_add (acfg->got_patches, ji);
2009 /* Add a method to the list of methods which need to be emitted */
2011 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2014 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2015 g_ptr_array_add (acfg->methods, method);
2016 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2017 acfg->nmethods = acfg->methods->len + 1;
2020 if (method->wrapper_type || extra)
2021 g_ptr_array_add (acfg->extra_methods, method);
2025 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2027 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2035 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2039 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2043 index = acfg->method_index;
2044 add_method_with_index (acfg, method, index, extra);
2046 /* FIXME: Fix quadratic behavior */
2047 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2049 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2051 acfg->method_index ++;
2057 add_method (MonoAotCompile *acfg, MonoMethod *method)
2059 return add_method_full (acfg, method, FALSE, 0);
2063 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2065 add_method_full (acfg, method, TRUE, 0);
2069 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2071 add_method_full (acfg, method, TRUE, depth);
2075 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2077 MonoAotCompile *acfg = user_data;
2078 MonoJitICallInfo *callinfo = value;
2079 MonoMethod *wrapper;
2085 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2086 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2089 add_method (acfg, wrapper);
2093 get_runtime_invoke_sig (MonoMethodSignature *sig)
2095 MonoMethodBuilder *mb;
2098 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2099 m = mono_mb_create_method (mb, sig, 16);
2100 return mono_marshal_get_runtime_invoke (m, FALSE);
2104 can_marshal_struct (MonoClass *klass)
2106 MonoClassField *field;
2107 gboolean can_marshal = TRUE;
2108 gpointer iter = NULL;
2110 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2113 /* Only allow a few field types to avoid asserts in the marshalling code */
2114 while ((field = mono_class_get_fields (klass, &iter))) {
2115 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2118 switch (field->type->type) {
2123 case MONO_TYPE_BOOLEAN:
2126 case MONO_TYPE_CHAR:
2134 case MONO_TYPE_STRING:
2136 case MONO_TYPE_VALUETYPE:
2137 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2138 can_marshal = FALSE;
2141 can_marshal = FALSE;
2147 /* Its hard to compute whenever these can be marshalled or not */
2148 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2155 add_wrappers (MonoAotCompile *acfg)
2157 MonoMethod *method, *m;
2159 MonoMethodSignature *sig, *csig;
2163 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2164 * so there is only one wrapper of a given type, or inlining their contents into their
2169 * FIXME: This depends on the fact that different wrappers have different
2173 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2175 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2176 gboolean skip = FALSE;
2178 method = mono_get_method (acfg->image, token, NULL);
2180 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2181 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2182 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2185 if (method->is_generic || method->klass->generic_container)
2188 /* Skip methods which can not be handled by get_runtime_invoke () */
2189 sig = mono_method_signature (method);
2190 if ((sig->ret->type == MONO_TYPE_PTR) ||
2191 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2194 for (j = 0; j < sig->param_count; j++) {
2195 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2199 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2200 if (!method->klass->contextbound) {
2201 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2202 gboolean has_nullable = FALSE;
2204 for (j = 0; j < sig->param_count; j++) {
2205 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2206 has_nullable = TRUE;
2209 if (info && !has_nullable) {
2210 /* Supported by the dynamic runtime-invoke wrapper */
2218 //printf ("%s\n", mono_method_full_name (method, TRUE));
2219 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2223 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2224 #ifdef MONO_ARCH_HAVE_TLS_GET
2225 MonoMethodDesc *desc;
2226 MonoMethod *orig_method;
2230 /* Runtime invoke wrappers */
2232 /* void runtime-invoke () [.cctor] */
2233 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2234 csig->ret = &mono_defaults.void_class->byval_arg;
2235 add_method (acfg, get_runtime_invoke_sig (csig));
2237 /* void runtime-invoke () [Finalize] */
2238 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2240 csig->ret = &mono_defaults.void_class->byval_arg;
2241 add_method (acfg, get_runtime_invoke_sig (csig));
2243 /* void runtime-invoke (string) [exception ctor] */
2244 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2246 csig->ret = &mono_defaults.void_class->byval_arg;
2247 csig->params [0] = &mono_defaults.string_class->byval_arg;
2248 add_method (acfg, get_runtime_invoke_sig (csig));
2250 /* void runtime-invoke (string, string) [exception ctor] */
2251 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2253 csig->ret = &mono_defaults.void_class->byval_arg;
2254 csig->params [0] = &mono_defaults.string_class->byval_arg;
2255 csig->params [1] = &mono_defaults.string_class->byval_arg;
2256 add_method (acfg, get_runtime_invoke_sig (csig));
2258 /* string runtime-invoke () [Exception.ToString ()] */
2259 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2261 csig->ret = &mono_defaults.string_class->byval_arg;
2262 add_method (acfg, get_runtime_invoke_sig (csig));
2264 /* void runtime-invoke (string, Exception) [exception ctor] */
2265 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2267 csig->ret = &mono_defaults.void_class->byval_arg;
2268 csig->params [0] = &mono_defaults.string_class->byval_arg;
2269 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2270 add_method (acfg, get_runtime_invoke_sig (csig));
2272 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2273 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2275 csig->ret = &(mono_class_from_name (
2276 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2277 csig->params [0] = &mono_defaults.string_class->byval_arg;
2278 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2279 add_method (acfg, get_runtime_invoke_sig (csig));
2281 /* runtime-invoke used by finalizers */
2282 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2284 /* This is used by mono_runtime_capture_context () */
2285 method = mono_get_context_capture_method ();
2287 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2289 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2290 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2293 /* JIT icall wrappers */
2294 /* FIXME: locking */
2295 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2298 add_method (acfg, mono_marshal_get_stelemref ());
2300 #ifdef MONO_ARCH_HAVE_TLS_GET
2301 /* Managed Allocators */
2302 nallocators = mono_gc_get_managed_allocator_types ();
2303 for (i = 0; i < nallocators; ++i) {
2304 m = mono_gc_get_managed_allocator_by_type (i);
2306 add_method (acfg, m);
2309 /* Monitor Enter/Exit */
2310 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2311 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2312 g_assert (orig_method);
2313 mono_method_desc_free (desc);
2314 method = mono_monitor_get_fast_path (orig_method);
2316 add_method (acfg, method);
2318 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2319 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2320 g_assert (orig_method);
2321 mono_method_desc_free (desc);
2322 method = mono_monitor_get_fast_path (orig_method);
2324 add_method (acfg, method);
2329 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2330 * we use the original method instead at runtime.
2331 * Since full-aot doesn't support remoting, this is not a problem.
2334 /* remoting-invoke wrappers */
2335 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2336 MonoMethodSignature *sig;
2338 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2339 method = mono_get_method (acfg->image, token, NULL);
2341 sig = mono_method_signature (method);
2343 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2344 m = mono_marshal_get_remoting_invoke_with_check (method);
2346 add_method (acfg, m);
2351 /* delegate-invoke wrappers */
2352 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2355 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2356 klass = mono_class_get (acfg->image, token);
2358 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2359 method = mono_get_delegate_invoke (klass);
2361 m = mono_marshal_get_delegate_invoke (method, NULL);
2363 add_method (acfg, m);
2365 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2366 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2368 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2369 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2373 /* Synchronized wrappers */
2374 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2375 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2376 method = mono_get_method (acfg->image, token, NULL);
2378 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2379 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2382 /* pinvoke wrappers */
2383 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2385 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2387 method = mono_get_method (acfg->image, token, NULL);
2389 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2390 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2391 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2395 /* native-to-managed wrappers */
2396 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2398 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2399 MonoCustomAttrInfo *cattr;
2402 method = mono_get_method (acfg->image, token, NULL);
2405 * Only generate native-to-managed wrappers for methods which have an
2406 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2407 * name to avoid defining a new assembly to contain it.
2409 cattr = mono_custom_attrs_from_method (method);
2412 for (j = 0; j < cattr->num_attrs; ++j)
2413 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2415 if (j < cattr->num_attrs) {
2416 MonoCustomAttrEntry *e = &cattr->attrs [j];
2417 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2418 const char *p = (const char*)e->data;
2424 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2426 g_assert (sig->param_count == 1);
2427 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2430 * Decode the cattr manually since we can't create objects
2431 * during aot compilation.
2437 /* From load_cattr_value () in reflection.c */
2438 slen = mono_metadata_decode_value (p, &p);
2439 n = g_memdup (p, slen + 1);
2441 t = mono_reflection_type_from_name (n, acfg->image);
2445 klass = mono_class_from_mono_type (t);
2446 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2448 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2452 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2453 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2454 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2458 /* StructureToPtr/PtrToStructure wrappers */
2459 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2462 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2463 klass = mono_class_get (acfg->image, token);
2465 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2466 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2467 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2473 has_type_vars (MonoClass *klass)
2475 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2478 return has_type_vars (klass->element_class);
2479 if (klass->generic_class) {
2480 MonoGenericContext *context = &klass->generic_class->context;
2481 if (context->class_inst) {
2484 for (i = 0; i < context->class_inst->type_argc; ++i)
2485 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2493 method_has_type_vars (MonoMethod *method)
2495 if (has_type_vars (method->klass))
2498 if (method->is_inflated) {
2499 MonoGenericContext *context = mono_method_get_context (method);
2500 if (context->method_inst) {
2503 for (i = 0; i < context->method_inst->type_argc; ++i)
2504 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2511 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2514 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2516 add_generic_class_with_depth (acfg, klass, 0);
2520 * add_generic_class:
2522 * Add all methods of a generic class.
2525 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2530 mono_class_init (klass);
2532 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2535 if (has_type_vars (klass))
2538 if (!klass->generic_class && !klass->rank)
2542 while ((method = mono_class_get_methods (klass, &iter))) {
2543 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2547 if (method->is_generic)
2552 * FIXME: Instances which are referenced by these methods are not added,
2553 * for example Array.Resize<int> for List<int>.Add ().
2555 add_extra_method_with_depth (acfg, method, depth);
2558 if (klass->delegate) {
2559 method = mono_get_delegate_invoke (klass);
2561 method = mono_marshal_get_delegate_invoke (method, NULL);
2563 add_method (acfg, method);
2567 * For ICollection<T>, add instances of the helper methods
2568 * in Array, since a T[] could be cast to ICollection<T>.
2570 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2571 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2572 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2573 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2577 if (!strcmp (klass->name, "IEnumerator`1"))
2578 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2580 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2582 /* Add the T[]/InternalEnumerator class */
2583 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2587 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2588 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2592 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2593 add_generic_class (acfg, nclass);
2597 while ((method = mono_class_get_methods (array_class, &iter))) {
2598 if (strstr (method->name, name_prefix)) {
2599 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2600 add_extra_method_with_depth (acfg, m, depth);
2604 g_free (name_prefix);
2607 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2608 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2609 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2610 MonoClass *icomparable, *gcomparer;
2611 MonoGenericContext ctx;
2612 MonoType *args [16];
2614 memset (&ctx, 0, sizeof (ctx));
2616 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2617 g_assert (icomparable);
2618 args [0] = &tclass->byval_arg;
2619 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2621 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2622 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2623 g_assert (gcomparer);
2624 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2630 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2633 MonoGenericContext ctx;
2634 MonoType *args [16];
2636 memset (&ctx, 0, sizeof (ctx));
2638 for (i = 0; i < ninsts; ++i) {
2639 args [0] = insts [i];
2640 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2641 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2646 * add_generic_instances:
2648 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2651 add_generic_instances (MonoAotCompile *acfg)
2656 MonoMethodHeader *header;
2657 MonoMethodSignature *sig;
2658 MonoGenericContext *context;
2660 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2661 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2662 method = mono_get_method (acfg->image, token, NULL);
2664 if (method->klass->image != acfg->image)
2667 context = mono_method_get_context (method);
2669 if (context && ((context->class_inst && context->class_inst->is_open)))
2673 * For open methods, create an instantiation which can be passed to the JIT.
2674 * FIXME: Handle class_inst as well.
2676 if (context && context->method_inst && context->method_inst->is_open) {
2677 MonoGenericContext shared_context;
2678 MonoGenericInst *inst;
2679 MonoType **type_argv;
2681 MonoMethod *declaring_method;
2682 gboolean supported = TRUE;
2684 /* Check that the context doesn't contain open constructed types */
2685 if (context->class_inst) {
2686 inst = context->class_inst;
2687 for (i = 0; i < inst->type_argc; ++i) {
2688 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)
2690 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2694 if (context->method_inst) {
2695 inst = context->method_inst;
2696 for (i = 0; i < inst->type_argc; ++i) {
2697 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)
2699 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2707 memset (&shared_context, 0, sizeof (MonoGenericContext));
2709 inst = context->class_inst;
2711 type_argv = g_new0 (MonoType*, inst->type_argc);
2712 for (i = 0; i < inst->type_argc; ++i) {
2713 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)
2714 type_argv [i] = &mono_defaults.object_class->byval_arg;
2716 type_argv [i] = inst->type_argv [i];
2719 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2723 inst = context->method_inst;
2725 type_argv = g_new0 (MonoType*, inst->type_argc);
2726 for (i = 0; i < inst->type_argc; ++i) {
2727 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)
2728 type_argv [i] = &mono_defaults.object_class->byval_arg;
2730 type_argv [i] = inst->type_argv [i];
2733 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2737 if (method->is_generic || method->klass->generic_container)
2738 declaring_method = method;
2740 declaring_method = mono_method_get_declaring_generic_method (method);
2742 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2746 * If the method is fully sharable, it was already added in place of its
2747 * generic definition.
2749 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2753 * FIXME: Partially shared methods are not shared here, so we end up with
2754 * many identical methods.
2756 add_extra_method (acfg, method);
2759 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2762 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2764 klass = mono_class_get (acfg->image, token);
2765 if (!klass || klass->rank)
2768 add_generic_class (acfg, klass);
2771 /* Add types of args/locals */
2772 for (i = 0; i < acfg->methods->len; ++i) {
2775 method = g_ptr_array_index (acfg->methods, i);
2777 sig = mono_method_signature (method);
2780 for (j = 0; j < sig->param_count; ++j)
2781 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2782 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2785 header = mono_method_get_header (method);
2788 for (j = 0; j < header->num_locals; ++j)
2789 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2790 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2794 if (acfg->image == mono_defaults.corlib) {
2796 MonoType *insts [256];
2799 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2800 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2801 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2802 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2803 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2804 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2805 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2806 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2807 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2808 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2809 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2810 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2812 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2813 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2815 add_instances_of (acfg, klass, insts, ninsts);
2816 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2818 add_instances_of (acfg, klass, insts, ninsts);
2820 /* Add instances of the array generic interfaces for primitive types */
2821 /* This will add instances of the InternalArray_ helper methods in Array too */
2822 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2824 add_instances_of (acfg, klass, insts, ninsts);
2825 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2827 add_instances_of (acfg, klass, insts, ninsts);
2828 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2830 add_instances_of (acfg, klass, insts, ninsts);
2833 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2834 * used for all instances of GetGenericValueImpl by the AOT runtime.
2837 MonoGenericContext ctx;
2838 MonoType *args [16];
2839 MonoMethod *get_method;
2840 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2842 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2845 memset (&ctx, 0, sizeof (ctx));
2846 args [0] = &mono_defaults.object_class->byval_arg;
2847 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2848 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2855 * is_direct_callable:
2857 * Return whenever the method identified by JI is directly callable without
2858 * going through the PLT.
2861 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2863 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2864 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2866 gboolean direct_callable = TRUE;
2868 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2869 direct_callable = FALSE;
2870 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2871 // FIXME: Maybe call the wrapper directly ?
2872 direct_callable = FALSE;
2874 if (direct_callable)
2883 * emit_and_reloc_code:
2885 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2886 * is true, calls are made through the GOT too. This is used for emitting trampolines
2887 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2888 * since trampolines are needed to make PTL work.
2891 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2893 int i, pindex, start_index, method_index;
2895 MonoJumpInfo *patch_info;
2896 MonoMethodHeader *header;
2897 gboolean skip, direct_call;
2899 char direct_call_target [128];
2902 header = mono_method_get_header (method);
2904 method_index = get_method_index (acfg, method);
2907 /* Collect and sort relocations */
2908 patches = g_ptr_array_new ();
2909 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2910 g_ptr_array_add (patches, patch_info);
2911 g_ptr_array_sort (patches, compare_patches);
2914 for (i = 0; i < code_len; i++) {
2916 for (pindex = start_index; pindex < patches->len; ++pindex) {
2917 patch_info = g_ptr_array_index (patches, pindex);
2918 if (patch_info->ip.i >= i)
2922 #ifdef MONO_ARCH_AOT_SUPPORTED
2924 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2925 start_index = pindex;
2927 switch (patch_info->type) {
2928 case MONO_PATCH_INFO_NONE:
2930 case MONO_PATCH_INFO_GOT_OFFSET: {
2933 arch_emit_got_offset (acfg, code + i, &code_size);
2936 patch_info->type = MONO_PATCH_INFO_NONE;
2941 * If this patch is a call, try emitting a direct call instead of
2942 * through a PLT entry. This is possible if the called method is in
2943 * the same assembly and requires no initialization.
2945 direct_call = FALSE;
2946 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2947 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2948 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2949 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2951 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
2952 patch_info->type = MONO_PATCH_INFO_NONE;
2953 acfg->stats.direct_calls ++;
2956 acfg->stats.all_calls ++;
2959 if (!got_only && !direct_call) {
2960 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
2962 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2964 sprintf (direct_call_target, "%s", plt_entry->symbol);
2966 /* Nullify the patch */
2967 patch_info->type = MONO_PATCH_INFO_NONE;
2974 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2979 got_slot = get_got_offset (acfg, patch_info);
2981 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2988 #endif /* MONO_ARCH_AOT_SUPPORTED */
2991 /* Find next patch */
2993 for (pindex = start_index; pindex < patches->len; ++pindex) {
2994 patch_info = g_ptr_array_index (patches, pindex);
2995 if (patch_info->ip.i >= i)
2999 /* Try to emit multiple bytes at once */
3000 if (pindex < patches->len && patch_info->ip.i > i) {
3001 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3002 i = patch_info->ip.i - 1;
3004 emit_bytes (acfg, code + i, 1);
3013 * Modify SYMBOL so it only includes characters permissible in symbols.
3016 sanitize_symbol (char *symbol)
3018 int i, len = strlen (symbol);
3020 for (i = 0; i < len; ++i)
3021 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3026 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3028 char *name1, *name2, *cached;
3029 int i, j, len, count;
3031 name1 = mono_method_full_name (method, TRUE);
3032 len = strlen (name1);
3033 name2 = malloc (strlen (prefix) + len + 16);
3034 memcpy (name2, prefix, strlen (prefix));
3035 j = strlen (prefix);
3036 for (i = 0; i < len; ++i) {
3037 if (isalnum (name1 [i])) {
3038 name2 [j ++] = name1 [i];
3039 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3041 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3044 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3053 while (g_hash_table_lookup (cache, name2)) {
3054 sprintf (name2 + j, "_%d", count);
3058 cached = g_strdup (name2);
3059 g_hash_table_insert (cache, cached, cached);
3065 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3070 char *debug_sym = NULL;
3072 int func_alignment = AOT_FUNC_ALIGNMENT;
3073 MonoMethodHeader *header;
3075 method = cfg->orig_method;
3076 code = cfg->native_code;
3077 header = cfg->header;
3079 method_index = get_method_index (acfg, method);
3081 /* Make the labels local */
3082 sprintf (symbol, "%s", cfg->asm_symbol);
3084 emit_section_change (acfg, ".text", 0);
3085 emit_alignment (acfg, func_alignment);
3086 emit_label (acfg, symbol);
3088 if (acfg->aot_opts.write_symbols) {
3090 * Write a C style symbol for every method, this has two uses:
3091 * - it works on platforms where the dwarf debugging info is not
3093 * - it allows the setting of breakpoints of aot-ed methods.
3095 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3097 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3098 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3099 emit_label (acfg, debug_sym);
3102 if (cfg->verbose_level > 0)
3103 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3105 acfg->stats.code_size += cfg->code_len;
3107 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3109 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3113 if (acfg->aot_opts.write_symbols) {
3114 emit_symbol_size (acfg, debug_sym, ".");
3118 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3119 emit_label (acfg, symbol);
3125 * Encode PATCH_INFO into its disk representation.
3128 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3132 switch (patch_info->type) {
3133 case MONO_PATCH_INFO_NONE:
3135 case MONO_PATCH_INFO_IMAGE:
3136 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3138 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3140 case MONO_PATCH_INFO_METHOD_REL:
3141 encode_value ((gint)patch_info->data.offset, p, &p);
3143 case MONO_PATCH_INFO_SWITCH: {
3144 gpointer *table = (gpointer *)patch_info->data.table->table;
3147 encode_value (patch_info->data.table->table_size, p, &p);
3148 for (k = 0; k < patch_info->data.table->table_size; k++)
3149 encode_value ((int)(gssize)table [k], p, &p);
3152 case MONO_PATCH_INFO_METHODCONST:
3153 case MONO_PATCH_INFO_METHOD:
3154 case MONO_PATCH_INFO_METHOD_JUMP:
3155 case MONO_PATCH_INFO_ICALL_ADDR:
3156 case MONO_PATCH_INFO_METHOD_RGCTX:
3157 encode_method_ref (acfg, patch_info->data.method, p, &p);
3159 case MONO_PATCH_INFO_INTERNAL_METHOD:
3160 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3161 guint32 len = strlen (patch_info->data.name);
3163 encode_value (len, p, &p);
3165 memcpy (p, patch_info->data.name, len);
3170 case MONO_PATCH_INFO_LDSTR: {
3171 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3172 guint32 token = patch_info->data.token->token;
3173 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3174 encode_value (image_index, p, &p);
3175 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3178 case MONO_PATCH_INFO_RVA:
3179 case MONO_PATCH_INFO_DECLSEC:
3180 case MONO_PATCH_INFO_LDTOKEN:
3181 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3182 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3183 encode_value (patch_info->data.token->token, p, &p);
3184 encode_value (patch_info->data.token->has_context, p, &p);
3185 if (patch_info->data.token->has_context)
3186 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3188 case MONO_PATCH_INFO_EXC_NAME: {
3189 MonoClass *ex_class;
3192 mono_class_from_name (mono_defaults.exception_class->image,
3193 "System", patch_info->data.target);
3194 g_assert (ex_class);
3195 encode_klass_ref (acfg, ex_class, p, &p);
3198 case MONO_PATCH_INFO_R4:
3199 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3201 case MONO_PATCH_INFO_R8:
3202 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3203 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3205 case MONO_PATCH_INFO_VTABLE:
3206 case MONO_PATCH_INFO_CLASS:
3207 case MONO_PATCH_INFO_IID:
3208 case MONO_PATCH_INFO_ADJUSTED_IID:
3209 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3211 case MONO_PATCH_INFO_CLASS_INIT:
3212 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3213 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3215 case MONO_PATCH_INFO_FIELD:
3216 case MONO_PATCH_INFO_SFLDA:
3217 encode_field_info (acfg, patch_info->data.field, p, &p);
3219 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3221 case MONO_PATCH_INFO_RGCTX_FETCH: {
3222 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3224 encode_method_ref (acfg, entry->method, p, &p);
3225 encode_value (entry->in_mrgctx, p, &p);
3226 encode_value (entry->info_type, p, &p);
3227 encode_value (entry->data->type, p, &p);
3228 encode_patch (acfg, entry->data, p, &p);
3231 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3232 case MONO_PATCH_INFO_MONITOR_ENTER:
3233 case MONO_PATCH_INFO_MONITOR_EXIT:
3234 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3236 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3237 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3238 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3241 g_warning ("unable to handle jump info %d", patch_info->type);
3242 g_assert_not_reached ();
3249 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3252 guint32 pindex, offset;
3253 MonoJumpInfo *patch_info;
3255 encode_value (n_patches, p, &p);
3257 for (pindex = 0; pindex < patches->len; ++pindex) {
3258 patch_info = g_ptr_array_index (patches, pindex);
3260 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3264 offset = get_got_offset (acfg, patch_info);
3265 encode_value (offset, p, &p);
3272 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3276 int pindex, buf_size, n_patches;
3279 MonoJumpInfo *patch_info;
3280 MonoMethodHeader *header;
3281 guint32 method_index;
3283 guint32 first_got_offset;
3285 method = cfg->orig_method;
3286 code = cfg->native_code;
3287 header = mono_method_get_header (method);
3289 method_index = get_method_index (acfg, method);
3291 /* Sort relocations */
3292 patches = g_ptr_array_new ();
3293 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3294 g_ptr_array_add (patches, patch_info);
3295 g_ptr_array_sort (patches, compare_patches);
3297 first_got_offset = acfg->cfgs [method_index]->got_offset;
3299 /**********************/
3300 /* Encode method info */
3301 /**********************/
3303 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3304 p = buf = g_malloc (buf_size);
3306 if (mono_class_get_cctor (method->klass))
3307 encode_klass_ref (acfg, method->klass, p, &p);
3309 /* Not needed when loading the method */
3310 encode_value (0, p, &p);
3313 if (cfg->opt & MONO_OPT_SHARED) {
3314 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3315 for (l = cfg->ldstr_list; l; l = l->next) {
3316 encode_value ((long)l->data, p, &p);
3320 /* Used only in shared mode */
3321 g_assert (!cfg->ldstr_list);
3324 for (pindex = 0; pindex < patches->len; ++pindex) {
3325 patch_info = g_ptr_array_index (patches, pindex);
3327 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3328 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3329 patch_info->type = MONO_PATCH_INFO_NONE;
3334 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3335 /* Stored in a GOT slot initialized at module load time */
3336 patch_info->type = MONO_PATCH_INFO_NONE;
3340 if (is_plt_patch (patch_info)) {
3341 /* Calls are made through the PLT */
3342 patch_info->type = MONO_PATCH_INFO_NONE;
3350 g_assert (cfg->has_got_slots);
3352 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3354 acfg->stats.info_size += p - buf;
3356 g_assert (p - buf < buf_size);
3358 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3363 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3365 guint32 cache_index;
3368 /* Reuse the unwind module to canonize and store unwind info entries */
3369 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3371 /* Use +/- 1 to distinguish 0s from missing entries */
3372 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3380 * It would be easier to use assembler symbols, but the caller needs an
3383 offset = acfg->unwind_info_offset;
3384 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3385 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3388 encode_value (encoded_len, p, &p);
3390 acfg->unwind_info_offset += encoded_len + (p - buf);
3396 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3399 int i, k, buf_size, method_index;
3400 guint32 debug_info_size;
3402 MonoMethodHeader *header;
3403 guint8 *p, *buf, *debug_info;
3404 MonoJitInfo *jinfo = cfg->jit_info;
3406 gboolean use_unwind_ops = FALSE;
3407 MonoSeqPointInfo *seq_points;
3409 method = cfg->orig_method;
3410 code = cfg->native_code;
3411 header = cfg->header;
3413 method_index = get_method_index (acfg, method);
3415 if (!acfg->aot_opts.nodebug) {
3416 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3419 debug_info_size = 0;
3422 seq_points = cfg->seq_point_info;
3424 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3425 p = buf = g_malloc (buf_size);
3427 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3428 use_unwind_ops = cfg->unwind_ops != NULL;
3431 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);
3433 encode_value (flags, p, &p);
3435 if (use_unwind_ops) {
3436 guint32 encoded_len;
3440 * This is a duplicate of the data in the .debug_frame section, but that
3441 * section cannot be accessed using the dl interface.
3443 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3444 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3447 encode_value (jinfo->used_regs, p, &p);
3450 /*Encode the number of holes before the number of clauses to make decoding easier*/
3451 if (jinfo->has_try_block_holes) {
3452 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3453 encode_value (table->num_holes, p, &p);
3456 /* Exception table */
3457 if (cfg->compile_llvm) {
3459 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3460 * since the information is only available to llc. Instead, we let llc save the data
3461 * into the LSDA, and read it from there at runtime.
3463 /* The assembly might be CIL stripped so emit the data ourselves */
3464 if (header->num_clauses)
3465 encode_value (header->num_clauses, p, &p);
3467 for (k = 0; k < header->num_clauses; ++k) {
3468 MonoExceptionClause *clause;
3470 clause = &header->clauses [k];
3472 encode_value (clause->flags, p, &p);
3473 if (clause->data.catch_class) {
3474 encode_value (1, p, &p);
3475 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3477 encode_value (0, p, &p);
3480 /* Emit a list of nesting clauses */
3481 for (i = 0; i < header->num_clauses; ++i) {
3483 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3485 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3487 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3488 encode_value (i, p, &p);
3490 encode_value (-1, p, &p);
3493 if (jinfo->num_clauses)
3494 encode_value (jinfo->num_clauses, p, &p);
3496 for (k = 0; k < jinfo->num_clauses; ++k) {
3497 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3499 encode_value (ei->flags, p, &p);
3500 encode_value (ei->exvar_offset, p, &p);
3502 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3503 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3505 if (ei->data.catch_class) {
3506 encode_value (1, p, &p);
3507 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3509 encode_value (0, p, &p);
3513 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3514 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3515 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3519 if (jinfo->has_generic_jit_info) {
3520 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3522 if (!cfg->compile_llvm) {
3523 encode_value (gi->has_this ? 1 : 0, p, &p);
3524 encode_value (gi->this_reg, p, &p);
3525 encode_value (gi->this_offset, p, &p);
3529 * Need to encode jinfo->method too, since it is not equal to 'method'
3530 * when using generic sharing.
3532 encode_method_ref (acfg, jinfo->method, p, &p);
3535 if (jinfo->has_try_block_holes) {
3536 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3537 for (i = 0; i < table->num_holes; ++i) {
3538 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3539 encode_value (hole->clause, p, &p);
3540 encode_value (hole->length, p, &p);
3541 encode_value (hole->offset, p, &p);
3546 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3548 encode_value (seq_points->len, p, &p);
3549 last_il_offset = last_native_offset = 0;
3550 for (i = 0; i < seq_points->len; ++i) {
3551 SeqPoint *sp = &seq_points->seq_points [i];
3552 il_offset = sp->il_offset;
3553 native_offset = sp->native_offset;
3554 encode_value (il_offset - last_il_offset, p, &p);
3555 encode_value (native_offset - last_native_offset, p, &p);
3556 last_il_offset = il_offset;
3557 last_native_offset = native_offset;
3559 encode_value (sp->next_len, p, &p);
3560 for (j = 0; j < sp->next_len; ++j)
3561 encode_value (sp->next [j], p, &p);
3566 g_assert (debug_info_size < buf_size);
3568 encode_value (debug_info_size, p, &p);
3569 if (debug_info_size) {
3570 memcpy (p, debug_info, debug_info_size);
3571 p += debug_info_size;
3572 g_free (debug_info);
3575 acfg->stats.ex_info_size += p - buf;
3577 g_assert (p - buf < buf_size);
3580 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3585 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3587 MonoClass *klass = mono_class_get (acfg->image, token);
3589 int i, buf_size, res;
3590 gboolean no_special_static, cant_encode;
3591 gpointer iter = NULL;
3596 p = buf = g_malloc (buf_size);
3598 /* Mark as unusable */
3599 encode_value (-1, p, &p);
3601 res = add_to_blob (acfg, buf, p - buf);
3607 buf_size = 10240 + (klass->vtable_size * 16);
3608 p = buf = g_malloc (buf_size);
3612 mono_class_init (klass);
3614 mono_class_get_nested_types (klass, &iter);
3615 g_assert (klass->nested_classes_inited);
3617 mono_class_setup_vtable (klass);
3620 * Emit all the information which is required for creating vtables so
3621 * the runtime does not need to create the MonoMethod structures which
3622 * take up a lot of space.
3625 no_special_static = !mono_class_has_special_static_fields (klass);
3627 /* Check whenever we have enough info to encode the vtable */
3628 cant_encode = FALSE;
3629 for (i = 0; i < klass->vtable_size; ++i) {
3630 MonoMethod *cm = klass->vtable [i];
3632 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3636 if (klass->generic_container || cant_encode) {
3637 encode_value (-1, p, &p);
3639 encode_value (klass->vtable_size, p, &p);
3640 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);
3641 if (klass->has_cctor)
3642 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3643 if (klass->has_finalize)
3644 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3646 encode_value (klass->instance_size, p, &p);
3647 encode_value (mono_class_data_size (klass), p, &p);
3648 encode_value (klass->packing_size, p, &p);
3649 encode_value (klass->min_align, p, &p);
3651 for (i = 0; i < klass->vtable_size; ++i) {
3652 MonoMethod *cm = klass->vtable [i];
3655 encode_method_ref (acfg, cm, p, &p);
3657 encode_value (0, p, &p);
3661 acfg->stats.class_info_size += p - buf;
3663 g_assert (p - buf < buf_size);
3664 res = add_to_blob (acfg, buf, p - buf);
3671 * Calls made from AOTed code are routed through a table of jumps similar to the
3672 * ELF PLT (Program Linkage Table). The differences are the following:
3673 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3674 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3675 * jumps. This means the jumps need to be patched when the address of the callee is
3676 * known. Initially the PLT entries jump to code which transfers control to the
3677 * AOT runtime through the first PLT entry.
3680 emit_plt (MonoAotCompile *acfg)
3686 cache = g_hash_table_new (g_str_hash, g_str_equal);
3689 sprintf (symbol, "plt");
3691 emit_section_change (acfg, ".text", 0);
3692 emit_global (acfg, symbol, TRUE);
3693 emit_alignment (acfg, 16);
3694 emit_label (acfg, symbol);
3695 emit_label (acfg, acfg->plt_symbol);
3697 for (i = 0; i < acfg->plt_offset; ++i) {
3699 char *debug_sym = NULL;
3700 MonoPltEntry *plt_entry = NULL;
3705 * The first plt entry is used to transfer code to the AOT loader.
3707 arch_emit_plt_entry (acfg, i);
3711 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3713 sprintf (label, "%s", plt_entry->symbol);
3717 * If the target is directly callable, alias the plt symbol to point to
3719 * FIXME: Use this to simplify emit_and_reloc_code ().
3720 * FIXME: Avoid the got slot.
3721 * FIXME: Add support to the binary writer.
3723 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3724 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3725 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3730 emit_label (acfg, label);
3732 if (acfg->aot_opts.write_symbols) {
3734 case MONO_PATCH_INFO_METHOD:
3735 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3737 case MONO_PATCH_INFO_INTERNAL_METHOD:
3738 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3740 case MONO_PATCH_INFO_CLASS_INIT:
3741 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3742 sanitize_symbol (debug_sym);
3744 case MONO_PATCH_INFO_RGCTX_FETCH:
3745 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3747 case MONO_PATCH_INFO_ICALL_ADDR: {
3748 char *s = get_debug_sym (ji->data.method, "", cache);
3750 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3754 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3755 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3757 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3758 debug_sym = g_strdup_printf ("plt__generic_class_init");
3765 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3766 emit_label (acfg, debug_sym);
3770 arch_emit_plt_entry (acfg, i);
3773 emit_symbol_size (acfg, debug_sym, ".");
3778 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3780 sprintf (symbol, "plt_end");
3781 emit_global (acfg, symbol, TRUE);
3782 emit_label (acfg, symbol);
3784 g_hash_table_destroy (cache);
3787 static G_GNUC_UNUSED void
3788 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3790 char start_symbol [256];
3792 guint32 buf_size, info_offset;
3793 MonoJumpInfo *patch_info;
3804 code_size = info->code_size;
3806 unwind_ops = info->unwind_ops;
3810 sprintf (start_symbol, "%s", name);
3812 emit_section_change (acfg, ".text", 0);
3813 emit_global (acfg, start_symbol, TRUE);
3814 emit_alignment (acfg, 16);
3815 emit_label (acfg, start_symbol);
3817 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3818 emit_label (acfg, symbol);
3821 * The code should access everything through the GOT, so we pass
3824 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3826 emit_symbol_size (acfg, start_symbol, ".");
3830 /* Sort relocations */
3831 patches = g_ptr_array_new ();
3832 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3833 if (patch_info->type != MONO_PATCH_INFO_NONE)
3834 g_ptr_array_add (patches, patch_info);
3835 g_ptr_array_sort (patches, compare_patches);
3837 buf_size = patches->len * 128 + 128;
3838 buf = g_malloc (buf_size);
3841 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3842 g_assert (p - buf < buf_size);
3844 sprintf (symbol, "%s_p", name);
3846 info_offset = add_to_blob (acfg, buf, p - buf);
3848 emit_section_change (acfg, RODATA_SECT, 0);
3849 emit_global (acfg, symbol, FALSE);
3850 emit_label (acfg, symbol);
3852 emit_int32 (acfg, info_offset);
3854 /* Emit debug info */
3858 sprintf (symbol, "%s", name);
3859 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3862 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3867 emit_trampolines (MonoAotCompile *acfg)
3870 int i, tramp_got_offset;
3871 MonoAotTrampoline ntype;
3872 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3877 if (!acfg->aot_opts.full_aot)
3880 g_assert (acfg->image->assembly);
3882 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3883 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3884 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3885 MonoTrampInfo *info;
3888 * Emit the generic trampolines.
3890 * We could save some code by treating the generic trampolines as a wrapper
3891 * method, but that approach has its own complexities, so we choose the simpler
3894 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3895 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
3896 emit_trampoline (acfg, acfg->got_offset, info);
3899 mono_arch_get_nullified_class_init_trampoline (&info);
3900 emit_trampoline (acfg, acfg->got_offset, info);
3901 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
3902 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
3903 emit_trampoline (acfg, acfg->got_offset, info);
3904 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
3905 emit_trampoline (acfg, acfg->got_offset, info);
3908 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
3909 emit_trampoline (acfg, acfg->got_offset, info);
3911 /* Emit the exception related code pieces */
3912 code = mono_arch_get_restore_context (&info, TRUE);
3913 emit_trampoline (acfg, acfg->got_offset, info);
3914 code = mono_arch_get_call_filter (&info, TRUE);
3915 emit_trampoline (acfg, acfg->got_offset, info);
3916 code = mono_arch_get_throw_exception (&info, TRUE);
3917 emit_trampoline (acfg, acfg->got_offset, info);
3918 code = mono_arch_get_rethrow_exception (&info, TRUE);
3919 emit_trampoline (acfg, acfg->got_offset, info);
3920 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
3921 emit_trampoline (acfg, acfg->got_offset, info);
3923 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
3925 GSList *l = mono_arch_get_trampolines (TRUE);
3928 MonoTrampInfo *info = l->data;
3930 emit_trampoline (acfg, acfg->got_offset, info);
3936 for (i = 0; i < 128; ++i) {
3939 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3940 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
3941 emit_trampoline (acfg, acfg->got_offset, info);
3943 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3944 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
3945 emit_trampoline (acfg, acfg->got_offset, info);
3951 /* delegate_invoke_impl trampolines */
3952 l = mono_arch_get_delegate_invoke_impls ();
3954 MonoTrampInfo *info = l->data;
3956 emit_trampoline (acfg, acfg->got_offset, info);
3961 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3963 /* Emit trampolines which are numerous */
3966 * These include the following:
3967 * - specific trampolines
3968 * - static rgctx invoke trampolines
3970 * These trampolines have the same code, they are parameterized by GOT
3972 * They are defined in this file, in the arch_... routines instead of
3973 * in tramp-<ARCH>.c, since it is easier to do it this way.
3977 * When running in aot-only mode, we can't create specific trampolines at
3978 * runtime, so we create a few, and save them in the AOT file.
3979 * Normal trampolines embed their argument as a literal inside the
3980 * trampoline code, we can't do that here, so instead we embed an offset
3981 * which needs to be added to the trampoline address to get the address of
3982 * the GOT slot which contains the argument value.
3983 * The generated trampolines jump to the generic trampolines using another
3984 * GOT slot, which will be setup by the AOT loader to point to the
3985 * generic trampoline code of the given type.
3989 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3993 emit_section_change (acfg, ".text", 0);
3995 tramp_got_offset = acfg->got_offset;
3997 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3999 case MONO_AOT_TRAMP_SPECIFIC:
4000 sprintf (symbol, "specific_trampolines");
4002 case MONO_AOT_TRAMP_STATIC_RGCTX:
4003 sprintf (symbol, "static_rgctx_trampolines");
4005 case MONO_AOT_TRAMP_IMT_THUNK:
4006 sprintf (symbol, "imt_thunks");
4009 g_assert_not_reached ();
4012 emit_global (acfg, symbol, TRUE);
4013 emit_alignment (acfg, 16);
4014 emit_label (acfg, symbol);
4016 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4018 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4022 case MONO_AOT_TRAMP_SPECIFIC:
4023 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4024 tramp_got_offset += 2;
4026 case MONO_AOT_TRAMP_STATIC_RGCTX:
4027 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4028 tramp_got_offset += 2;
4030 case MONO_AOT_TRAMP_IMT_THUNK:
4031 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4032 tramp_got_offset += 1;
4035 g_assert_not_reached ();
4038 if (!acfg->trampoline_size [ntype]) {
4039 g_assert (tramp_size);
4040 acfg->trampoline_size [ntype] = tramp_size;
4045 /* Reserve some entries at the end of the GOT for our use */
4046 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4049 acfg->got_offset += acfg->num_trampoline_got_entries;
4053 str_begins_with (const char *str1, const char *str2)
4055 int len = strlen (str2);
4056 return strncmp (str1, str2, len) == 0;
4060 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4062 gchar **args, **ptr;
4064 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4065 for (ptr = args; ptr && *ptr; ptr ++) {
4066 const char *arg = *ptr;
4068 if (str_begins_with (arg, "outfile=")) {
4069 opts->outfile = g_strdup (arg + strlen ("outfile="));
4070 } else if (str_begins_with (arg, "save-temps")) {
4071 opts->save_temps = TRUE;
4072 } else if (str_begins_with (arg, "keep-temps")) {
4073 opts->save_temps = TRUE;
4074 } else if (str_begins_with (arg, "write-symbols")) {
4075 opts->write_symbols = TRUE;
4076 } else if (str_begins_with (arg, "metadata-only")) {
4077 opts->metadata_only = TRUE;
4078 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4079 opts->bind_to_runtime_version = TRUE;
4080 } else if (str_begins_with (arg, "full")) {
4081 opts->full_aot = TRUE;
4082 } else if (str_begins_with (arg, "threads=")) {
4083 opts->nthreads = atoi (arg + strlen ("threads="));
4084 } else if (str_begins_with (arg, "static")) {
4085 opts->static_link = TRUE;
4086 opts->no_dlsym = TRUE;
4087 } else if (str_begins_with (arg, "asmonly")) {
4088 opts->asm_only = TRUE;
4089 } else if (str_begins_with (arg, "asmwriter")) {
4090 opts->asm_writer = TRUE;
4091 } else if (str_begins_with (arg, "nodebug")) {
4092 opts->nodebug = TRUE;
4093 } else if (str_begins_with (arg, "ntrampolines=")) {
4094 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4095 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4096 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4097 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4098 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4099 } else if (str_begins_with (arg, "autoreg")) {
4100 opts->autoreg = TRUE;
4101 } else if (str_begins_with (arg, "tool-prefix=")) {
4102 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4103 } else if (str_begins_with (arg, "soft-debug")) {
4104 opts->soft_debug = TRUE;
4105 } else if (str_begins_with (arg, "print-skipped")) {
4106 opts->print_skipped_methods = TRUE;
4107 } else if (str_begins_with (arg, "stats")) {
4110 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4119 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4121 MonoMethod *method = (MonoMethod*)key;
4122 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4123 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4124 MonoAotCompile *acfg = user_data;
4126 new_ji->image = ji->image;
4127 new_ji->token = ji->token;
4128 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4132 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4134 if (klass->type_token)
4136 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4139 return can_encode_class (acfg, klass->element_class);
4144 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4146 switch (patch_info->type) {
4147 case MONO_PATCH_INFO_METHOD:
4148 case MONO_PATCH_INFO_METHODCONST: {
4149 MonoMethod *method = patch_info->data.method;
4151 if (method->wrapper_type) {
4152 switch (method->wrapper_type) {
4153 case MONO_WRAPPER_NONE:
4154 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4155 case MONO_WRAPPER_XDOMAIN_INVOKE:
4156 case MONO_WRAPPER_STFLD:
4157 case MONO_WRAPPER_LDFLD:
4158 case MONO_WRAPPER_LDFLDA:
4159 case MONO_WRAPPER_LDFLD_REMOTE:
4160 case MONO_WRAPPER_STFLD_REMOTE:
4161 case MONO_WRAPPER_STELEMREF:
4162 case MONO_WRAPPER_ISINST:
4163 case MONO_WRAPPER_PROXY_ISINST:
4164 case MONO_WRAPPER_ALLOC:
4165 case MONO_WRAPPER_REMOTING_INVOKE:
4166 case MONO_WRAPPER_UNKNOWN:
4167 case MONO_WRAPPER_WRITE_BARRIER:
4169 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4170 if (!strcmp (method->name, "ElementAddr"))
4175 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4179 if (!method->token) {
4180 /* The method is part of a constructed type like Int[,].Set (). */
4181 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4182 if (method->klass->rank)
4190 case MONO_PATCH_INFO_VTABLE:
4191 case MONO_PATCH_INFO_CLASS_INIT:
4192 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4193 case MONO_PATCH_INFO_CLASS:
4194 case MONO_PATCH_INFO_IID:
4195 case MONO_PATCH_INFO_ADJUSTED_IID:
4196 if (!can_encode_class (acfg, patch_info->data.klass)) {
4197 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4201 case MONO_PATCH_INFO_RGCTX_FETCH: {
4202 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4204 if (!can_encode_patch (acfg, entry->data))
4216 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4221 * AOT compile a given method.
4222 * This function might be called by multiple threads, so it must be thread-safe.
4225 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4228 MonoJumpInfo *patch_info;
4231 MonoMethod *wrapped;
4233 if (acfg->aot_opts.metadata_only)
4236 mono_acfg_lock (acfg);
4237 index = get_method_index (acfg, method);
4238 mono_acfg_unlock (acfg);
4240 /* fixme: maybe we can also precompile wrapper methods */
4241 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4242 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4243 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4244 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4248 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4251 wrapped = mono_marshal_method_from_wrapper (method);
4252 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4253 // FIXME: The wrapper should be generic too, but it is not
4256 InterlockedIncrement (&acfg->stats.mcount);
4259 if (method->is_generic || method->klass->generic_container) {
4260 InterlockedIncrement (&acfg->stats.genericcount);
4265 //acfg->aot_opts.print_skipped_methods = TRUE;
4268 * Since these methods are the only ones which are compiled with
4269 * AOT support, and they are not used by runtime startup/shutdown code,
4270 * the runtime will not see AOT methods during AOT compilation,so it
4271 * does not need to support them by creating a fake GOT etc.
4273 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4274 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4275 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4276 InterlockedIncrement (&acfg->stats.genericcount);
4279 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4280 /* Let the exception happen at runtime */
4284 if (cfg->disable_aot) {
4285 if (acfg->aot_opts.print_skipped_methods)
4286 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4287 InterlockedIncrement (&acfg->stats.ocount);
4288 mono_destroy_compile (cfg);
4292 /* Nullify patches which need no aot processing */
4293 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4294 switch (patch_info->type) {
4295 case MONO_PATCH_INFO_LABEL:
4296 case MONO_PATCH_INFO_BB:
4297 patch_info->type = MONO_PATCH_INFO_NONE;
4304 /* Collect method->token associations from the cfg */
4305 mono_acfg_lock (acfg);
4306 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4307 mono_acfg_unlock (acfg);
4310 * Check for absolute addresses.
4313 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4314 switch (patch_info->type) {
4315 case MONO_PATCH_INFO_ABS:
4316 /* unable to handle this */
4325 if (acfg->aot_opts.print_skipped_methods)
4326 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4327 InterlockedIncrement (&acfg->stats.abscount);
4328 mono_destroy_compile (cfg);
4332 /* Lock for the rest of the code */
4333 mono_acfg_lock (acfg);
4336 * Check for methods/klasses we can't encode.
4339 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4340 if (!can_encode_patch (acfg, patch_info))
4345 if (acfg->aot_opts.print_skipped_methods)
4346 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4347 acfg->stats.ocount++;
4348 mono_destroy_compile (cfg);
4349 mono_acfg_unlock (acfg);
4353 /* Adds generic instances referenced by this method */
4355 * The depth is used to avoid infinite loops when generic virtual recursion is
4358 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4360 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4361 switch (patch_info->type) {
4362 case MONO_PATCH_INFO_METHOD: {
4363 MonoMethod *m = patch_info->data.method;
4364 if (m->is_inflated) {
4365 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4366 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4367 !method_has_type_vars (m)) {
4368 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4369 if (acfg->aot_opts.full_aot)
4370 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4372 add_extra_method_with_depth (acfg, m, depth + 1);
4375 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4377 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4378 add_extra_method_with_depth (acfg, m, depth + 1);
4381 case MONO_PATCH_INFO_VTABLE: {
4382 MonoClass *klass = patch_info->data.klass;
4384 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4385 add_generic_class_with_depth (acfg, klass, depth + 5);
4394 /* Determine whenever the method has GOT slots */
4395 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4396 switch (patch_info->type) {
4397 case MONO_PATCH_INFO_GOT_OFFSET:
4398 case MONO_PATCH_INFO_NONE:
4400 case MONO_PATCH_INFO_IMAGE:
4401 /* The assembly is stored in GOT slot 0 */
4402 if (patch_info->data.image != acfg->image)
4403 cfg->has_got_slots = TRUE;
4406 if (!is_plt_patch (patch_info))
4407 cfg->has_got_slots = TRUE;
4412 if (!cfg->has_got_slots)
4413 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4416 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4418 /* Make a copy of the patch info which is in the mempool */
4420 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4422 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4423 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4426 patches = new_patch_info;
4428 patches_end->next = new_patch_info;
4429 patches_end = new_patch_info;
4431 cfg->patch_info = patches;
4433 /* Make a copy of the unwind info */
4435 GSList *l, *unwind_ops;
4439 for (l = cfg->unwind_ops; l; l = l->next) {
4440 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4441 memcpy (op, l->data, sizeof (MonoUnwindOp));
4442 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4444 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4446 /* Make a copy of the argument/local info */
4448 MonoInst **args, **locals;
4449 MonoMethodSignature *sig;
4450 MonoMethodHeader *header;
4453 sig = mono_method_signature (method);
4454 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4455 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4456 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4457 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4461 header = mono_method_get_header (method);
4462 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4463 for (i = 0; i < header->num_locals; ++i) {
4464 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4465 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4467 cfg->locals = locals;
4470 /* Free some fields used by cfg to conserve memory */
4471 mono_mempool_destroy (cfg->mempool);
4472 cfg->mempool = NULL;
4473 g_free (cfg->varinfo);
4474 cfg->varinfo = NULL;
4478 mono_regstate_free (cfg->rs);
4482 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4484 while (index >= acfg->cfgs_size) {
4485 MonoCompile **new_cfgs;
4488 new_size = acfg->cfgs_size * 2;
4489 new_cfgs = g_new0 (MonoCompile*, new_size);
4490 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4491 g_free (acfg->cfgs);
4492 acfg->cfgs = new_cfgs;
4493 acfg->cfgs_size = new_size;
4495 acfg->cfgs [index] = cfg;
4497 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4500 if (cfg->orig_method->wrapper_type)
4501 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4504 mono_acfg_unlock (acfg);
4506 InterlockedIncrement (&acfg->stats.ccount);
4510 compile_thread_main (gpointer *user_data)
4512 MonoDomain *domain = user_data [0];
4513 MonoAotCompile *acfg = user_data [1];
4514 GPtrArray *methods = user_data [2];
4517 mono_thread_attach (domain);
4519 for (i = 0; i < methods->len; ++i)
4520 compile_method (acfg, g_ptr_array_index (methods, i));
4524 load_profile_files (MonoAotCompile *acfg)
4528 int file_index, res, method_index, i;
4535 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4537 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4542 infile = fopen (tmp, "r");
4545 printf ("Using profile data file '%s'\n", tmp);
4550 res = fscanf (infile, "%32s\n", ver);
4551 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4552 printf ("Profile file has wrong version or invalid.\n");
4559 MonoMethodDesc *desc;
4562 if (fgets (name, 1023, infile) == NULL)
4565 /* Kill the newline */
4566 if (strlen (name) > 0)
4567 name [strlen (name) - 1] = '\0';
4569 desc = mono_method_desc_new (name, TRUE);
4571 method = mono_method_desc_search_in_image (desc, acfg->image);
4573 if (method && mono_method_get_token (method)) {
4574 token = mono_method_get_token (method);
4575 method_index = mono_metadata_token_index (token) - 1;
4577 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4578 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4581 //printf ("No method found matching '%s'.\n", name);
4587 /* Add missing methods */
4589 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4590 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4591 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4593 unordered = g_list_reverse (unordered);
4594 if (acfg->method_order)
4595 g_list_last (acfg->method_order)->next = unordered;
4597 acfg->method_order = unordered;
4600 /* Used by the LLVM backend */
4602 mono_aot_get_got_offset (MonoJumpInfo *ji)
4604 return get_got_offset (llvm_acfg, ji);
4608 mono_aot_get_method_name (MonoCompile *cfg)
4610 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4612 return g_strdup_printf ("m_%x", method_index);
4616 mono_aot_get_method_debug_name (MonoCompile *cfg)
4618 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4622 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4624 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4625 MonoPltEntry *plt_entry;
4628 ji->data.target = data;
4630 if (!can_encode_patch (llvm_acfg, ji))
4633 plt_entry = get_plt_entry (llvm_acfg, ji);
4635 return g_strdup_printf (plt_entry->symbol);
4639 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4643 mono_acfg_lock (llvm_acfg);
4644 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4645 mono_acfg_unlock (llvm_acfg);
4655 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4659 emit_llvm_file (MonoAotCompile *acfg)
4661 char *command, *opts;
4663 MonoJumpInfo *patch_info;
4664 const char *llc_extra_args;
4667 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4671 /* Compute the final size of the got */
4672 for (i = 0; i < acfg->nmethods; ++i) {
4673 if (acfg->cfgs [i]) {
4674 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4675 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4676 if (!is_plt_patch (patch_info))
4677 get_got_offset (acfg, patch_info);
4679 get_plt_entry (acfg, patch_info);
4685 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4687 if (acfg->aot_opts.full_aot) {
4691 * Need to add the got entries used by the trampolines.
4692 * This is only a conservative approximation.
4694 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4695 /* For the generic + rgctx trampolines */
4696 acfg->final_got_size += 200;
4697 /* For the specific trampolines */
4698 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4699 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4704 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4707 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4708 * a lot of time, and doesn't seem to save much space.
4709 * The following optimizations cannot be enabled:
4711 * - 'jump-threading' changes our blockaddress references to int constants.
4712 * The opt list below was produced by taking the output of:
4713 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4714 * then removing tailcallelim + the global opts, and adding a second gvn.
4716 opts = g_strdup ("-instcombine -simplifycfg");
4717 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");
4719 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4720 printf ("Executing opt: %s\n", command);
4721 if (system (command) != 0) {
4727 #if !LLVM_CHECK_VERSION(2, 8)
4728 /* LLVM 2.8 removed the -f flag ??? */
4729 llc_extra_args = "-f";
4731 llc_extra_args = "";
4733 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);
4735 printf ("Executing llc: %s\n", command);
4737 if (system (command) != 0) {
4744 emit_code (MonoAotCompile *acfg)
4748 char end_symbol [256];
4751 #if defined(TARGET_POWERPC64)
4752 sprintf (symbol, ".Lgot_addr");
4753 emit_section_change (acfg, ".text", 0);
4754 emit_alignment (acfg, 8);
4755 emit_label (acfg, symbol);
4756 emit_pointer (acfg, acfg->got_symbol);
4760 * This global symbol is used to compute the address of each method using the
4761 * code_offsets array. It is also used to compute the memory ranges occupied by
4762 * AOT code, so it must be equal to the address of the first emitted method.
4764 sprintf (symbol, "methods");
4765 emit_section_change (acfg, ".text", 0);
4766 emit_global (acfg, symbol, TRUE);
4767 emit_alignment (acfg, 8);
4769 for (i = 0; i < acfg->nmethods; ++i) {
4770 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4771 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4775 if (i == acfg->nmethods)
4776 /* No LLVM compiled methods */
4777 emit_label (acfg, symbol);
4779 emit_label (acfg, symbol);
4783 * Emit some padding so the local symbol for the first method doesn't have the
4784 * same address as 'methods'.
4786 emit_zero_bytes (acfg, 16);
4788 for (l = acfg->method_order; l != NULL; l = l->next) {
4792 i = GPOINTER_TO_UINT (l->data);
4794 cfg = acfg->cfgs [i];
4799 method = cfg->orig_method;
4801 /* Emit unbox trampoline */
4802 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4803 char call_target [256];
4805 if (!method->wrapper_type && !method->is_inflated) {
4806 g_assert (method->token);
4807 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4809 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4812 emit_section_change (acfg, ".text", 0);
4813 emit_global (acfg, symbol, TRUE);
4814 emit_label (acfg, symbol);
4816 sprintf (call_target, "%s", cfg->asm_symbol);
4818 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4821 if (cfg->compile_llvm)
4822 acfg->stats.llvm_count ++;
4824 emit_method_code (acfg, cfg);
4827 sprintf (symbol, "methods_end");
4828 emit_section_change (acfg, ".text", 0);
4829 emit_global (acfg, symbol, FALSE);
4830 emit_alignment (acfg, 8);
4831 emit_label (acfg, symbol);
4833 sprintf (symbol, "code_offsets");
4834 emit_section_change (acfg, RODATA_SECT, 1);
4835 emit_global (acfg, symbol, FALSE);
4836 emit_alignment (acfg, 8);
4837 emit_label (acfg, symbol);
4839 acfg->stats.offsets_size += acfg->nmethods * 4;
4841 sprintf (end_symbol, "methods");
4842 for (i = 0; i < acfg->nmethods; ++i) {
4843 if (acfg->cfgs [i]) {
4844 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4846 emit_int32 (acfg, 0xffffffff);
4853 emit_info (MonoAotCompile *acfg)
4860 offsets = g_new0 (gint32, acfg->nmethods);
4862 for (l = acfg->method_order; l != NULL; l = l->next) {
4863 i = GPOINTER_TO_UINT (l->data);
4865 if (acfg->cfgs [i]) {
4866 emit_method_info (acfg, acfg->cfgs [i]);
4867 offsets [i] = acfg->cfgs [i]->method_info_offset;
4873 sprintf (symbol, "method_info_offsets");
4874 emit_section_change (acfg, RODATA_SECT, 1);
4875 emit_global (acfg, symbol, FALSE);
4876 emit_alignment (acfg, 8);
4877 emit_label (acfg, symbol);
4879 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4884 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4886 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4887 #define mix(a,b,c) { \
4888 a -= c; a ^= rot(c, 4); c += b; \
4889 b -= a; b ^= rot(a, 6); a += c; \
4890 c -= b; c ^= rot(b, 8); b += a; \
4891 a -= c; a ^= rot(c,16); c += b; \
4892 b -= a; b ^= rot(a,19); a += c; \
4893 c -= b; c ^= rot(b, 4); b += a; \
4895 #define final(a,b,c) { \
4896 c ^= b; c -= rot(b,14); \
4897 a ^= c; a -= rot(c,11); \
4898 b ^= a; b -= rot(a,25); \
4899 c ^= b; c -= rot(b,16); \
4900 a ^= c; a -= rot(c,4); \
4901 b ^= a; b -= rot(a,14); \
4902 c ^= b; c -= rot(b,24); \
4906 mono_aot_type_hash (MonoType *t1)
4908 guint hash = t1->type;
4910 hash |= t1->byref << 6; /* do not collide with t1->type values */
4912 case MONO_TYPE_VALUETYPE:
4913 case MONO_TYPE_CLASS:
4914 case MONO_TYPE_SZARRAY:
4915 /* check if the distribution is good enough */
4916 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4918 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4919 case MONO_TYPE_ARRAY:
4920 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4921 case MONO_TYPE_GENERICINST:
4922 return ((hash << 5) - hash) ^ 0;
4928 * mono_aot_method_hash:
4930 * Return a hash code for methods which only depends on metadata.
4933 mono_aot_method_hash (MonoMethod *method)
4935 MonoMethodSignature *sig;
4939 guint32 *hashes_start, *hashes;
4942 /* Similar to the hash in mono_method_get_imt_slot () */
4944 sig = mono_method_signature (method);
4946 hashes_count = sig->param_count + 5;
4947 hashes_start = malloc (hashes_count * sizeof (guint32));
4948 hashes = hashes_start;
4950 /* Some wrappers are assigned to random classes */
4951 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4952 klass = method->klass;
4954 klass = mono_defaults.object_class;
4956 if (!method->wrapper_type) {
4957 char *full_name = mono_type_full_name (&klass->byval_arg);
4959 hashes [0] = mono_metadata_str_hash (full_name);
4963 hashes [0] = mono_metadata_str_hash (klass->name);
4964 hashes [1] = mono_metadata_str_hash (klass->name_space);
4966 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4967 /* The method name includes a stringified pointer */
4970 hashes [2] = mono_metadata_str_hash (method->name);
4971 hashes [3] = method->wrapper_type;
4972 hashes [4] = mono_aot_type_hash (sig->ret);
4973 for (i = 0; i < sig->param_count; i++) {
4974 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4977 /* Setup internal state */
4978 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4980 /* Handle most of the hashes */
4981 while (hashes_count > 3) {
4990 /* Handle the last 3 hashes (all the case statements fall through) */
4991 switch (hashes_count) {
4992 case 3 : c += hashes [2];
4993 case 2 : b += hashes [1];
4994 case 1 : a += hashes [0];
4996 case 0: /* nothing left to add */
5000 free (hashes_start);
5009 * mono_aot_wrapper_name:
5011 * Return a string which uniqely identifies the given wrapper method.
5014 mono_aot_wrapper_name (MonoMethod *method)
5016 char *name, *tmpsig, *klass_desc;
5018 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5020 switch (method->wrapper_type) {
5021 case MONO_WRAPPER_RUNTIME_INVOKE:
5022 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5023 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5025 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5028 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5029 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5030 g_free (klass_desc);
5040 * mono_aot_get_array_helper_from_wrapper;
5042 * Get the helper method in Array called by an array wrapper method.
5045 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5049 MonoGenericContext ctx;
5050 MonoType *args [16];
5051 char *mname, *iname, *s, *s2, *helper_name = NULL;
5053 prefix = "System.Collections.Generic";
5054 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5055 s2 = strstr (s, "`1.");
5061 //printf ("X: %s %s\n", iname, mname);
5063 if (!strcmp (iname, "IList"))
5064 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5066 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5067 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5069 g_free (helper_name);
5072 if (m->is_generic) {
5073 memset (&ctx, 0, sizeof (ctx));
5074 args [0] = &method->klass->element_class->byval_arg;
5075 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5076 m = mono_class_inflate_generic_method (m, &ctx);
5082 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5084 typedef struct HashEntry {
5085 guint32 key, value, index;
5086 struct HashEntry *next;
5090 * emit_extra_methods:
5092 * Emit methods which are not in the METHOD table, like wrappers.
5095 emit_extra_methods (MonoAotCompile *acfg)
5097 int i, table_size, buf_size;
5100 guint32 *info_offsets;
5103 HashEntry *entry, *new_entry;
5104 int nmethods, max_chain_length;
5107 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5109 /* Emit method info */
5111 for (i = 0; i < acfg->extra_methods->len; ++i) {
5112 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5113 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5120 p = buf = g_malloc (buf_size);
5124 method = cfg->method_to_register;
5127 if (method->wrapper_type) {
5129 * We encode some wrappers using their name, since encoding them
5130 * directly would be difficult. This also avoids creating the wrapper
5131 * methods at runtime, since they are not needed anyway.
5133 switch (method->wrapper_type) {
5134 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5135 case MONO_WRAPPER_SYNCHRONIZED:
5136 /* encode_method_ref () can handle these */
5138 case MONO_WRAPPER_RUNTIME_INVOKE:
5139 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5140 /* Direct wrapper, encode normally */
5144 name = mono_aot_wrapper_name (method);
5150 encode_value (1, p, &p);
5151 encode_value (method->wrapper_type, p, &p);
5152 strcpy ((char*)p, name);
5153 p += strlen (name ) + 1;
5156 encode_value (0, p, &p);
5157 encode_method_ref (acfg, method, p, &p);
5160 g_assert ((p - buf) < buf_size);
5162 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5167 * Construct a chained hash table for mapping indexes in extra_method_info to
5170 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5171 table = g_ptr_array_sized_new (table_size);
5172 for (i = 0; i < table_size; ++i)
5173 g_ptr_array_add (table, NULL);
5174 chain_lengths = g_new0 (int, table_size);
5175 max_chain_length = 0;
5176 for (i = 0; i < acfg->extra_methods->len; ++i) {
5177 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5178 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5184 key = info_offsets [i];
5185 value = get_method_index (acfg, method);
5187 hash = mono_aot_method_hash (method) % table_size;
5189 chain_lengths [hash] ++;
5190 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5192 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5193 new_entry->key = key;
5194 new_entry->value = value;
5196 entry = g_ptr_array_index (table, hash);
5197 if (entry == NULL) {
5198 new_entry->index = hash;
5199 g_ptr_array_index (table, hash) = new_entry;
5202 entry = entry->next;
5204 entry->next = new_entry;
5205 new_entry->index = table->len;
5206 g_ptr_array_add (table, new_entry);
5210 //printf ("MAX: %d\n", max_chain_length);
5212 /* Emit the table */
5213 sprintf (symbol, "extra_method_table");
5214 emit_section_change (acfg, RODATA_SECT, 0);
5215 emit_global (acfg, symbol, FALSE);
5216 emit_alignment (acfg, 8);
5217 emit_label (acfg, symbol);
5219 emit_int32 (acfg, table_size);
5220 for (i = 0; i < table->len; ++i) {
5221 HashEntry *entry = g_ptr_array_index (table, i);
5223 if (entry == NULL) {
5224 emit_int32 (acfg, 0);
5225 emit_int32 (acfg, 0);
5226 emit_int32 (acfg, 0);
5228 //g_assert (entry->key > 0);
5229 emit_int32 (acfg, entry->key);
5230 emit_int32 (acfg, entry->value);
5232 emit_int32 (acfg, entry->next->index);
5234 emit_int32 (acfg, 0);
5239 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5240 * This is used by mono_aot_find_jit_info ().
5242 sprintf (symbol, "extra_method_info_offsets");
5243 emit_section_change (acfg, RODATA_SECT, 0);
5244 emit_global (acfg, symbol, FALSE);
5245 emit_alignment (acfg, 8);
5246 emit_label (acfg, symbol);
5248 emit_int32 (acfg, acfg->extra_methods->len);
5249 for (i = 0; i < acfg->extra_methods->len; ++i) {
5250 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5252 emit_int32 (acfg, get_method_index (acfg, method));
5253 emit_int32 (acfg, info_offsets [i]);
5258 emit_exception_info (MonoAotCompile *acfg)
5264 offsets = g_new0 (gint32, acfg->nmethods);
5265 for (i = 0; i < acfg->nmethods; ++i) {
5266 if (acfg->cfgs [i]) {
5267 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5268 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5274 sprintf (symbol, "ex_info_offsets");
5275 emit_section_change (acfg, RODATA_SECT, 1);
5276 emit_global (acfg, symbol, FALSE);
5277 emit_alignment (acfg, 8);
5278 emit_label (acfg, symbol);
5280 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5285 emit_unwind_info (MonoAotCompile *acfg)
5291 * The unwind info contains a lot of duplicates so we emit each unique
5292 * entry once, and only store the offset from the start of the table in the
5296 sprintf (symbol, "unwind_info");
5297 emit_section_change (acfg, RODATA_SECT, 1);
5298 emit_alignment (acfg, 8);
5299 emit_label (acfg, symbol);
5300 emit_global (acfg, symbol, FALSE);
5302 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5303 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5304 guint8 *unwind_info;
5305 guint32 unwind_info_len;
5309 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5312 encode_value (unwind_info_len, p, &p);
5313 emit_bytes (acfg, buf, p - buf);
5314 emit_bytes (acfg, unwind_info, unwind_info_len);
5316 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5321 emit_class_info (MonoAotCompile *acfg)
5327 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5328 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5329 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5331 sprintf (symbol, "class_info_offsets");
5332 emit_section_change (acfg, RODATA_SECT, 1);
5333 emit_global (acfg, symbol, FALSE);
5334 emit_alignment (acfg, 8);
5335 emit_label (acfg, symbol);
5337 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5341 typedef struct ClassNameTableEntry {
5342 guint32 token, index;
5343 struct ClassNameTableEntry *next;
5344 } ClassNameTableEntry;
5347 emit_class_name_table (MonoAotCompile *acfg)
5350 guint32 token, hash;
5355 ClassNameTableEntry *entry, *new_entry;
5358 * Construct a chained hash table for mapping class names to typedef tokens.
5360 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5361 table = g_ptr_array_sized_new (table_size);
5362 for (i = 0; i < table_size; ++i)
5363 g_ptr_array_add (table, NULL);
5364 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5365 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5366 klass = mono_class_get (acfg->image, token);
5369 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5370 hash = mono_metadata_str_hash (full_name) % table_size;
5373 /* FIXME: Allocate from the mempool */
5374 new_entry = g_new0 (ClassNameTableEntry, 1);
5375 new_entry->token = token;
5377 entry = g_ptr_array_index (table, hash);
5378 if (entry == NULL) {
5379 new_entry->index = hash;
5380 g_ptr_array_index (table, hash) = new_entry;
5383 entry = entry->next;
5385 entry->next = new_entry;
5386 new_entry->index = table->len;
5387 g_ptr_array_add (table, new_entry);
5391 /* Emit the table */
5392 sprintf (symbol, "class_name_table");
5393 emit_section_change (acfg, RODATA_SECT, 0);
5394 emit_global (acfg, symbol, FALSE);
5395 emit_alignment (acfg, 8);
5396 emit_label (acfg, symbol);
5398 /* FIXME: Optimize memory usage */
5399 g_assert (table_size < 65000);
5400 emit_int16 (acfg, table_size);
5401 g_assert (table->len < 65000);
5402 for (i = 0; i < table->len; ++i) {
5403 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5405 if (entry == NULL) {
5406 emit_int16 (acfg, 0);
5407 emit_int16 (acfg, 0);
5409 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5411 emit_int16 (acfg, entry->next->index);
5413 emit_int16 (acfg, 0);
5419 emit_image_table (MonoAotCompile *acfg)
5425 * The image table is small but referenced in a lot of places.
5426 * So we emit it at once, and reference its elements by an index.
5429 sprintf (symbol, "mono_image_table");
5430 emit_section_change (acfg, RODATA_SECT, 1);
5431 emit_global (acfg, symbol, FALSE);
5432 emit_alignment (acfg, 8);
5433 emit_label (acfg, symbol);
5435 emit_int32 (acfg, acfg->image_table->len);
5436 for (i = 0; i < acfg->image_table->len; i++) {
5437 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5438 MonoAssemblyName *aname = &image->assembly->aname;
5440 /* FIXME: Support multi-module assemblies */
5441 g_assert (image->assembly->image == image);
5443 emit_string (acfg, image->assembly_name);
5444 emit_string (acfg, image->guid);
5445 emit_string (acfg, aname->culture ? aname->culture : "");
5446 emit_string (acfg, (const char*)aname->public_key_token);
5448 emit_alignment (acfg, 8);
5449 emit_int32 (acfg, aname->flags);
5450 emit_int32 (acfg, aname->major);
5451 emit_int32 (acfg, aname->minor);
5452 emit_int32 (acfg, aname->build);
5453 emit_int32 (acfg, aname->revision);
5458 emit_got_info (MonoAotCompile *acfg)
5461 int i, first_plt_got_patch, buf_size;
5463 guint32 *got_info_offsets;
5465 /* Add the patches needed by the PLT to the GOT */
5466 acfg->plt_got_offset_base = acfg->got_offset;
5467 first_plt_got_patch = acfg->got_patches->len;
5468 for (i = 1; i < acfg->plt_offset; ++i) {
5469 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5471 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5474 acfg->got_offset += acfg->plt_offset;
5478 * - optimize offsets table.
5479 * - reduce number of exported symbols.
5480 * - emit info for a klass only once.
5481 * - determine when a method uses a GOT slot which is guaranteed to be already
5483 * - clean up and document the code.
5484 * - use String.Empty in class libs.
5487 /* Encode info required to decode shared GOT entries */
5488 buf_size = acfg->got_patches->len * 128;
5489 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5490 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5491 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5493 if (acfg->plt_offset)
5494 acfg->plt_got_info_offsets [0] = 0;
5495 for (i = 0; i < acfg->got_patches->len; ++i) {
5496 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5500 encode_value (ji->type, p, &p);
5501 encode_patch (acfg, ji, p, &p);
5503 g_assert (p - buf <= buf_size);
5504 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5506 if (i >= first_plt_got_patch)
5507 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5508 acfg->stats.got_info_size += p - buf;
5511 /* Emit got_info_offsets table */
5512 sprintf (symbol, "got_info_offsets");
5513 emit_section_change (acfg, RODATA_SECT, 1);
5514 emit_global (acfg, symbol, FALSE);
5515 emit_alignment (acfg, 8);
5516 emit_label (acfg, symbol);
5518 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5519 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5523 emit_got (MonoAotCompile *acfg)
5528 /* Don't make GOT global so accesses to it don't need relocations */
5529 sprintf (symbol, "%s", acfg->got_symbol);
5530 emit_section_change (acfg, ".bss", 0);
5531 emit_alignment (acfg, 8);
5532 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5533 emit_label (acfg, symbol);
5534 if (acfg->got_offset > 0)
5535 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5537 sprintf (symbol, "got_end");
5538 emit_label (acfg, symbol);
5541 sprintf (symbol, "mono_aot_got_addr");
5542 emit_section_change (acfg, ".data", 0);
5543 emit_global (acfg, symbol, FALSE);
5544 emit_alignment (acfg, 8);
5545 emit_label (acfg, symbol);
5546 emit_pointer (acfg, acfg->got_symbol);
5549 typedef struct GlobalsTableEntry {
5550 guint32 value, index;
5551 struct GlobalsTableEntry *next;
5552 } GlobalsTableEntry;
5555 emit_globals_table (MonoAotCompile *acfg)
5561 GlobalsTableEntry *entry, *new_entry;
5564 * Construct a chained hash table for mapping global names to their index in
5565 * the globals table.
5567 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5568 table = g_ptr_array_sized_new (table_size);
5569 for (i = 0; i < table_size; ++i)
5570 g_ptr_array_add (table, NULL);
5571 for (i = 0; i < acfg->globals->len; ++i) {
5572 char *name = g_ptr_array_index (acfg->globals, i);
5574 hash = mono_metadata_str_hash (name) % table_size;
5576 /* FIXME: Allocate from the mempool */
5577 new_entry = g_new0 (GlobalsTableEntry, 1);
5578 new_entry->value = i;
5580 entry = g_ptr_array_index (table, hash);
5581 if (entry == NULL) {
5582 new_entry->index = hash;
5583 g_ptr_array_index (table, hash) = new_entry;
5586 entry = entry->next;
5588 entry->next = new_entry;
5589 new_entry->index = table->len;
5590 g_ptr_array_add (table, new_entry);
5594 /* Emit the table */
5595 sprintf (symbol, ".Lglobals_hash");
5596 emit_section_change (acfg, RODATA_SECT, 0);
5597 emit_alignment (acfg, 8);
5598 emit_label (acfg, symbol);
5600 /* FIXME: Optimize memory usage */
5601 g_assert (table_size < 65000);
5602 emit_int16 (acfg, table_size);
5603 for (i = 0; i < table->len; ++i) {
5604 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5606 if (entry == NULL) {
5607 emit_int16 (acfg, 0);
5608 emit_int16 (acfg, 0);
5610 emit_int16 (acfg, entry->value + 1);
5612 emit_int16 (acfg, entry->next->index);
5614 emit_int16 (acfg, 0);
5618 /* Emit the names */
5619 for (i = 0; i < acfg->globals->len; ++i) {
5620 char *name = g_ptr_array_index (acfg->globals, i);
5622 sprintf (symbol, "name_%d", i);
5623 emit_section_change (acfg, RODATA_SECT, 1);
5624 emit_label (acfg, symbol);
5625 emit_string (acfg, name);
5628 /* Emit the globals table */
5629 sprintf (symbol, ".Lglobals");
5630 emit_section_change (acfg, ".data", 0);
5631 /* This is not a global, since it is accessed by the init function */
5632 emit_alignment (acfg, 8);
5633 emit_label (acfg, symbol);
5635 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5636 emit_pointer (acfg, symbol);
5638 for (i = 0; i < acfg->globals->len; ++i) {
5639 char *name = g_ptr_array_index (acfg->globals, i);
5641 sprintf (symbol, "name_%d", i);
5642 emit_pointer (acfg, symbol);
5644 sprintf (symbol, "%s", name);
5645 emit_pointer (acfg, symbol);
5647 /* Null terminate the table */
5648 emit_int32 (acfg, 0);
5649 emit_int32 (acfg, 0);
5653 emit_globals (MonoAotCompile *acfg)
5657 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5659 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5661 if (acfg->aot_opts.bind_to_runtime_version) {
5662 build_info = mono_get_runtime_build_info ();
5663 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5664 g_free (build_info);
5666 emit_string_symbol (acfg, "mono_runtime_version", "");
5670 * When static linking, we emit a global which will point to the symbol table.
5672 if (acfg->aot_opts.static_link) {
5676 /* Emit a string holding the assembly name */
5677 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5679 emit_globals_table (acfg);
5682 * Emit a global symbol which can be passed by an embedding app to
5683 * mono_aot_register_module ().
5685 #if defined(__MACH__)
5686 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5688 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5691 /* Get rid of characters which cannot occur in symbols */
5693 for (p = symbol; *p; ++p) {
5694 if (!(isalnum (*p) || *p == '_'))
5697 acfg->static_linking_symbol = g_strdup (symbol);
5698 emit_global_inner (acfg, symbol, FALSE);
5699 emit_alignment (acfg, 8);
5700 emit_label (acfg, symbol);
5701 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5702 emit_pointer (acfg, symbol);
5707 emit_autoreg (MonoAotCompile *acfg)
5712 * Emit a function into the .ctor section which will be called by the ELF
5713 * loader to register this module with the runtime.
5715 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5718 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5720 arch_emit_autoreg (acfg, symbol);
5726 emit_mem_end (MonoAotCompile *acfg)
5730 sprintf (symbol, "mem_end");
5731 emit_section_change (acfg, ".text", 1);
5732 emit_global (acfg, symbol, FALSE);
5733 emit_alignment (acfg, 8);
5734 emit_label (acfg, symbol);
5738 * Emit a structure containing all the information not stored elsewhere.
5741 emit_file_info (MonoAotCompile *acfg)
5746 sprintf (symbol, "mono_aot_file_info");
5747 emit_section_change (acfg, ".data", 0);
5748 emit_alignment (acfg, 8);
5749 emit_label (acfg, symbol);
5750 emit_global (acfg, symbol, FALSE);
5752 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5753 emit_int32 (acfg, acfg->plt_got_offset_base);
5754 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5755 emit_int32 (acfg, acfg->plt_offset);
5756 emit_int32 (acfg, acfg->nmethods);
5757 emit_int32 (acfg, acfg->flags);
5758 emit_int32 (acfg, acfg->opts);
5760 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5761 emit_int32 (acfg, acfg->num_trampolines [i]);
5762 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5763 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5764 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5765 emit_int32 (acfg, acfg->trampoline_size [i]);
5769 emit_blob (MonoAotCompile *acfg)
5773 sprintf (symbol, "blob");
5774 emit_section_change (acfg, RODATA_SECT, 1);
5775 emit_global (acfg, symbol, FALSE);
5776 emit_alignment (acfg, 8);
5777 emit_label (acfg, symbol);
5779 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5783 emit_dwarf_info (MonoAotCompile *acfg)
5785 #ifdef EMIT_DWARF_INFO
5787 char symbol [128], symbol2 [128];
5789 /* DIEs for methods */
5790 for (i = 0; i < acfg->nmethods; ++i) {
5791 MonoCompile *cfg = acfg->cfgs [i];
5796 // FIXME: LLVM doesn't define .Lme_...
5797 if (cfg->compile_llvm)
5800 sprintf (symbol, "%s", cfg->asm_symbol);
5801 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5803 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 ()));
5809 collect_methods (MonoAotCompile *acfg)
5812 MonoImage *image = acfg->image;
5814 /* Collect methods */
5815 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5817 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5819 method = mono_get_method (acfg->image, token, NULL);
5822 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5826 /* Load all methods eagerly to skip the slower lazy loading code */
5827 mono_class_setup_methods (method->klass);
5829 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5830 /* Compile the wrapper instead */
5831 /* We do this here instead of add_wrappers () because it is easy to do it here */
5832 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5836 /* FIXME: Some mscorlib methods don't have debug info */
5838 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5839 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5840 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5841 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5842 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5843 if (!mono_debug_lookup_method (method)) {
5844 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5851 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5852 add_method_with_index (acfg, method, i, FALSE);
5853 acfg->method_index ++;
5856 add_generic_instances (acfg);
5858 if (acfg->aot_opts.full_aot)
5859 add_wrappers (acfg);
5863 compile_methods (MonoAotCompile *acfg)
5867 if (acfg->aot_opts.nthreads > 0) {
5872 gpointer *user_data;
5873 MonoMethod **methods;
5875 methods_len = acfg->methods->len;
5877 len = acfg->methods->len / acfg->aot_opts.nthreads;
5880 * Partition the list of methods into fragments, and hand it to threads to
5883 threads = g_ptr_array_new ();
5884 /* Make a copy since acfg->methods is modified by compile_method () */
5885 methods = g_new0 (MonoMethod*, methods_len);
5886 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5887 for (i = 0; i < methods_len; ++i)
5888 methods [i] = g_ptr_array_index (acfg->methods, i);
5890 while (i < methods_len) {
5891 frag = g_ptr_array_new ();
5892 for (j = 0; j < len; ++j) {
5893 if (i < methods_len) {
5894 g_ptr_array_add (frag, methods [i]);
5899 user_data = g_new0 (gpointer, 3);
5900 user_data [0] = mono_domain_get ();
5901 user_data [1] = acfg;
5902 user_data [2] = frag;
5904 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5905 g_ptr_array_add (threads, handle);
5909 for (i = 0; i < threads->len; ++i) {
5910 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5916 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5917 for (i = methods_len; i < acfg->methods->len; ++i) {
5918 /* This can new methods to acfg->methods */
5919 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5924 compile_asm (MonoAotCompile *acfg)
5926 char *command, *objfile;
5927 char *outfile_name, *tmp_outfile_name;
5928 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5930 #if defined(TARGET_AMD64)
5931 #define AS_OPTIONS "--64"
5932 #elif defined(TARGET_POWERPC64)
5933 #define AS_OPTIONS "-a64 -mppc64"
5934 #define LD_OPTIONS "-m elf64ppc"
5935 #elif defined(sparc) && SIZEOF_VOID_P == 8
5936 #define AS_OPTIONS "-xarch=v9"
5938 #define AS_OPTIONS ""
5942 #define LD_OPTIONS ""
5946 #define EH_LD_OPTIONS "--eh-frame-hdr"
5948 #define EH_LD_OPTIONS ""
5951 if (acfg->aot_opts.asm_only) {
5952 printf ("Output file: '%s'.\n", acfg->tmpfname);
5953 if (acfg->aot_opts.static_link)
5954 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5958 if (acfg->aot_opts.static_link) {
5959 if (acfg->aot_opts.outfile)
5960 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5962 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5964 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5966 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5967 printf ("Executing the native assembler: %s\n", command);
5968 if (system (command) != 0) {
5976 if (acfg->aot_opts.static_link) {
5977 printf ("Output file: '%s'.\n", objfile);
5978 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5983 if (acfg->aot_opts.outfile)
5984 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5986 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5988 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5991 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5992 #elif defined(__ppc__) && defined(__MACH__)
5993 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5994 #elif defined(HOST_WIN32)
5995 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5997 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5999 printf ("Executing the native linker: %s\n", command);
6000 if (system (command) != 0) {
6001 g_free (tmp_outfile_name);
6002 g_free (outfile_name);
6010 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6011 printf ("Stripping the binary: %s\n", com);
6015 #if defined(TARGET_ARM) && !defined(__MACH__)
6017 * gas generates 'mapping symbols' each time code and data is mixed, which
6018 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6020 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6021 printf ("Stripping the binary: %s\n", command);
6022 if (system (command) != 0) {
6023 g_free (tmp_outfile_name);
6024 g_free (outfile_name);
6031 rename (tmp_outfile_name, outfile_name);
6033 g_free (tmp_outfile_name);
6034 g_free (outfile_name);
6037 if (acfg->aot_opts.save_temps)
6038 printf ("Retained input file.\n");
6040 unlink (acfg->tmpfname);
6045 static MonoAotCompile*
6046 acfg_create (MonoAssembly *ass, guint32 opts)
6048 MonoImage *image = ass->image;
6049 MonoAotCompile *acfg;
6052 acfg = g_new0 (MonoAotCompile, 1);
6053 acfg->methods = g_ptr_array_new ();
6054 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6055 acfg->method_depth = g_hash_table_new (NULL, NULL);
6056 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6057 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6058 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6059 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6060 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6061 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6062 acfg->got_patches = g_ptr_array_new ();
6063 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6064 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6065 acfg->image_hash = g_hash_table_new (NULL, NULL);
6066 acfg->image_table = g_ptr_array_new ();
6067 acfg->globals = g_ptr_array_new ();
6068 acfg->image = image;
6070 acfg->mempool = mono_mempool_new ();
6071 acfg->extra_methods = g_ptr_array_new ();
6072 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6073 acfg->unwind_ops = g_ptr_array_new ();
6074 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6075 InitializeCriticalSection (&acfg->mutex);
6081 acfg_free (MonoAotCompile *acfg)
6085 img_writer_destroy (acfg->w);
6086 for (i = 0; i < acfg->nmethods; ++i)
6088 g_free (acfg->cfgs [i]);
6089 g_free (acfg->cfgs);
6090 g_free (acfg->static_linking_symbol);
6091 g_free (acfg->got_symbol);
6092 g_free (acfg->plt_symbol);
6093 g_ptr_array_free (acfg->methods, TRUE);
6094 g_ptr_array_free (acfg->got_patches, TRUE);
6095 g_ptr_array_free (acfg->image_table, TRUE);
6096 g_ptr_array_free (acfg->globals, TRUE);
6097 g_ptr_array_free (acfg->unwind_ops, TRUE);
6098 g_hash_table_destroy (acfg->method_indexes);
6099 g_hash_table_destroy (acfg->method_depth);
6100 g_hash_table_destroy (acfg->plt_offset_to_entry);
6101 g_hash_table_destroy (acfg->patch_to_plt_entry);
6102 g_hash_table_destroy (acfg->patch_to_got_offset);
6103 g_hash_table_destroy (acfg->method_to_cfg);
6104 g_hash_table_destroy (acfg->token_info_hash);
6105 g_hash_table_destroy (acfg->image_hash);
6106 g_hash_table_destroy (acfg->unwind_info_offsets);
6107 g_hash_table_destroy (acfg->method_label_hash);
6108 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6109 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6110 g_free (acfg->patch_to_got_offset_by_type);
6111 mono_mempool_destroy (acfg->mempool);
6116 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6118 MonoImage *image = ass->image;
6120 MonoAotCompile *acfg;
6121 char *outfile_name, *tmp_outfile_name, *p;
6125 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6127 acfg = acfg_create (ass, opts);
6129 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6130 acfg->aot_opts.write_symbols = TRUE;
6131 acfg->aot_opts.ntrampolines = 1024;
6132 acfg->aot_opts.nrgctx_trampolines = 1024;
6133 acfg->aot_opts.nimt_trampolines = 128;
6135 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6137 if (acfg->aot_opts.static_link)
6138 acfg->aot_opts.autoreg = TRUE;
6140 //acfg->aot_opts.print_skipped_methods = TRUE;
6142 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6143 if (acfg->aot_opts.full_aot) {
6144 printf ("--aot=full is not supported on this platform.\n");
6149 if (acfg->aot_opts.static_link)
6150 acfg->aot_opts.asm_writer = TRUE;
6152 if (acfg->aot_opts.soft_debug) {
6153 MonoDebugOptions *opt = mini_get_debug_options ();
6155 opt->mdb_optimizations = TRUE;
6156 opt->gen_seq_points = TRUE;
6158 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6159 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6166 acfg->aot_opts.asm_writer = TRUE;
6167 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6170 if (acfg->aot_opts.full_aot)
6171 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6173 load_profile_files (acfg);
6175 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6176 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6177 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6179 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6181 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6182 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6184 /* Get rid of characters which cannot occur in symbols */
6185 for (p = acfg->got_symbol_base; *p; ++p) {
6186 if (!(isalnum (*p) || *p == '_'))
6189 for (p = acfg->plt_symbol; *p; ++p) {
6190 if (!(isalnum (*p) || *p == '_'))
6194 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6197 * The prefix LLVM likes to put in front of symbol names on darwin.
6198 * The mach-os specs require this for globals, but LLVM puts them in front of all
6199 * symbols. We need to handle this, since we need to refer to LLVM generated
6202 acfg->llvm_label_prefix = "";
6204 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6206 acfg->method_index = 1;
6208 collect_methods (acfg);
6210 acfg->cfgs_size = acfg->methods->len + 32;
6211 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6213 /* PLT offset 0 is reserved for the PLT trampoline */
6214 acfg->plt_offset = 1;
6218 mono_llvm_create_aot_module (acfg->got_symbol_base);
6221 /* GOT offset 0 is reserved for the address of the current assembly */
6225 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6226 ji->type = MONO_PATCH_INFO_IMAGE;
6227 ji->data.image = acfg->image;
6229 get_got_offset (acfg, ji);
6231 /* Slot 1 is reserved for the mscorlib got addr */
6232 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6233 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6234 get_got_offset (acfg, ji);
6239 compile_methods (acfg);
6243 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6249 if (acfg->aot_opts.asm_only) {
6250 if (acfg->aot_opts.outfile)
6251 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6253 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6255 acfg->tmpfname = g_strdup ("temp.s");
6259 emit_llvm_file (acfg);
6262 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6263 if (acfg->aot_opts.outfile)
6264 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6266 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6269 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6270 * it might be in another file system so the rename () won't work.
6272 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6274 acfg->fp = fopen (tmp_outfile_name, "w");
6276 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6280 acfg->w = img_writer_create (acfg->fp, TRUE);
6281 acfg->use_bin_writer = TRUE;
6284 /* Append to the .s file created by llvm */
6285 /* FIXME: Use multiple files instead */
6286 acfg->fp = fopen (acfg->tmpfname, "a+");
6288 if (acfg->aot_opts.asm_only) {
6289 if (acfg->aot_opts.outfile)
6290 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6292 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6293 acfg->fp = fopen (acfg->tmpfname, "w+");
6295 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6296 acfg->fp = fdopen (i, "w+");
6298 g_assert (acfg->fp);
6300 acfg->w = img_writer_create (acfg->fp, FALSE);
6302 tmp_outfile_name = NULL;
6303 outfile_name = NULL;
6306 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6308 /* Compute symbols for methods */
6309 for (i = 0; i < acfg->nmethods; ++i) {
6310 if (acfg->cfgs [i]) {
6311 MonoCompile *cfg = acfg->cfgs [i];
6312 int method_index = get_method_index (acfg, cfg->orig_method);
6314 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6318 if (!acfg->aot_opts.nodebug)
6319 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6321 img_writer_emit_start (acfg->w);
6324 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6330 emit_extra_methods (acfg);
6332 emit_trampolines (acfg);
6334 emit_class_name_table (acfg);
6336 emit_got_info (acfg);
6338 emit_exception_info (acfg);
6340 emit_unwind_info (acfg);
6342 emit_class_info (acfg);
6346 emit_image_table (acfg);
6350 emit_file_info (acfg);
6354 emit_globals (acfg);
6356 emit_autoreg (acfg);
6359 emit_dwarf_info (acfg);
6360 mono_dwarf_writer_close (acfg->dwarf);
6363 emit_mem_end (acfg);
6367 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6370 g_assert (acfg->got_offset <= acfg->final_got_size);
6372 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);
6375 res = img_writer_emit_writeout (acfg->w);
6380 if (acfg->use_bin_writer) {
6381 int err = rename (tmp_outfile_name, outfile_name);
6384 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6388 res = compile_asm (acfg);
6395 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6397 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);
6398 if (acfg->stats.genericcount)
6399 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6400 if (acfg->stats.abscount)
6401 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6402 if (acfg->stats.lmfcount)
6403 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6404 if (acfg->stats.ocount)
6405 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6407 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6408 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);
6409 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6411 if (acfg->aot_opts.stats) {
6414 printf ("GOT slot distribution:\n");
6415 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6416 if (acfg->stats.got_slot_types [i])
6417 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6420 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);
6432 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)