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.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 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76 #define SHARED_EXT ".dll"
77 #elif defined(__ppc__) && defined(__MACH__)
78 #define SHARED_EXT ".dylib"
80 #define SHARED_EXT ".so"
83 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
84 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
85 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
87 typedef struct MonoAotOptions {
90 gboolean write_symbols;
91 gboolean metadata_only;
92 gboolean bind_to_runtime_version;
102 int nrgctx_trampolines;
103 int nimt_trampolines;
104 gboolean print_skipped_methods;
110 typedef struct MonoAotStats {
111 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
112 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
113 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
114 int got_slots, offsets_size;
115 int got_slot_types [MONO_PATCH_INFO_NONE];
116 int jit_time, gen_time, link_time;
119 typedef struct MonoAotCompile {
122 GHashTable *method_indexes;
123 GHashTable *method_depth;
126 GHashTable *patch_to_plt_offset;
127 GHashTable *plt_offset_to_patch;
128 GHashTable *patch_to_got_offset;
129 GHashTable **patch_to_got_offset_by_type;
130 GPtrArray *got_patches;
131 GHashTable *image_hash;
132 GHashTable *method_to_cfg;
133 GHashTable *token_info_hash;
134 GPtrArray *extra_methods;
135 GPtrArray *image_table;
138 guint32 *plt_got_info_offsets;
139 guint32 got_offset, plt_offset, plt_got_offset_base;
140 guint32 final_got_size;
141 /* Number of GOT entries reserved for trampolines */
142 guint32 num_trampoline_got_entries;
144 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
145 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
146 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
148 MonoAotOptions aot_opts;
151 MonoMemPool *mempool;
154 char *static_linking_symbol;
155 CRITICAL_SECTION mutex;
156 gboolean use_bin_writer;
158 MonoDwarfWriter *dwarf;
162 GHashTable *unwind_info_offsets;
163 GPtrArray *unwind_ops;
164 guint32 unwind_info_offset;
165 char *got_symbol_base;
168 GHashTable *method_label_hash;
169 const char *temp_prefix;
170 const char *llvm_label_prefix;
171 guint32 label_generator;
173 MonoAotFileFlags flags;
174 MonoDynamicStream blob;
177 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
178 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
180 /* This points to the current acfg in LLVM mode */
181 static MonoAotCompile *llvm_acfg;
183 #ifdef HAVE_ARRAY_ELEM_INIT
184 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
185 #define MSGSTRFIELD1(line) str##line
186 static const struct msgstr_t {
187 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
188 #include "patch-info.h"
191 #define PATCH_INFO(a,b) b,
192 #include "patch-info.h"
195 static const gint16 opidx [] = {
196 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
197 #include "patch-info.h"
201 static G_GNUC_UNUSED const char*
202 get_patch_name (int info)
204 return (const char*)&opstr + opidx [info];
208 #define PATCH_INFO(a,b) b,
209 static const char* const
210 patch_types [MONO_PATCH_INFO_NUM + 1] = {
211 #include "patch-info.h"
215 static G_GNUC_UNUSED const char*
216 get_patch_name (int info)
218 return patch_types [info];
223 /* Wrappers around the image writer functions */
226 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
228 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
232 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
234 img_writer_emit_push_section (acfg->w, section_name, subsection);
238 emit_pop_section (MonoAotCompile *acfg)
240 img_writer_emit_pop_section (acfg->w);
244 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
246 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
250 emit_label (MonoAotCompile *acfg, const char *name)
252 img_writer_emit_label (acfg->w, name);
256 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
258 img_writer_emit_bytes (acfg->w, buf, size);
262 emit_string (MonoAotCompile *acfg, const char *value)
264 img_writer_emit_string (acfg->w, value);
268 emit_line (MonoAotCompile *acfg)
270 img_writer_emit_line (acfg->w);
274 emit_alignment (MonoAotCompile *acfg, int size)
276 img_writer_emit_alignment (acfg->w, size);
280 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
282 img_writer_emit_pointer_unaligned (acfg->w, target);
286 emit_pointer (MonoAotCompile *acfg, const char *target)
288 img_writer_emit_pointer (acfg->w, target);
292 emit_int16 (MonoAotCompile *acfg, int value)
294 img_writer_emit_int16 (acfg->w, value);
298 emit_int32 (MonoAotCompile *acfg, int value)
300 img_writer_emit_int32 (acfg->w, value);
304 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
306 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
310 emit_zero_bytes (MonoAotCompile *acfg, int num)
312 img_writer_emit_zero_bytes (acfg->w, num);
316 emit_byte (MonoAotCompile *acfg, guint8 val)
318 img_writer_emit_byte (acfg->w, val);
321 static G_GNUC_UNUSED void
322 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
324 img_writer_emit_global (acfg->w, name, func);
328 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
330 if (acfg->aot_opts.no_dlsym) {
331 g_ptr_array_add (acfg->globals, g_strdup (name));
332 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
334 img_writer_emit_global (acfg->w, name, func);
339 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
341 img_writer_emit_symbol_size (acfg->w, name, end_label);
345 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
347 img_writer_emit_section_change (acfg->w, ".text", 1);
348 emit_global (acfg, name, FALSE);
349 img_writer_emit_label (acfg->w, name);
350 img_writer_emit_string (acfg->w, value);
353 static G_GNUC_UNUSED void
354 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
357 guint8 b = value & 0x7f;
359 if (value != 0) /* more bytes to come */
365 static G_GNUC_UNUSED void
366 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
369 gboolean negative = (value < 0);
376 /* the following is unnecessary if the
377 * implementation of >>= uses an arithmetic rather
378 * than logical shift for a signed left operand
382 value |= - ((gint64)1 <<(size - 7));
383 /* sign bit of byte is second high order bit (0x40) */
384 if ((value == 0 && !(byte & 0x40)) ||
385 (value == -1 && (byte & 0x40)))
389 emit_byte (acfg, byte);
393 static G_GNUC_UNUSED void
394 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
399 guint8 b = value & 0x7f;
401 if (value != 0) /* more bytes to come */
409 static G_GNUC_UNUSED void
410 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
413 gboolean negative = (value < 0);
421 /* the following is unnecessary if the
422 * implementation of >>= uses an arithmetic rather
423 * than logical shift for a signed left operand
427 value |= - (1 <<(size - 7));
428 /* sign bit of byte is second high order bit (0x40) */
429 if ((value == 0 && !(byte & 0x40)) ||
430 (value == -1 && (byte & 0x40)))
440 /* ARCHITECTURE SPECIFIC CODE */
442 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
443 #define EMIT_DWARF_INFO 1
446 #if defined(TARGET_ARM)
447 #define AOT_FUNC_ALIGNMENT 4
449 #define AOT_FUNC_ALIGNMENT 16
452 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
453 #define PPC_LD_OP "ld"
454 #define PPC_LDX_OP "ldx"
456 #define PPC_LD_OP "lwz"
457 #define PPC_LDX_OP "lwzx"
463 #define LLVM_LABEL_PREFIX "_"
465 #define LLVM_LABEL_PREFIX ""
470 #define LLC_TARGET_ARGS "-march=arm -mattr=+v6 -mtriple=arm-apple-darwin"
472 //#define LLC_TARGET_ARGS "-march=arm -mtriple=arm-linux-gnueabi -soft-float"
474 #define LLC_TARGET_ARGS ""
478 * arch_emit_direct_call:
480 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
484 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
486 #if defined(TARGET_X86) || defined(TARGET_AMD64)
487 /* Need to make sure this is exactly 5 bytes long */
488 emit_byte (acfg, '\xe8');
489 emit_symbol_diff (acfg, target, ".", -4);
491 #elif defined(TARGET_ARM)
492 if (acfg->use_bin_writer) {
499 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
500 emit_bytes (acfg, buf, 4);
502 img_writer_emit_unset_mode (acfg->w);
503 fprintf (acfg->fp, "bl %s\n", target);
506 #elif defined(TARGET_POWERPC)
507 if (acfg->use_bin_writer) {
508 g_assert_not_reached ();
510 img_writer_emit_unset_mode (acfg->w);
511 fprintf (acfg->fp, "bl %s\n", target);
515 g_assert_not_reached ();
521 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
523 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
524 * in in the 2. slot of every GOT, and require every method to place the GOT
525 * address in r30, even when it doesn't access the GOT otherwise. This way,
526 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
531 * PPC64 uses function descriptors which greatly complicate all code, since
532 * these are used very inconsistently in the runtime. Some functions like
533 * mono_compile_method () return ftn descriptors, while others like the
534 * trampoline creation functions do not.
535 * We assume that all GOT slots contain function descriptors, and create
536 * descriptors in aot-runtime.c when needed.
537 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
538 * from function descriptors, we could do the same, but it would require
539 * rewriting all the ppc/aot code to handle function descriptors properly.
540 * So instead, we use the same approach as on PPC32.
541 * This is a horrible mess, but fixing it would probably lead to an even bigger
545 #ifdef MONO_ARCH_AOT_SUPPORTED
547 * arch_emit_got_offset:
549 * The memory pointed to by CODE should hold native code for computing the GOT
550 * address. Emit this code while patching it with the offset between code and
551 * the GOT. CODE_SIZE is set to the number of bytes emitted.
554 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
556 #if defined(TARGET_POWERPC64)
557 g_assert (!acfg->use_bin_writer);
558 img_writer_emit_unset_mode (acfg->w);
560 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
561 * unsupported relocations. So we store the got address into the .Lgot_addr
562 * symbol which is in the text segment, compute its address, and load it.
564 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
565 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
566 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
567 fprintf (acfg->fp, "add 30, 30, 0\n");
568 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
569 acfg->label_generator ++;
571 #elif defined(TARGET_POWERPC)
572 g_assert (!acfg->use_bin_writer);
573 img_writer_emit_unset_mode (acfg->w);
574 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
575 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
576 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
577 acfg->label_generator ++;
580 guint32 offset = mono_arch_get_patch_offset (code);
581 emit_bytes (acfg, code, offset);
582 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
584 *code_size = offset + 4;
589 * arch_emit_got_access:
591 * The memory pointed to by CODE should hold native code for loading a GOT
592 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
593 * CODE_SIZE is set to the number of bytes emitted.
596 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
598 /* Emit beginning of instruction */
599 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
601 /* Emit the offset */
603 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
604 *code_size = mono_arch_get_patch_offset (code) + 4;
605 #elif defined(TARGET_X86)
606 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
607 *code_size = mono_arch_get_patch_offset (code) + 4;
608 #elif defined(TARGET_ARM)
609 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
610 *code_size = mono_arch_get_patch_offset (code) + 4;
611 #elif defined(TARGET_POWERPC)
617 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
618 g_assert (code - buf == 8);
619 emit_bytes (acfg, buf, code - buf);
620 *code_size = code - buf;
623 g_assert_not_reached ();
630 * arch_emit_plt_entry:
632 * Emit code for the PLT entry with index INDEX.
635 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
637 #if defined(TARGET_X86)
639 /* It is filled up during loading by the AOT loader. */
640 emit_zero_bytes (acfg, 16);
642 /* Need to make sure this is 9 bytes long */
643 emit_byte (acfg, '\xe9');
644 emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
645 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
647 #elif defined(TARGET_AMD64)
649 * We can't emit jumps because they are 32 bits only so they can't be patched.
650 * So we make indirect calls through GOT entries which are patched by the AOT
651 * loader to point to .Lpd entries.
653 /* jmpq *<offset>(%rip) */
654 emit_byte (acfg, '\xff');
655 emit_byte (acfg, '\x25');
656 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
657 /* Used by mono_aot_get_plt_info_offset */
658 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
659 #elif defined(TARGET_ARM)
664 * - optimize OP_AOTCONST implementation
665 * - optimize the PLT entries
666 * - optimize SWITCH AOT implementation
669 if (acfg->use_bin_writer && FALSE) {
670 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
671 /* We only emit 1 relocation since we implement it ourselves anyway */
672 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
673 /* FIXME: A 2 instruction encoding is sufficient in most cases */
674 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
675 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
676 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
677 emit_bytes (acfg, buf, code - buf);
678 /* Used by mono_aot_get_plt_info_offset */
679 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
681 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
682 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
683 emit_bytes (acfg, buf, code - buf);
684 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
685 /* Used by mono_aot_get_plt_info_offset */
686 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
689 * The plt_got_info_offset is computed automatically by
690 * mono_aot_get_plt_info_offset (), so no need to save it here.
692 #elif defined(TARGET_POWERPC)
693 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
695 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
696 g_assert (!acfg->use_bin_writer);
697 img_writer_emit_unset_mode (acfg->w);
698 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
699 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
700 fprintf (acfg->fp, "add 11, 11, 30\n");
701 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
702 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
703 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
704 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
706 fprintf (acfg->fp, "mtctr 11\n");
707 fprintf (acfg->fp, "bctr\n");
708 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
710 g_assert_not_reached ();
715 * arch_emit_specific_trampoline:
717 * Emit code for a specific trampoline. OFFSET is the offset of the first of
718 * two GOT slots which contain the generic trampoline address and the trampoline
719 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
722 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
725 * The trampolines created here are variations of the specific
726 * trampolines created in mono_arch_create_specific_trampoline (). The
728 * - the generic trampoline address is taken from a got slot.
729 * - the offset of the got slot where the trampoline argument is stored
730 * is embedded in the instruction stream, and the generic trampoline
731 * can load the argument by loading the offset, adding it to the
732 * address of the trampoline to get the address of the got slot, and
733 * loading the argument from there.
734 * - all the trampolines should be of the same length.
736 #if defined(TARGET_AMD64)
737 /* This should be exactly 16 bytes long */
739 /* call *<offset>(%rip) */
740 emit_byte (acfg, '\x41');
741 emit_byte (acfg, '\xff');
742 emit_byte (acfg, '\x15');
743 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
744 /* This should be relative to the start of the trampoline */
745 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
746 emit_zero_bytes (acfg, 5);
747 #elif defined(TARGET_ARM)
751 /* This should be exactly 20 bytes long */
754 ARM_PUSH (code, 0x5fff);
755 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
756 /* Load the value from the GOT */
757 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
759 ARM_BLX_REG (code, ARMREG_R1);
761 g_assert (code - buf == 16);
764 emit_bytes (acfg, buf, code - buf);
766 * Only one offset is needed, since the second one would be equal to the
769 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
770 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
771 #elif defined(TARGET_POWERPC)
778 g_assert (!acfg->use_bin_writer);
781 * PPC has no ip relative addressing, so we need to compute the address
782 * of the mscorlib got. That is slow and complex, so instead, we store it
783 * in the second got slot of every aot image. The caller already computed
784 * the address of its got and placed it into r30.
786 img_writer_emit_unset_mode (acfg->w);
787 /* Load mscorlib got address */
788 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
789 /* Load generic trampoline address */
790 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
791 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
792 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
793 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
794 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
796 fprintf (acfg->fp, "mtctr 11\n");
797 /* Load trampoline argument */
798 /* On ppc, we pass it normally to the generic trampoline */
799 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
800 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
801 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
802 /* Branch to generic trampoline */
803 fprintf (acfg->fp, "bctr\n");
805 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
806 *tramp_size = 10 * 4;
811 g_assert_not_reached ();
816 * arch_emit_unbox_trampoline:
818 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
819 * CALL_TARGET is the symbol pointing to the native code of METHOD.
822 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
824 #if defined(TARGET_AMD64)
829 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
831 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
833 emit_bytes (acfg, buf, code - buf);
835 emit_byte (acfg, '\xe9');
836 emit_symbol_diff (acfg, call_target, ".", -4);
837 #elif defined(TARGET_ARM)
844 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
847 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
849 emit_bytes (acfg, buf, code - buf);
851 if (acfg->use_bin_writer) {
858 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
859 emit_bytes (acfg, buf, 4);
861 fprintf (acfg->fp, "\n\tb %s\n", call_target);
863 #elif defined(TARGET_POWERPC)
866 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
869 g_assert (!acfg->use_bin_writer);
871 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
872 fprintf (acfg->fp, "\n\tb %s\n", call_target);
874 g_assert_not_reached ();
879 * arch_emit_static_rgctx_trampoline:
881 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
882 * two GOT slots which contain the rgctx argument, and the method to jump to.
883 * TRAMP_SIZE is set to the size of the emitted trampoline.
884 * These kinds of trampolines cannot be enumerated statically, since there could
885 * be one trampoline per method instantiation, so we emit the same code for all
886 * trampolines, and parameterize them using two GOT slots.
889 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
891 #if defined(TARGET_AMD64)
892 /* This should be exactly 13 bytes long */
895 /* mov <OFFSET>(%rip), %r10 */
896 emit_byte (acfg, '\x4d');
897 emit_byte (acfg, '\x8b');
898 emit_byte (acfg, '\x15');
899 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
901 /* jmp *<offset>(%rip) */
902 emit_byte (acfg, '\xff');
903 emit_byte (acfg, '\x25');
904 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
905 #elif defined(TARGET_ARM)
909 /* This should be exactly 24 bytes long */
912 /* Load rgctx value */
913 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
914 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
915 /* Load branch addr + branch */
916 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
917 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
919 g_assert (code - buf == 16);
922 emit_bytes (acfg, buf, code - buf);
923 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
924 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
925 #elif defined(TARGET_POWERPC)
932 g_assert (!acfg->use_bin_writer);
935 * PPC has no ip relative addressing, so we need to compute the address
936 * of the mscorlib got. That is slow and complex, so instead, we store it
937 * in the second got slot of every aot image. The caller already computed
938 * the address of its got and placed it into r30.
940 img_writer_emit_unset_mode (acfg->w);
941 /* Load mscorlib got address */
942 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
944 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
945 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
946 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
947 /* Load target address */
948 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
949 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
950 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
951 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
952 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
953 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
955 fprintf (acfg->fp, "mtctr 11\n");
956 /* Branch to the target address */
957 fprintf (acfg->fp, "bctr\n");
959 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
960 *tramp_size = 11 * 4;
966 g_assert_not_reached ();
971 * arch_emit_imt_thunk:
973 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
974 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
975 * key is the IMT key, and ptr holds the address of a memory location holding
976 * the address to branch to if the IMT arg matches the key. The array is
977 * terminated by a pair whose key is NULL, and whose ptr is the address of the
979 * TRAMP_SIZE is set to the size of the emitted trampoline.
982 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
984 #if defined(TARGET_AMD64)
988 code = buf = g_malloc (256);
990 /* FIXME: Optimize this, i.e. use binary search etc. */
991 /* Maybe move the body into a separate function (slower, but much smaller) */
993 /* R10 is a free register */
996 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
998 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1001 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
1003 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1006 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
1007 amd64_jump_code (code, labels [0]);
1010 mono_amd64_patch (labels [2], code);
1011 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
1012 amd64_jump_membase (code, AMD64_R10, 0);
1016 mono_amd64_patch (labels [1], code);
1017 x86_breakpoint (code);
1019 /* mov <OFFSET>(%rip), %r10 */
1020 emit_byte (acfg, '\x4d');
1021 emit_byte (acfg, '\x8b');
1022 emit_byte (acfg, '\x15');
1023 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1025 emit_bytes (acfg, buf, code - buf);
1027 *tramp_size = code - buf + 7;
1028 #elif defined(TARGET_ARM)
1030 guint8 *code, *code2, *labels [16];
1034 /* The IMT method is in v5 */
1036 /* Need at least two free registers, plus a slot for storing the pc */
1037 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1039 /* Load the parameter from the GOT */
1040 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1041 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1044 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1045 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1047 ARM_B_COND (code, ARMCOND_EQ, 0);
1049 /* End-of-loop check */
1050 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1052 ARM_B_COND (code, ARMCOND_EQ, 0);
1055 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1058 arm_patch (labels [4], labels [1]);
1061 arm_patch (labels [2], code);
1062 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1063 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1064 /* Save it to the third stack slot */
1065 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1066 /* Restore the registers and branch */
1067 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1070 arm_patch (labels [3], code);
1075 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1077 emit_bytes (acfg, buf, code - buf);
1078 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1080 *tramp_size = code - buf + 4;
1081 #elif defined(TARGET_POWERPC)
1083 guint8 *code, *labels [16];
1087 /* Load the mscorlib got address */
1088 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1089 /* Load the parameter from the GOT */
1090 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1091 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1093 /* Load and check key */
1095 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1096 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1098 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1100 /* End-of-loop check */
1101 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1103 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1106 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1109 mono_ppc_patch (labels [4], labels [1]);
1112 mono_ppc_patch (labels [2], code);
1113 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1114 /* r11 now contains the value of the vtable slot */
1115 /* this is not a function descriptor on ppc64 */
1116 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1117 ppc_mtctr (code, ppc_r11);
1118 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1121 mono_ppc_patch (labels [3], code);
1125 *tramp_size = code - buf;
1127 emit_bytes (acfg, buf, code - buf);
1129 g_assert_not_reached ();
1134 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1136 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1137 /* Based on code generated by gcc */
1138 img_writer_emit_unset_mode (acfg->w);
1141 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1142 ".section .ctors,\"aw\",@progbits\n"
1146 ".section .opd,\"aw\"\n"
1149 ".long .%s,.TOC.@tocbase32\n"
1152 ".type .%s,@function\n"
1154 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1156 ".section .ctors,\"aw\",@progbits\n"
1160 ".section .opd,\"aw\"\n"
1163 ".long .%1$s,.TOC.@tocbase32\n"
1164 ".size %1$s,.-%1$s\n"
1166 ".type .%1$s,@function\n"
1168 ".%1$s:\n", symbol);
1179 "lis 3, .Lglobals@h\n"
1180 "ori 3, 3, .Lglobals@l\n"
1181 "bl .mono_aot_register_module\n"
1189 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1191 ".size .%s,.-.%s\n", symbol, symbol);
1194 ".size .%1$s,.-.%1$s\n", symbol);
1201 * mono_arch_get_cie_program:
1203 * Get the unwind bytecode for the DWARF CIE.
1206 mono_arch_get_cie_program (void)
1211 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
1212 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
1215 #elif defined(TARGET_POWERPC)
1218 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, ppc_r1, 0);
1226 /* END OF ARCH SPECIFIC CODE */
1229 mono_get_field_token (MonoClassField *field)
1231 MonoClass *klass = field->parent;
1234 for (i = 0; i < klass->field.count; ++i) {
1235 if (field == &klass->fields [i])
1236 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1239 g_assert_not_reached ();
1244 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1248 //printf ("ENCODE: %d 0x%x.\n", value, value);
1251 * Same encoding as the one used in the metadata, extended to handle values
1252 * greater than 0x1fffffff.
1254 if ((value >= 0) && (value <= 127))
1256 else if ((value >= 0) && (value <= 16383)) {
1257 p [0] = 0x80 | (value >> 8);
1258 p [1] = value & 0xff;
1260 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1261 p [0] = (value >> 24) | 0xc0;
1262 p [1] = (value >> 16) & 0xff;
1263 p [2] = (value >> 8) & 0xff;
1264 p [3] = value & 0xff;
1269 p [1] = (value >> 24) & 0xff;
1270 p [2] = (value >> 16) & 0xff;
1271 p [3] = (value >> 8) & 0xff;
1272 p [4] = value & 0xff;
1280 stream_init (MonoDynamicStream *sh)
1283 sh->alloc_size = 4096;
1284 sh->data = g_malloc (4096);
1286 /* So offsets are > 0 */
1291 make_room_in_stream (MonoDynamicStream *stream, int size)
1293 if (size <= stream->alloc_size)
1296 while (stream->alloc_size <= size) {
1297 if (stream->alloc_size < 4096)
1298 stream->alloc_size = 4096;
1300 stream->alloc_size *= 2;
1303 stream->data = g_realloc (stream->data, stream->alloc_size);
1307 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1311 make_room_in_stream (stream, stream->index + len);
1312 memcpy (stream->data + stream->index, data, len);
1313 idx = stream->index;
1314 stream->index += len;
1321 * Add data to the binary blob inside the aot image. Returns the offset inside the
1322 * blob where the data was stored.
1325 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1327 if (acfg->blob.alloc_size == 0)
1328 stream_init (&acfg->blob);
1330 return add_stream_data (&acfg->blob, (char*)data, data_len);
1334 * emit_offset_table:
1336 * Emit a table of increasing offsets in a compact form using differential encoding.
1337 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1338 * group size, the more compact the table becomes, but the slower it becomes to compute
1339 * a given entry. Returns the size of the table.
1342 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1344 gint32 current_offset;
1345 int i, buf_size, ngroups, index_entry_size;
1347 guint32 *index_offsets;
1349 ngroups = (noffsets + (group_size - 1)) / group_size;
1351 index_offsets = g_new0 (guint32, ngroups);
1353 buf_size = noffsets * 4;
1354 p = buf = g_malloc0 (buf_size);
1357 for (i = 0; i < noffsets; ++i) {
1358 //printf ("D: %d -> %d\n", i, offsets [i]);
1359 if ((i % group_size) == 0) {
1360 index_offsets [i / group_size] = p - buf;
1361 /* Emit the full value for these entries */
1362 encode_value (offsets [i], p, &p);
1364 /* The offsets are allowed to be non-increasing */
1365 //g_assert (offsets [i] >= current_offset);
1366 encode_value (offsets [i] - current_offset, p, &p);
1368 current_offset = offsets [i];
1371 if (ngroups && index_offsets [ngroups - 1] < 65000)
1372 index_entry_size = 2;
1374 index_entry_size = 4;
1376 /* Emit the header */
1377 emit_int32 (acfg, noffsets);
1378 emit_int32 (acfg, group_size);
1379 emit_int32 (acfg, ngroups);
1380 emit_int32 (acfg, index_entry_size);
1382 /* Emit the index */
1383 for (i = 0; i < ngroups; ++i) {
1384 if (index_entry_size == 2)
1385 emit_int16 (acfg, index_offsets [i]);
1387 emit_int32 (acfg, index_offsets [i]);
1391 emit_bytes (acfg, buf, p - buf);
1393 return (int)(p - buf) + (ngroups * 4);
1397 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1401 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1405 index = g_hash_table_size (cfg->image_hash);
1406 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1407 g_ptr_array_add (cfg->image_table, image);
1413 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1416 MonoClass *k = NULL;
1418 /* FIXME: Search referenced images as well */
1419 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1420 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1425 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1426 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1432 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1437 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1438 * standard metadata encoding.
1441 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1445 if (klass->generic_class) {
1447 g_assert (klass->type_token);
1449 /* Find a typespec for a class if possible */
1450 token = find_typespec_for_class (acfg, klass);
1452 encode_value (token, p, &p);
1453 encode_value (get_image_index (acfg, acfg->image), p, &p);
1455 MonoClass *gclass = klass->generic_class->container_class;
1456 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1459 /* Encode it ourselves */
1461 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1462 encode_value (MONO_TYPE_GENERICINST, p, &p);
1463 encode_klass_ref (acfg, gclass, p, &p);
1464 encode_value (inst->type_argc, p, &p);
1465 for (i = 0; i < inst->type_argc; ++i)
1466 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1468 } else if (klass->type_token) {
1469 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1470 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1471 encode_value (get_image_index (acfg, klass->image), p, &p);
1472 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1473 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1474 g_assert (container);
1477 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1478 encode_value (klass->byval_arg.type, p, &p);
1480 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1482 encode_value (container->is_method, p, &p);
1483 if (container->is_method)
1484 encode_method_ref (acfg, container->owner.method, p, &p);
1486 encode_klass_ref (acfg, container->owner.klass, p, &p);
1489 g_assert (klass->rank > 0);
1490 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1491 encode_value (get_image_index (acfg, klass->image), p, &p);
1492 encode_value (klass->rank, p, &p);
1493 encode_klass_ref (acfg, klass->element_class, p, &p);
1499 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1501 guint32 token = mono_get_field_token (field);
1504 encode_klass_ref (cfg, field->parent, p, &p);
1505 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1506 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1511 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1515 MonoGenericInst *inst;
1517 /* Encode the context */
1518 inst = context->class_inst;
1519 encode_value (inst ? 1 : 0, p, &p);
1521 encode_value (inst->type_argc, p, &p);
1522 for (i = 0; i < inst->type_argc; ++i)
1523 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1525 inst = context->method_inst;
1526 encode_value (inst ? 1 : 0, p, &p);
1528 encode_value (inst->type_argc, p, &p);
1529 for (i = 0; i < inst->type_argc; ++i)
1530 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1536 #define MAX_IMAGE_INDEX 250
1539 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1541 guint32 image_index = get_image_index (acfg, method->klass->image);
1542 guint32 token = method->token;
1543 MonoJumpInfoToken *ji;
1548 * The encoding for most methods is as follows:
1549 * - image index encoded as a leb128
1550 * - token index encoded as a leb128
1551 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1552 * types of method encodings.
1555 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1557 /* Mark methods which can't use aot trampolines because they need the further
1558 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1560 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1561 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1562 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1565 * Some wrapper methods are shared using their signature, encode their
1566 * stringified signature instead.
1567 * FIXME: Optimize disk usage
1570 if (method->wrapper_type) {
1571 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1572 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1573 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1574 name = mono_aot_wrapper_name (method);
1575 } else if (mono_marshal_method_from_wrapper (method) != method) {
1576 /* Direct wrapper, encode it normally */
1578 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1581 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1582 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1583 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1585 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1586 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1587 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1589 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1590 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1591 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1597 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1598 strcpy ((char*)p, name);
1599 p += strlen (name) + 1;
1601 } else if (method->wrapper_type) {
1602 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1604 encode_value (method->wrapper_type, p, &p);
1606 switch (method->wrapper_type) {
1607 case MONO_WRAPPER_REMOTING_INVOKE:
1608 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1609 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1612 m = mono_marshal_method_from_wrapper (method);
1614 encode_method_ref (acfg, m, p, &p);
1617 case MONO_WRAPPER_PROXY_ISINST:
1618 case MONO_WRAPPER_LDFLD:
1619 case MONO_WRAPPER_LDFLDA:
1620 case MONO_WRAPPER_STFLD:
1621 case MONO_WRAPPER_ISINST: {
1622 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1623 encode_klass_ref (acfg, proxy_class, p, &p);
1626 case MONO_WRAPPER_LDFLD_REMOTE:
1627 case MONO_WRAPPER_STFLD_REMOTE:
1629 case MONO_WRAPPER_ALLOC: {
1630 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1632 g_assert (info->alloc_type != -1);
1633 encode_value (info->alloc_type, p, &p);
1636 case MONO_WRAPPER_WRITE_BARRIER:
1638 case MONO_WRAPPER_STELEMREF:
1640 case MONO_WRAPPER_UNKNOWN:
1641 if (strcmp (method->name, "FastMonitorEnter") == 0)
1642 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1643 else if (strcmp (method->name, "FastMonitorExit") == 0)
1644 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1646 g_assert_not_reached ();
1648 case MONO_WRAPPER_SYNCHRONIZED:
1649 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1650 case MONO_WRAPPER_RUNTIME_INVOKE: {
1653 m = mono_marshal_method_from_wrapper (method);
1655 g_assert (m != method);
1656 encode_method_ref (acfg, m, p, &p);
1659 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1660 if (!strcmp (method->name, "ElementAddr")) {
1661 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1664 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1665 encode_value (info->rank, p, &p);
1666 encode_value (info->elem_size, p, &p);
1668 g_assert_not_reached ();
1672 g_assert_not_reached ();
1674 } else if (mono_method_signature (method)->is_inflated) {
1676 * This is a generic method, find the original token which referenced it and
1678 * Obtain the token from information recorded by the JIT.
1680 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1682 image_index = get_image_index (acfg, ji->image);
1683 g_assert (image_index < MAX_IMAGE_INDEX);
1686 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1687 encode_value (image_index, p, &p);
1688 encode_value (token, p, &p);
1690 MonoMethod *declaring;
1691 MonoGenericContext *context = mono_method_get_context (method);
1693 g_assert (method->is_inflated);
1694 declaring = ((MonoMethodInflated*)method)->declaring;
1697 * This might be a non-generic method of a generic instance, which
1698 * doesn't have a token since the reference is generated by the JIT
1699 * like Nullable:Box/Unbox, or by generic sharing.
1702 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1703 /* Encode the klass */
1704 encode_klass_ref (acfg, method->klass, p, &p);
1705 /* Encode the method */
1706 image_index = get_image_index (acfg, method->klass->image);
1707 g_assert (image_index < MAX_IMAGE_INDEX);
1708 g_assert (declaring->token);
1709 token = declaring->token;
1710 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1711 encode_value (image_index, p, &p);
1712 encode_value (token, p, &p);
1713 encode_generic_context (acfg, context, p, &p);
1715 } else if (token == 0) {
1716 /* This might be a method of a constructed type like int[,].Set */
1717 /* Obtain the token from information recorded by the JIT */
1718 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1720 image_index = get_image_index (acfg, ji->image);
1721 g_assert (image_index < MAX_IMAGE_INDEX);
1724 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1725 encode_value (image_index, p, &p);
1726 encode_value (token, p, &p);
1729 g_assert (method->klass->rank);
1731 /* Encode directly */
1732 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1733 encode_klass_ref (acfg, method->klass, p, &p);
1734 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1735 encode_value (0, p, &p);
1736 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1737 encode_value (1, p, &p);
1738 else if (!strcmp (method->name, "Get"))
1739 encode_value (2, p, &p);
1740 else if (!strcmp (method->name, "Address"))
1741 encode_value (3, p, &p);
1742 else if (!strcmp (method->name, "Set"))
1743 encode_value (4, p, &p);
1745 g_assert_not_reached ();
1748 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1749 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1755 compare_patches (gconstpointer a, gconstpointer b)
1759 i = (*(MonoJumpInfo**)a)->ip.i;
1760 j = (*(MonoJumpInfo**)b)->ip.i;
1774 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1777 static inline gboolean
1778 is_plt_patch (MonoJumpInfo *patch_info)
1780 switch (patch_info->type) {
1781 case MONO_PATCH_INFO_METHOD:
1782 case MONO_PATCH_INFO_INTERNAL_METHOD:
1783 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1784 case MONO_PATCH_INFO_ICALL_ADDR:
1785 case MONO_PATCH_INFO_CLASS_INIT:
1786 case MONO_PATCH_INFO_RGCTX_FETCH:
1787 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1788 case MONO_PATCH_INFO_MONITOR_ENTER:
1789 case MONO_PATCH_INFO_MONITOR_EXIT:
1790 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1798 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1802 if (is_plt_patch (patch_info)) {
1803 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1805 // FIXME: This breaks the calculation of final_got_size
1806 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1808 * Allocate a separate PLT slot for each such patch, since some plt
1809 * entries will refer to the method itself, and some will refer to the
1818 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1820 g_assert (!acfg->final_got_size);
1822 res = acfg->plt_offset;
1823 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1824 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1825 acfg->plt_offset ++;
1835 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1836 * JI could be found if it exists, otherwise allocates a new one.
1839 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1843 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1845 return got_offset - 1;
1847 got_offset = acfg->got_offset;
1848 acfg->got_offset ++;
1850 if (acfg->final_got_size)
1851 g_assert (got_offset < acfg->final_got_size);
1853 acfg->stats.got_slots ++;
1854 acfg->stats.got_slot_types [ji->type] ++;
1856 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1857 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1858 g_ptr_array_add (acfg->got_patches, ji);
1863 /* Add a method to the list of methods which need to be emitted */
1865 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1868 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1869 g_ptr_array_add (acfg->methods, method);
1870 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1871 acfg->nmethods = acfg->methods->len + 1;
1874 if (method->wrapper_type || extra)
1875 g_ptr_array_add (acfg->extra_methods, method);
1879 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1881 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1889 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1893 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1897 index = acfg->method_index;
1898 add_method_with_index (acfg, method, index, extra);
1900 /* FIXME: Fix quadratic behavior */
1901 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1903 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1905 acfg->method_index ++;
1911 add_method (MonoAotCompile *acfg, MonoMethod *method)
1913 return add_method_full (acfg, method, FALSE, 0);
1917 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1919 add_method_full (acfg, method, TRUE, 0);
1923 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
1925 add_method_full (acfg, method, TRUE, depth);
1929 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1931 MonoAotCompile *acfg = user_data;
1932 MonoJitICallInfo *callinfo = value;
1933 MonoMethod *wrapper;
1939 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1940 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1943 add_method (acfg, wrapper);
1947 get_runtime_invoke_sig (MonoMethodSignature *sig)
1949 MonoMethodBuilder *mb;
1952 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1953 m = mono_mb_create_method (mb, sig, 16);
1954 return mono_marshal_get_runtime_invoke (m, FALSE);
1958 can_marshal_struct (MonoClass *klass)
1960 MonoClassField *field;
1961 gboolean can_marshal = TRUE;
1962 gpointer iter = NULL;
1964 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1967 /* Only allow a few field types to avoid asserts in the marshalling code */
1968 while ((field = mono_class_get_fields (klass, &iter))) {
1969 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1972 switch (field->type->type) {
1977 case MONO_TYPE_BOOLEAN:
1980 case MONO_TYPE_CHAR:
1988 case MONO_TYPE_STRING:
1990 case MONO_TYPE_VALUETYPE:
1991 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
1992 can_marshal = FALSE;
1995 can_marshal = FALSE;
2001 /* Its hard to compute whenever these can be marshalled or not */
2002 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2009 add_wrappers (MonoAotCompile *acfg)
2011 MonoMethod *method, *m;
2013 MonoMethodSignature *sig, *csig;
2017 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2018 * so there is only one wrapper of a given type, or inlining their contents into their
2023 * FIXME: This depends on the fact that different wrappers have different
2027 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2029 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2030 gboolean skip = FALSE;
2032 method = mono_get_method (acfg->image, token, NULL);
2034 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2035 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2036 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2039 if (method->is_generic || method->klass->generic_container)
2042 /* Skip methods which can not be handled by get_runtime_invoke () */
2043 sig = mono_method_signature (method);
2044 if ((sig->ret->type == MONO_TYPE_PTR) ||
2045 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2048 for (j = 0; j < sig->param_count; j++) {
2049 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2053 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2054 if (!method->klass->contextbound) {
2055 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2056 gboolean has_nullable = FALSE;
2058 for (j = 0; j < sig->param_count; j++) {
2059 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2060 has_nullable = TRUE;
2063 if (info && !has_nullable) {
2064 /* Supported by the dynamic runtime-invoke wrapper */
2072 //printf ("%s\n", mono_method_full_name (method, TRUE));
2073 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2077 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2078 #ifdef MONO_ARCH_HAVE_TLS_GET
2079 MonoMethodDesc *desc;
2080 MonoMethod *orig_method;
2084 /* Runtime invoke wrappers */
2086 /* void runtime-invoke () [.cctor] */
2087 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2088 csig->ret = &mono_defaults.void_class->byval_arg;
2089 add_method (acfg, get_runtime_invoke_sig (csig));
2091 /* void runtime-invoke () [Finalize] */
2092 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2094 csig->ret = &mono_defaults.void_class->byval_arg;
2095 add_method (acfg, get_runtime_invoke_sig (csig));
2097 /* void runtime-invoke (string) [exception ctor] */
2098 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2100 csig->ret = &mono_defaults.void_class->byval_arg;
2101 csig->params [0] = &mono_defaults.string_class->byval_arg;
2102 add_method (acfg, get_runtime_invoke_sig (csig));
2104 /* void runtime-invoke (string, string) [exception ctor] */
2105 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2107 csig->ret = &mono_defaults.void_class->byval_arg;
2108 csig->params [0] = &mono_defaults.string_class->byval_arg;
2109 csig->params [1] = &mono_defaults.string_class->byval_arg;
2110 add_method (acfg, get_runtime_invoke_sig (csig));
2112 /* string runtime-invoke () [Exception.ToString ()] */
2113 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2115 csig->ret = &mono_defaults.string_class->byval_arg;
2116 add_method (acfg, get_runtime_invoke_sig (csig));
2118 /* void runtime-invoke (string, Exception) [exception ctor] */
2119 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2121 csig->ret = &mono_defaults.void_class->byval_arg;
2122 csig->params [0] = &mono_defaults.string_class->byval_arg;
2123 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2124 add_method (acfg, get_runtime_invoke_sig (csig));
2126 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2127 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2129 csig->ret = &(mono_class_from_name (
2130 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2131 csig->params [0] = &mono_defaults.string_class->byval_arg;
2132 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2133 add_method (acfg, get_runtime_invoke_sig (csig));
2135 /* runtime-invoke used by finalizers */
2136 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2138 /* This is used by mono_runtime_capture_context () */
2139 method = mono_get_context_capture_method ();
2141 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2143 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2144 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2147 /* JIT icall wrappers */
2148 /* FIXME: locking */
2149 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2152 add_method (acfg, mono_marshal_get_stelemref ());
2154 #ifdef MONO_ARCH_HAVE_TLS_GET
2155 /* Managed Allocators */
2156 nallocators = mono_gc_get_managed_allocator_types ();
2157 for (i = 0; i < nallocators; ++i) {
2158 m = mono_gc_get_managed_allocator_by_type (i);
2160 add_method (acfg, m);
2163 /* Monitor Enter/Exit */
2164 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2165 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2166 g_assert (orig_method);
2167 mono_method_desc_free (desc);
2168 method = mono_monitor_get_fast_path (orig_method);
2170 add_method (acfg, method);
2172 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2173 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2174 g_assert (orig_method);
2175 mono_method_desc_free (desc);
2176 method = mono_monitor_get_fast_path (orig_method);
2178 add_method (acfg, method);
2183 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2184 * we use the original method instead at runtime.
2185 * Since full-aot doesn't support remoting, this is not a problem.
2188 /* remoting-invoke wrappers */
2189 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2190 MonoMethodSignature *sig;
2192 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2193 method = mono_get_method (acfg->image, token, NULL);
2195 sig = mono_method_signature (method);
2197 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2198 m = mono_marshal_get_remoting_invoke_with_check (method);
2200 add_method (acfg, m);
2205 /* delegate-invoke wrappers */
2206 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2209 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2210 klass = mono_class_get (acfg->image, token);
2212 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2213 method = mono_get_delegate_invoke (klass);
2215 m = mono_marshal_get_delegate_invoke (method, NULL);
2217 add_method (acfg, m);
2219 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2220 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2222 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2223 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2227 /* Synchronized wrappers */
2228 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2229 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2230 method = mono_get_method (acfg->image, token, NULL);
2232 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2233 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2236 /* pinvoke wrappers */
2237 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2239 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2241 method = mono_get_method (acfg->image, token, NULL);
2243 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2244 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2245 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2249 /* native-to-managed wrappers */
2250 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2252 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2253 MonoCustomAttrInfo *cattr;
2256 method = mono_get_method (acfg->image, token, NULL);
2259 * Only generate native-to-managed wrappers for methods which have an
2260 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2261 * name to avoid defining a new assembly to contain it.
2263 cattr = mono_custom_attrs_from_method (method);
2266 for (j = 0; j < cattr->num_attrs; ++j)
2267 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2269 if (j < cattr->num_attrs) {
2270 MonoCustomAttrEntry *e = &cattr->attrs [j];
2271 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2272 const char *p = (const char*)e->data;
2278 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2280 g_assert (sig->param_count == 1);
2281 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2284 * Decode the cattr manually since we can't create objects
2285 * during aot compilation.
2291 /* From load_cattr_value () in reflection.c */
2292 slen = mono_metadata_decode_value (p, &p);
2293 n = g_memdup (p, slen + 1);
2295 t = mono_reflection_type_from_name (n, acfg->image);
2299 klass = mono_class_from_mono_type (t);
2300 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2302 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, NULL));
2306 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2307 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2308 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2312 /* StructureToPtr/PtrToStructure wrappers */
2313 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2316 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2317 klass = mono_class_get (acfg->image, token);
2319 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2320 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2321 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2327 has_type_vars (MonoClass *klass)
2329 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2332 return has_type_vars (klass->element_class);
2333 if (klass->generic_class) {
2334 MonoGenericContext *context = &klass->generic_class->context;
2335 if (context->class_inst) {
2338 for (i = 0; i < context->class_inst->type_argc; ++i)
2339 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2347 method_has_type_vars (MonoMethod *method)
2349 if (has_type_vars (method->klass))
2352 if (method->is_inflated) {
2353 MonoGenericContext *context = mono_method_get_context (method);
2354 if (context->method_inst) {
2357 for (i = 0; i < context->method_inst->type_argc; ++i)
2358 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2366 * add_generic_class:
2368 * Add all methods of a generic class.
2371 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2376 mono_class_init (klass);
2378 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2381 if (has_type_vars (klass))
2384 if (!klass->generic_class && !klass->rank)
2388 while ((method = mono_class_get_methods (klass, &iter))) {
2389 if (mono_method_is_generic_sharable_impl (method, FALSE))
2393 if (method->is_generic)
2398 * FIXME: Instances which are referenced by these methods are not added,
2399 * for example Array.Resize<int> for List<int>.Add ().
2401 add_extra_method (acfg, method);
2404 if (klass->delegate) {
2405 method = mono_get_delegate_invoke (klass);
2407 method = mono_marshal_get_delegate_invoke (method, NULL);
2409 add_method (acfg, method);
2413 * For ICollection<T>, add instances of the helper methods
2414 * in Array, since a T[] could be cast to ICollection<T>.
2416 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2417 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2418 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2419 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2423 if (!strcmp (klass->name, "IEnumerator`1"))
2424 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2426 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2428 /* Add the T[]/InternalEnumerator class */
2429 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2433 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2434 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2438 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2439 add_generic_class (acfg, nclass);
2443 while ((method = mono_class_get_methods (array_class, &iter))) {
2444 if (strstr (method->name, name_prefix)) {
2445 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2446 add_extra_method (acfg, m);
2450 g_free (name_prefix);
2453 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2454 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2455 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2456 MonoClass *icomparable, *gcomparer;
2457 MonoGenericContext ctx;
2458 MonoType *args [16];
2460 memset (&ctx, 0, sizeof (ctx));
2462 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2463 g_assert (icomparable);
2464 args [0] = &tclass->byval_arg;
2465 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2467 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2468 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2469 g_assert (gcomparer);
2470 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2476 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2479 MonoGenericContext ctx;
2480 MonoType *args [16];
2482 memset (&ctx, 0, sizeof (ctx));
2484 for (i = 0; i < ninsts; ++i) {
2485 args [0] = insts [i];
2486 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2487 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2492 * add_generic_instances:
2494 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2497 add_generic_instances (MonoAotCompile *acfg)
2502 MonoMethodHeader *header;
2503 MonoMethodSignature *sig;
2504 MonoGenericContext *context;
2506 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2507 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2508 method = mono_get_method (acfg->image, token, NULL);
2510 context = mono_method_get_context (method);
2511 if (context && ((context->class_inst && context->class_inst->is_open) ||
2512 (context->method_inst && context->method_inst->is_open)))
2515 if (method->klass->image != acfg->image)
2518 if (mono_method_is_generic_sharable_impl (method, FALSE))
2522 add_extra_method (acfg, method);
2525 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2528 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2530 klass = mono_class_get (acfg->image, token);
2531 if (!klass || klass->rank)
2534 add_generic_class (acfg, klass);
2537 /* Add types of args/locals */
2538 for (i = 0; i < acfg->methods->len; ++i) {
2541 method = g_ptr_array_index (acfg->methods, i);
2543 sig = mono_method_signature (method);
2546 for (j = 0; j < sig->param_count; ++j)
2547 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2548 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2551 header = mono_method_get_header (method);
2554 for (j = 0; j < header->num_locals; ++j)
2555 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2556 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2560 if (acfg->image == mono_defaults.corlib) {
2562 MonoType *insts [256];
2565 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2566 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2567 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2568 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2569 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2570 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2571 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2572 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2573 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2574 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2575 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2576 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2578 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2579 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2581 add_instances_of (acfg, klass, insts, ninsts);
2582 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2584 add_instances_of (acfg, klass, insts, ninsts);
2586 /* Add instances of the array generic interfaces for primitive types */
2587 /* This will add instances of the InternalArray_ helper methods in Array too */
2588 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2590 add_instances_of (acfg, klass, insts, ninsts);
2591 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2593 add_instances_of (acfg, klass, insts, ninsts);
2594 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2596 add_instances_of (acfg, klass, insts, ninsts);
2599 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2600 * used for all instances of GetGenericValueImpl by the AOT runtime.
2603 MonoGenericContext ctx;
2604 MonoType *args [16];
2605 MonoMethod *get_method;
2606 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2608 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2611 memset (&ctx, 0, sizeof (ctx));
2612 args [0] = &mono_defaults.object_class->byval_arg;
2613 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2614 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2621 * is_direct_callable:
2623 * Return whenever the method identified by JI is directly callable without
2624 * going through the PLT.
2627 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2629 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2630 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2632 gboolean direct_callable = TRUE;
2634 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2635 direct_callable = FALSE;
2636 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2637 // FIXME: Maybe call the wrapper directly ?
2638 direct_callable = FALSE;
2640 if (direct_callable)
2649 * emit_and_reloc_code:
2651 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2652 * is true, calls are made through the GOT too. This is used for emitting trampolines
2653 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2654 * since trampolines are needed to make PTL work.
2657 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2659 int i, pindex, start_index, method_index;
2661 MonoJumpInfo *patch_info;
2662 MonoMethodHeader *header;
2663 gboolean skip, direct_call;
2665 char direct_call_target [128];
2668 header = mono_method_get_header (method);
2670 method_index = get_method_index (acfg, method);
2673 /* Collect and sort relocations */
2674 patches = g_ptr_array_new ();
2675 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2676 g_ptr_array_add (patches, patch_info);
2677 g_ptr_array_sort (patches, compare_patches);
2680 for (i = 0; i < code_len; i++) {
2682 for (pindex = start_index; pindex < patches->len; ++pindex) {
2683 patch_info = g_ptr_array_index (patches, pindex);
2684 if (patch_info->ip.i >= i)
2688 #ifdef MONO_ARCH_AOT_SUPPORTED
2690 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2691 start_index = pindex;
2693 switch (patch_info->type) {
2694 case MONO_PATCH_INFO_NONE:
2696 case MONO_PATCH_INFO_GOT_OFFSET: {
2699 arch_emit_got_offset (acfg, code + i, &code_size);
2702 patch_info->type = MONO_PATCH_INFO_NONE;
2707 * If this patch is a call, try emitting a direct call instead of
2708 * through a PLT entry. This is possible if the called method is in
2709 * the same assembly and requires no initialization.
2711 direct_call = FALSE;
2712 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2713 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2714 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2715 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2717 sprintf (direct_call_target, callee_cfg->asm_symbol);
2718 patch_info->type = MONO_PATCH_INFO_NONE;
2719 acfg->stats.direct_calls ++;
2722 acfg->stats.all_calls ++;
2725 if (!got_only && !direct_call) {
2726 int plt_offset = get_plt_offset (acfg, patch_info);
2727 if (plt_offset != -1) {
2728 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2730 sprintf (direct_call_target, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
2732 /* Nullify the patch */
2733 patch_info->type = MONO_PATCH_INFO_NONE;
2740 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2745 got_slot = get_got_offset (acfg, patch_info);
2747 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2754 #endif /* MONO_ARCH_AOT_SUPPORTED */
2757 /* Find next patch */
2759 for (pindex = start_index; pindex < patches->len; ++pindex) {
2760 patch_info = g_ptr_array_index (patches, pindex);
2761 if (patch_info->ip.i >= i)
2765 /* Try to emit multiple bytes at once */
2766 if (pindex < patches->len && patch_info->ip.i > i) {
2767 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2768 i = patch_info->ip.i - 1;
2770 emit_bytes (acfg, code + i, 1);
2779 * Modify SYMBOL so it only includes characters permissible in symbols.
2782 sanitize_symbol (char *symbol)
2784 int i, len = strlen (symbol);
2786 for (i = 0; i < len; ++i)
2787 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2792 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2794 char *name1, *name2, *cached;
2795 int i, j, len, count;
2797 name1 = mono_method_full_name (method, TRUE);
2798 len = strlen (name1);
2799 name2 = malloc (strlen (prefix) + len + 16);
2800 memcpy (name2, prefix, strlen (prefix));
2801 j = strlen (prefix);
2802 for (i = 0; i < len; ++i) {
2803 if (isalnum (name1 [i])) {
2804 name2 [j ++] = name1 [i];
2805 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2807 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2810 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2819 while (g_hash_table_lookup (cache, name2)) {
2820 sprintf (name2 + j, "_%d", count);
2824 cached = g_strdup (name2);
2825 g_hash_table_insert (cache, cached, cached);
2831 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2836 char *debug_sym = NULL;
2838 int func_alignment = AOT_FUNC_ALIGNMENT;
2839 MonoMethodHeader *header;
2841 method = cfg->orig_method;
2842 code = cfg->native_code;
2843 header = mono_method_get_header (method);
2845 method_index = get_method_index (acfg, method);
2847 /* Make the labels local */
2848 sprintf (symbol, "%s", cfg->asm_symbol);
2850 emit_section_change (acfg, ".text", 0);
2851 emit_alignment (acfg, func_alignment);
2852 emit_label (acfg, symbol);
2854 if (acfg->aot_opts.write_symbols) {
2856 * Write a C style symbol for every method, this has two uses:
2857 * - it works on platforms where the dwarf debugging info is not
2859 * - it allows the setting of breakpoints of aot-ed methods.
2861 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2863 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2864 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2865 emit_label (acfg, debug_sym);
2868 if (cfg->verbose_level > 0)
2869 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2871 acfg->stats.code_size += cfg->code_len;
2873 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2875 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2879 if (acfg->aot_opts.write_symbols) {
2880 emit_symbol_size (acfg, debug_sym, ".");
2884 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2885 emit_label (acfg, symbol);
2891 * Encode PATCH_INFO into its disk representation.
2894 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2898 switch (patch_info->type) {
2899 case MONO_PATCH_INFO_NONE:
2901 case MONO_PATCH_INFO_IMAGE:
2902 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2904 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2906 case MONO_PATCH_INFO_METHOD_REL:
2907 encode_value ((gint)patch_info->data.offset, p, &p);
2909 case MONO_PATCH_INFO_SWITCH: {
2910 gpointer *table = (gpointer *)patch_info->data.table->table;
2913 encode_value (patch_info->data.table->table_size, p, &p);
2914 for (k = 0; k < patch_info->data.table->table_size; k++)
2915 encode_value ((int)(gssize)table [k], p, &p);
2918 case MONO_PATCH_INFO_METHODCONST:
2919 case MONO_PATCH_INFO_METHOD:
2920 case MONO_PATCH_INFO_METHOD_JUMP:
2921 case MONO_PATCH_INFO_ICALL_ADDR:
2922 case MONO_PATCH_INFO_METHOD_RGCTX:
2923 encode_method_ref (acfg, patch_info->data.method, p, &p);
2925 case MONO_PATCH_INFO_INTERNAL_METHOD:
2926 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2927 guint32 len = strlen (patch_info->data.name);
2929 encode_value (len, p, &p);
2931 memcpy (p, patch_info->data.name, len);
2936 case MONO_PATCH_INFO_LDSTR: {
2937 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2938 guint32 token = patch_info->data.token->token;
2939 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2940 encode_value (image_index, p, &p);
2941 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2944 case MONO_PATCH_INFO_RVA:
2945 case MONO_PATCH_INFO_DECLSEC:
2946 case MONO_PATCH_INFO_LDTOKEN:
2947 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2948 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2949 encode_value (patch_info->data.token->token, p, &p);
2950 encode_value (patch_info->data.token->has_context, p, &p);
2951 if (patch_info->data.token->has_context)
2952 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2954 case MONO_PATCH_INFO_EXC_NAME: {
2955 MonoClass *ex_class;
2958 mono_class_from_name (mono_defaults.exception_class->image,
2959 "System", patch_info->data.target);
2960 g_assert (ex_class);
2961 encode_klass_ref (acfg, ex_class, p, &p);
2964 case MONO_PATCH_INFO_R4:
2965 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2967 case MONO_PATCH_INFO_R8:
2968 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
2969 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
2971 case MONO_PATCH_INFO_VTABLE:
2972 case MONO_PATCH_INFO_CLASS:
2973 case MONO_PATCH_INFO_IID:
2974 case MONO_PATCH_INFO_ADJUSTED_IID:
2975 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2977 case MONO_PATCH_INFO_CLASS_INIT:
2978 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2979 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2981 case MONO_PATCH_INFO_FIELD:
2982 case MONO_PATCH_INFO_SFLDA:
2983 encode_field_info (acfg, patch_info->data.field, p, &p);
2985 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2987 case MONO_PATCH_INFO_RGCTX_FETCH: {
2988 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2990 encode_method_ref (acfg, entry->method, p, &p);
2991 encode_value (entry->in_mrgctx, p, &p);
2992 encode_value (entry->info_type, p, &p);
2993 encode_value (entry->data->type, p, &p);
2994 encode_patch (acfg, entry->data, p, &p);
2997 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2998 case MONO_PATCH_INFO_MONITOR_ENTER:
2999 case MONO_PATCH_INFO_MONITOR_EXIT:
3000 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3002 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3003 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3004 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3007 g_warning ("unable to handle jump info %d", patch_info->type);
3008 g_assert_not_reached ();
3015 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3018 guint32 pindex, offset;
3019 MonoJumpInfo *patch_info;
3021 encode_value (n_patches, p, &p);
3023 for (pindex = 0; pindex < patches->len; ++pindex) {
3024 patch_info = g_ptr_array_index (patches, pindex);
3026 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3030 offset = get_got_offset (acfg, patch_info);
3031 encode_value (offset, p, &p);
3038 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3042 int pindex, buf_size, n_patches;
3045 MonoJumpInfo *patch_info;
3046 MonoMethodHeader *header;
3047 guint32 method_index;
3049 guint32 first_got_offset;
3051 method = cfg->orig_method;
3052 code = cfg->native_code;
3053 header = mono_method_get_header (method);
3055 method_index = get_method_index (acfg, method);
3057 /* Sort relocations */
3058 patches = g_ptr_array_new ();
3059 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3060 g_ptr_array_add (patches, patch_info);
3061 g_ptr_array_sort (patches, compare_patches);
3063 first_got_offset = acfg->cfgs [method_index]->got_offset;
3065 /**********************/
3066 /* Encode method info */
3067 /**********************/
3069 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3070 p = buf = g_malloc (buf_size);
3072 if (mono_class_get_cctor (method->klass))
3073 encode_klass_ref (acfg, method->klass, p, &p);
3075 /* Not needed when loading the method */
3076 encode_value (0, p, &p);
3079 if (cfg->opt & MONO_OPT_SHARED) {
3080 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3081 for (l = cfg->ldstr_list; l; l = l->next) {
3082 encode_value ((long)l->data, p, &p);
3086 /* Used only in shared mode */
3087 g_assert (!cfg->ldstr_list);
3090 for (pindex = 0; pindex < patches->len; ++pindex) {
3091 patch_info = g_ptr_array_index (patches, pindex);
3093 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3094 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3095 patch_info->type = MONO_PATCH_INFO_NONE;
3100 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3101 /* Stored in a GOT slot initialized at module load time */
3102 patch_info->type = MONO_PATCH_INFO_NONE;
3106 if (is_plt_patch (patch_info)) {
3107 /* Calls are made through the PLT */
3108 patch_info->type = MONO_PATCH_INFO_NONE;
3116 g_assert (cfg->has_got_slots);
3118 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3120 acfg->stats.info_size += p - buf;
3122 g_assert (p - buf < buf_size);
3124 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3129 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3131 guint32 cache_index;
3134 /* Reuse the unwind module to canonize and store unwind info entries */
3135 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3137 /* Use +/- 1 to distinguish 0s from missing entries */
3138 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3146 * It would be easier to use assembler symbols, but the caller needs an
3149 offset = acfg->unwind_info_offset;
3150 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3151 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3154 encode_value (encoded_len, p, &p);
3156 acfg->unwind_info_offset += encoded_len + (p - buf);
3162 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3165 int i, k, buf_size, method_index;
3166 guint32 debug_info_size;
3168 MonoMethodHeader *header;
3169 guint8 *p, *buf, *debug_info;
3170 MonoJitInfo *jinfo = cfg->jit_info;
3172 gboolean use_unwind_ops = FALSE;
3173 MonoSeqPointInfo *seq_points;
3175 method = cfg->orig_method;
3176 code = cfg->native_code;
3177 header = mono_method_get_header (method);
3179 method_index = get_method_index (acfg, method);
3181 if (!acfg->aot_opts.nodebug) {
3182 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3185 debug_info_size = 0;
3188 seq_points = cfg->seq_point_info;
3190 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3191 p = buf = g_malloc (buf_size);
3193 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3194 use_unwind_ops = cfg->unwind_ops != NULL;
3197 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);
3199 encode_value (flags, p, &p);
3201 if (use_unwind_ops) {
3202 guint32 encoded_len;
3206 * This is a duplicate of the data in the .debug_frame section, but that
3207 * section cannot be accessed using the dl interface.
3209 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3210 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3213 encode_value (jinfo->used_regs, p, &p);
3216 /* Exception table */
3217 if (jinfo->num_clauses)
3218 encode_value (jinfo->num_clauses, p, &p);
3220 for (k = 0; k < jinfo->num_clauses; ++k) {
3221 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3223 encode_value (ei->flags, p, &p);
3224 encode_value (ei->exvar_offset, p, &p);
3226 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3227 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3229 if (ei->data.catch_class) {
3230 encode_value (1, p, &p);
3231 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3233 encode_value (0, p, &p);
3237 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3238 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3239 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3242 if (jinfo->has_generic_jit_info) {
3243 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3245 encode_value (gi->has_this ? 1 : 0, p, &p);
3246 encode_value (gi->this_reg, p, &p);
3247 encode_value (gi->this_offset, p, &p);
3250 * Need to encode jinfo->method too, since it is not equal to 'method'
3251 * when using generic sharing.
3253 encode_method_ref (acfg, jinfo->method, p, &p);
3257 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3259 encode_value (seq_points->len, p, &p);
3260 last_il_offset = last_native_offset = 0;
3261 for (i = 0; i < seq_points->len; ++i) {
3262 SeqPoint *sp = &seq_points->seq_points [i];
3263 il_offset = sp->il_offset;
3264 native_offset = sp->native_offset;
3265 encode_value (il_offset - last_il_offset, p, &p);
3266 encode_value (native_offset - last_native_offset, p, &p);
3267 last_il_offset = il_offset;
3268 last_native_offset = native_offset;
3270 encode_value (sp->next_len, p, &p);
3271 for (j = 0; j < sp->next_len; ++j)
3272 encode_value (sp->next [j], p, &p);
3277 g_assert (debug_info_size < buf_size);
3279 encode_value (debug_info_size, p, &p);
3280 if (debug_info_size) {
3281 memcpy (p, debug_info, debug_info_size);
3282 p += debug_info_size;
3283 g_free (debug_info);
3286 acfg->stats.ex_info_size += p - buf;
3288 g_assert (p - buf < buf_size);
3291 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3296 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3298 MonoClass *klass = mono_class_get (acfg->image, token);
3300 int i, buf_size, res;
3301 gboolean no_special_static, cant_encode;
3302 gpointer iter = NULL;
3304 buf_size = 10240 + (klass->vtable_size * 16);
3305 p = buf = g_malloc (buf_size);
3309 mono_class_init (klass);
3311 mono_class_get_nested_types (klass, &iter);
3312 g_assert (klass->nested_classes_inited);
3314 mono_class_setup_vtable (klass);
3317 * Emit all the information which is required for creating vtables so
3318 * the runtime does not need to create the MonoMethod structures which
3319 * take up a lot of space.
3322 no_special_static = !mono_class_has_special_static_fields (klass);
3324 /* Check whenever we have enough info to encode the vtable */
3325 cant_encode = FALSE;
3326 for (i = 0; i < klass->vtable_size; ++i) {
3327 MonoMethod *cm = klass->vtable [i];
3329 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3333 if (klass->generic_container || cant_encode) {
3334 encode_value (-1, p, &p);
3336 encode_value (klass->vtable_size, p, &p);
3337 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);
3338 if (klass->has_cctor)
3339 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3340 if (klass->has_finalize)
3341 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3343 encode_value (klass->instance_size, p, &p);
3344 encode_value (mono_class_data_size (klass), p, &p);
3345 encode_value (klass->packing_size, p, &p);
3346 encode_value (klass->min_align, p, &p);
3348 for (i = 0; i < klass->vtable_size; ++i) {
3349 MonoMethod *cm = klass->vtable [i];
3352 encode_method_ref (acfg, cm, p, &p);
3354 encode_value (0, p, &p);
3358 acfg->stats.class_info_size += p - buf;
3360 g_assert (p - buf < buf_size);
3361 res = add_to_blob (acfg, buf, p - buf);
3368 * Calls made from AOTed code are routed through a table of jumps similar to the
3369 * ELF PLT (Program Linkage Table). The differences are the following:
3370 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3371 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3372 * jumps. This means the jumps need to be patched when the address of the callee is
3373 * known. Initially the PLT entries jump to code which transfers control to the
3374 * AOT runtime through the first PLT entry.
3377 emit_plt (MonoAotCompile *acfg)
3383 cache = g_hash_table_new (g_str_hash, g_str_equal);
3386 sprintf (symbol, "plt");
3388 emit_section_change (acfg, ".text", 0);
3389 emit_global (acfg, symbol, TRUE);
3391 /* This section will be made read-write by the AOT loader */
3392 emit_alignment (acfg, mono_pagesize ());
3394 emit_alignment (acfg, 16);
3396 emit_label (acfg, symbol);
3397 emit_label (acfg, acfg->plt_symbol);
3399 for (i = 0; i < acfg->plt_offset; ++i) {
3401 char *debug_sym = NULL;
3404 sprintf (label, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, i);
3408 * If the target is directly callable, alias the plt symbol to point to
3410 * FIXME: Use this to simplify emit_and_reloc_code ().
3411 * FIXME: Avoid the got slot.
3412 * FIXME: Add support to the binary writer.
3414 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3415 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3416 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3417 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3422 emit_label (acfg, label);
3424 if (acfg->aot_opts.write_symbols) {
3425 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3429 case MONO_PATCH_INFO_METHOD:
3430 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3432 case MONO_PATCH_INFO_INTERNAL_METHOD:
3433 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3435 case MONO_PATCH_INFO_CLASS_INIT:
3436 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3437 sanitize_symbol (debug_sym);
3439 case MONO_PATCH_INFO_RGCTX_FETCH:
3440 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3442 case MONO_PATCH_INFO_ICALL_ADDR: {
3443 char *s = get_debug_sym (ji->data.method, "", cache);
3445 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3449 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3450 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3452 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3453 debug_sym = g_strdup_printf ("plt__generic_class_init");
3460 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3461 emit_label (acfg, debug_sym);
3467 * The first plt entry is used to transfer code to the AOT loader.
3469 arch_emit_plt_entry (acfg, i);
3472 emit_symbol_size (acfg, debug_sym, ".");
3477 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3479 sprintf (symbol, "plt_end");
3480 emit_global (acfg, symbol, TRUE);
3481 emit_label (acfg, symbol);
3483 g_hash_table_destroy (cache);
3486 static G_GNUC_UNUSED void
3487 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3488 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3490 char start_symbol [256];
3492 guint32 buf_size, info_offset;
3493 MonoJumpInfo *patch_info;
3499 sprintf (start_symbol, "%s", name);
3501 emit_section_change (acfg, ".text", 0);
3502 emit_global (acfg, start_symbol, TRUE);
3503 emit_alignment (acfg, 16);
3504 emit_label (acfg, start_symbol);
3506 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3507 emit_label (acfg, symbol);
3510 * The code should access everything through the GOT, so we pass
3513 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3515 emit_symbol_size (acfg, start_symbol, ".");
3519 /* Sort relocations */
3520 patches = g_ptr_array_new ();
3521 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3522 if (patch_info->type != MONO_PATCH_INFO_NONE)
3523 g_ptr_array_add (patches, patch_info);
3524 g_ptr_array_sort (patches, compare_patches);
3526 buf_size = patches->len * 128 + 128;
3527 buf = g_malloc (buf_size);
3530 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3531 g_assert (p - buf < buf_size);
3533 sprintf (symbol, "%s_p", name);
3535 info_offset = add_to_blob (acfg, buf, p - buf);
3537 emit_section_change (acfg, ".text", 0);
3538 emit_global (acfg, symbol, FALSE);
3539 emit_label (acfg, symbol);
3541 emit_int32 (acfg, info_offset);
3543 /* Emit debug info */
3547 sprintf (symbol, "%s", name);
3548 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3551 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3556 emit_trampolines (MonoAotCompile *acfg)
3559 int i, tramp_got_offset;
3560 MonoAotTrampoline ntype;
3561 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3569 if (!acfg->aot_opts.full_aot)
3572 g_assert (acfg->image->assembly);
3574 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3575 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3576 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3578 * Emit the generic trampolines.
3580 * We could save some code by treating the generic trampolines as a wrapper
3581 * method, but that approach has its own complexities, so we choose the simpler
3584 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3585 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3587 /* Emit trampoline code */
3589 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3591 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3594 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3595 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3596 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3597 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3598 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3599 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3600 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3603 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3604 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3606 /* Emit the exception related code pieces */
3607 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3608 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3609 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3610 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3611 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3612 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3613 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3614 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3615 #ifdef MONO_ARCH_HAVE_THROW_EXCEPTION_BY_NAME
3616 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3617 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3619 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3620 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3622 #if defined(TARGET_AMD64)
3623 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3624 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3627 for (i = 0; i < 128; ++i) {
3630 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3631 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3632 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3633 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3635 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3636 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3637 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3638 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3644 /* delegate_invoke_impl trampolines */
3645 l = mono_arch_get_delegate_invoke_impls ();
3647 MonoAotTrampInfo *info = l->data;
3649 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3654 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3656 /* Emit trampolines which are numerous */
3659 * These include the following:
3660 * - specific trampolines
3661 * - static rgctx invoke trampolines
3663 * These trampolines have the same code, they are parameterized by GOT
3665 * They are defined in this file, in the arch_... routines instead of
3666 * in tramp-<ARCH>.c, since it is easier to do it this way.
3670 * When running in aot-only mode, we can't create specific trampolines at
3671 * runtime, so we create a few, and save them in the AOT file.
3672 * Normal trampolines embed their argument as a literal inside the
3673 * trampoline code, we can't do that here, so instead we embed an offset
3674 * which needs to be added to the trampoline address to get the address of
3675 * the GOT slot which contains the argument value.
3676 * The generated trampolines jump to the generic trampolines using another
3677 * GOT slot, which will be setup by the AOT loader to point to the
3678 * generic trampoline code of the given type.
3682 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3686 emit_section_change (acfg, ".text", 0);
3688 tramp_got_offset = acfg->got_offset;
3690 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3692 case MONO_AOT_TRAMP_SPECIFIC:
3693 sprintf (symbol, "specific_trampolines");
3695 case MONO_AOT_TRAMP_STATIC_RGCTX:
3696 sprintf (symbol, "static_rgctx_trampolines");
3698 case MONO_AOT_TRAMP_IMT_THUNK:
3699 sprintf (symbol, "imt_thunks");
3702 g_assert_not_reached ();
3705 emit_global (acfg, symbol, TRUE);
3706 emit_alignment (acfg, 16);
3707 emit_label (acfg, symbol);
3709 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3711 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3715 case MONO_AOT_TRAMP_SPECIFIC:
3716 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3717 tramp_got_offset += 2;
3719 case MONO_AOT_TRAMP_STATIC_RGCTX:
3720 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3721 tramp_got_offset += 2;
3723 case MONO_AOT_TRAMP_IMT_THUNK:
3724 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3725 tramp_got_offset += 1;
3728 g_assert_not_reached ();
3731 if (!acfg->trampoline_size [ntype]) {
3732 g_assert (tramp_size);
3733 acfg->trampoline_size [ntype] = tramp_size;
3738 /* Reserve some entries at the end of the GOT for our use */
3739 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3742 acfg->got_offset += acfg->num_trampoline_got_entries;
3746 str_begins_with (const char *str1, const char *str2)
3748 int len = strlen (str2);
3749 return strncmp (str1, str2, len) == 0;
3753 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3755 gchar **args, **ptr;
3757 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3758 for (ptr = args; ptr && *ptr; ptr ++) {
3759 const char *arg = *ptr;
3761 if (str_begins_with (arg, "outfile=")) {
3762 opts->outfile = g_strdup (arg + strlen ("outfile="));
3763 } else if (str_begins_with (arg, "save-temps")) {
3764 opts->save_temps = TRUE;
3765 } else if (str_begins_with (arg, "keep-temps")) {
3766 opts->save_temps = TRUE;
3767 } else if (str_begins_with (arg, "write-symbols")) {
3768 opts->write_symbols = TRUE;
3769 } else if (str_begins_with (arg, "metadata-only")) {
3770 opts->metadata_only = TRUE;
3771 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3772 opts->bind_to_runtime_version = TRUE;
3773 } else if (str_begins_with (arg, "full")) {
3774 opts->full_aot = TRUE;
3775 } else if (str_begins_with (arg, "threads=")) {
3776 opts->nthreads = atoi (arg + strlen ("threads="));
3777 } else if (str_begins_with (arg, "static")) {
3778 opts->static_link = TRUE;
3779 opts->no_dlsym = TRUE;
3780 } else if (str_begins_with (arg, "asmonly")) {
3781 opts->asm_only = TRUE;
3782 } else if (str_begins_with (arg, "asmwriter")) {
3783 opts->asm_writer = TRUE;
3784 } else if (str_begins_with (arg, "nodebug")) {
3785 opts->nodebug = TRUE;
3786 } else if (str_begins_with (arg, "ntrampolines=")) {
3787 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3788 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
3789 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
3790 } else if (str_begins_with (arg, "nimt-trampolines=")) {
3791 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
3792 } else if (str_begins_with (arg, "autoreg")) {
3793 opts->autoreg = TRUE;
3794 } else if (str_begins_with (arg, "tool-prefix=")) {
3795 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3796 } else if (str_begins_with (arg, "soft-debug")) {
3797 opts->soft_debug = TRUE;
3798 } else if (str_begins_with (arg, "print-skipped")) {
3799 opts->print_skipped_methods = TRUE;
3800 } else if (str_begins_with (arg, "stats")) {
3803 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3812 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3814 MonoMethod *method = (MonoMethod*)key;
3815 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3816 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3817 MonoAotCompile *acfg = user_data;
3819 new_ji->image = ji->image;
3820 new_ji->token = ji->token;
3821 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3825 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3827 if (klass->type_token)
3829 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3832 return can_encode_class (acfg, klass->element_class);
3837 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3839 switch (patch_info->type) {
3840 case MONO_PATCH_INFO_METHOD:
3841 case MONO_PATCH_INFO_METHODCONST: {
3842 MonoMethod *method = patch_info->data.method;
3844 if (method->wrapper_type) {
3845 switch (method->wrapper_type) {
3846 case MONO_WRAPPER_NONE:
3847 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3848 case MONO_WRAPPER_XDOMAIN_INVOKE:
3849 case MONO_WRAPPER_STFLD:
3850 case MONO_WRAPPER_LDFLD:
3851 case MONO_WRAPPER_LDFLDA:
3852 case MONO_WRAPPER_LDFLD_REMOTE:
3853 case MONO_WRAPPER_STFLD_REMOTE:
3854 case MONO_WRAPPER_STELEMREF:
3855 case MONO_WRAPPER_ISINST:
3856 case MONO_WRAPPER_PROXY_ISINST:
3857 case MONO_WRAPPER_ALLOC:
3858 case MONO_WRAPPER_REMOTING_INVOKE:
3859 case MONO_WRAPPER_UNKNOWN:
3860 case MONO_WRAPPER_WRITE_BARRIER:
3862 case MONO_WRAPPER_MANAGED_TO_MANAGED:
3863 if (!strcmp (method->name, "ElementAddr"))
3868 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3872 if (!method->token) {
3873 /* The method is part of a constructed type like Int[,].Set (). */
3874 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3875 if (method->klass->rank)
3883 case MONO_PATCH_INFO_VTABLE:
3884 case MONO_PATCH_INFO_CLASS_INIT:
3885 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3886 case MONO_PATCH_INFO_CLASS:
3887 case MONO_PATCH_INFO_IID:
3888 case MONO_PATCH_INFO_ADJUSTED_IID:
3889 if (!can_encode_class (acfg, patch_info->data.klass)) {
3890 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3894 case MONO_PATCH_INFO_RGCTX_FETCH: {
3895 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3897 if (!can_encode_patch (acfg, entry->data))
3909 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3914 * AOT compile a given method.
3915 * This function might be called by multiple threads, so it must be thread-safe.
3918 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3921 MonoJumpInfo *patch_info;
3924 MonoMethod *wrapped;
3926 if (acfg->aot_opts.metadata_only)
3929 mono_acfg_lock (acfg);
3930 index = get_method_index (acfg, method);
3931 mono_acfg_unlock (acfg);
3933 /* fixme: maybe we can also precompile wrapper methods */
3934 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3935 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3936 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3937 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3941 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3944 wrapped = mono_marshal_method_from_wrapper (method);
3945 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3946 // FIXME: The wrapper should be generic too, but it is not
3949 InterlockedIncrement (&acfg->stats.mcount);
3952 if (method->is_generic || method->klass->generic_container) {
3953 InterlockedIncrement (&acfg->stats.genericcount);
3958 //acfg->aot_opts.print_skipped_methods = TRUE;
3961 * Since these methods are the only ones which are compiled with
3962 * AOT support, and they are not used by runtime startup/shutdown code,
3963 * the runtime will not see AOT methods during AOT compilation,so it
3964 * does not need to support them by creating a fake GOT etc.
3966 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3967 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3968 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3969 InterlockedIncrement (&acfg->stats.genericcount);
3972 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3973 /* Let the exception happen at runtime */
3977 if (cfg->disable_aot) {
3978 if (acfg->aot_opts.print_skipped_methods)
3979 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3980 InterlockedIncrement (&acfg->stats.ocount);
3981 mono_destroy_compile (cfg);
3985 /* Nullify patches which need no aot processing */
3986 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3987 switch (patch_info->type) {
3988 case MONO_PATCH_INFO_LABEL:
3989 case MONO_PATCH_INFO_BB:
3990 patch_info->type = MONO_PATCH_INFO_NONE;
3997 /* Collect method->token associations from the cfg */
3998 mono_acfg_lock (acfg);
3999 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4000 mono_acfg_unlock (acfg);
4003 * Check for absolute addresses.
4006 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4007 switch (patch_info->type) {
4008 case MONO_PATCH_INFO_ABS:
4009 /* unable to handle this */
4018 if (acfg->aot_opts.print_skipped_methods)
4019 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4020 InterlockedIncrement (&acfg->stats.abscount);
4021 mono_destroy_compile (cfg);
4025 /* Lock for the rest of the code */
4026 mono_acfg_lock (acfg);
4029 * Check for methods/klasses we can't encode.
4032 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4033 if (!can_encode_patch (acfg, patch_info))
4038 if (acfg->aot_opts.print_skipped_methods)
4039 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4040 acfg->stats.ocount++;
4041 mono_destroy_compile (cfg);
4042 mono_acfg_unlock (acfg);
4046 /* Adds generic instances referenced by this method */
4048 * The depth is used to avoid infinite loops when generic virtual recursion is
4051 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4053 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4054 switch (patch_info->type) {
4055 case MONO_PATCH_INFO_METHOD: {
4056 MonoMethod *m = patch_info->data.method;
4057 if (m->is_inflated) {
4058 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4059 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4060 !method_has_type_vars (m)) {
4061 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4062 if (acfg->aot_opts.full_aot)
4063 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4065 add_extra_method_with_depth (acfg, m, depth + 1);
4068 add_generic_class (acfg, m->klass);
4070 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4071 add_extra_method_with_depth (acfg, m, depth + 1);
4074 case MONO_PATCH_INFO_VTABLE: {
4075 MonoClass *klass = patch_info->data.klass;
4077 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4078 add_generic_class (acfg, klass);
4087 /* Determine whenever the method has GOT slots */
4088 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4089 switch (patch_info->type) {
4090 case MONO_PATCH_INFO_GOT_OFFSET:
4091 case MONO_PATCH_INFO_NONE:
4093 case MONO_PATCH_INFO_IMAGE:
4094 /* The assembly is stored in GOT slot 0 */
4095 if (patch_info->data.image != acfg->image)
4096 cfg->has_got_slots = TRUE;
4099 if (!is_plt_patch (patch_info))
4100 cfg->has_got_slots = TRUE;
4105 if (!cfg->has_got_slots)
4106 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4109 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4111 /* Make a copy of the patch info which is in the mempool */
4113 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4115 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4116 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4119 patches = new_patch_info;
4121 patches_end->next = new_patch_info;
4122 patches_end = new_patch_info;
4124 cfg->patch_info = patches;
4126 /* Make a copy of the unwind info */
4128 GSList *l, *unwind_ops;
4132 for (l = cfg->unwind_ops; l; l = l->next) {
4133 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4134 memcpy (op, l->data, sizeof (MonoUnwindOp));
4135 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4137 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4139 /* Make a copy of the argument/local info */
4141 MonoInst **args, **locals;
4142 MonoMethodSignature *sig;
4143 MonoMethodHeader *header;
4146 sig = mono_method_signature (method);
4147 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4148 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4149 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4150 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4154 header = mono_method_get_header (method);
4155 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4156 for (i = 0; i < header->num_locals; ++i) {
4157 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4158 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4160 cfg->locals = locals;
4163 /* Free some fields used by cfg to conserve memory */
4164 mono_mempool_destroy (cfg->mempool);
4165 cfg->mempool = NULL;
4166 g_free (cfg->varinfo);
4167 cfg->varinfo = NULL;
4171 mono_regstate_free (cfg->rs);
4175 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4177 while (index >= acfg->cfgs_size) {
4178 MonoCompile **new_cfgs;
4181 new_size = acfg->cfgs_size * 2;
4182 new_cfgs = g_new0 (MonoCompile*, new_size);
4183 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4184 g_free (acfg->cfgs);
4185 acfg->cfgs = new_cfgs;
4186 acfg->cfgs_size = new_size;
4188 acfg->cfgs [index] = cfg;
4190 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4193 if (cfg->orig_method->wrapper_type)
4194 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4197 mono_acfg_unlock (acfg);
4199 InterlockedIncrement (&acfg->stats.ccount);
4203 compile_thread_main (gpointer *user_data)
4205 MonoDomain *domain = user_data [0];
4206 MonoAotCompile *acfg = user_data [1];
4207 GPtrArray *methods = user_data [2];
4210 mono_thread_attach (domain);
4212 for (i = 0; i < methods->len; ++i)
4213 compile_method (acfg, g_ptr_array_index (methods, i));
4217 load_profile_files (MonoAotCompile *acfg)
4221 int file_index, res, method_index, i;
4228 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4230 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4235 infile = fopen (tmp, "r");
4238 printf ("Using profile data file '%s'\n", tmp);
4243 res = fscanf (infile, "%32s\n", ver);
4244 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4245 printf ("Profile file has wrong version or invalid.\n");
4252 MonoMethodDesc *desc;
4255 if (fgets (name, 1023, infile) == NULL)
4258 /* Kill the newline */
4259 if (strlen (name) > 0)
4260 name [strlen (name) - 1] = '\0';
4262 desc = mono_method_desc_new (name, TRUE);
4264 method = mono_method_desc_search_in_image (desc, acfg->image);
4266 if (method && mono_method_get_token (method)) {
4267 token = mono_method_get_token (method);
4268 method_index = mono_metadata_token_index (token) - 1;
4270 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4271 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4274 //printf ("No method found matching '%s'.\n", name);
4280 /* Add missing methods */
4282 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4283 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4284 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4286 unordered = g_list_reverse (unordered);
4287 if (acfg->method_order)
4288 g_list_last (acfg->method_order)->next = unordered;
4290 acfg->method_order = unordered;
4293 /* Used by the LLVM backend */
4295 mono_aot_get_got_offset (MonoJumpInfo *ji)
4297 return get_got_offset (llvm_acfg, ji);
4301 mono_aot_get_method_name (MonoCompile *cfg)
4303 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4305 return g_strdup_printf ("m_%x", method_index);
4309 mono_aot_get_method_debug_name (MonoCompile *cfg)
4311 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4315 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4317 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4321 ji->data.target = data;
4323 if (!can_encode_patch (llvm_acfg, ji))
4326 offset = get_plt_offset (llvm_acfg, ji);
4328 return g_strdup_printf ("%sp_%d", llvm_acfg->temp_prefix, offset);
4332 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4336 mono_acfg_lock (llvm_acfg);
4337 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4338 mono_acfg_unlock (llvm_acfg);
4348 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4352 emit_llvm_file (MonoAotCompile *acfg)
4354 char *command, *opts;
4356 MonoJumpInfo *patch_info;
4357 char *llc_target_args;
4360 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4364 /* Compute the final size of the got */
4365 for (i = 0; i < acfg->nmethods; ++i) {
4366 if (acfg->cfgs [i]) {
4367 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4368 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4369 if (!is_plt_patch (patch_info))
4370 get_got_offset (acfg, patch_info);
4372 get_plt_offset (acfg, patch_info);
4378 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4380 if (acfg->aot_opts.full_aot) {
4384 * Need to add the got entries used by the trampolines.
4385 * This is only a conservative approximation.
4387 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4388 /* For the generic + rgctx trampolines */
4389 acfg->final_got_size += 200;
4390 /* For the specific trampolines */
4391 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4392 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4397 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4400 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4401 * a lot of time, and doesn't seem to save much space.
4402 * The following optimizations cannot be enabled:
4404 * The opt list below was produced by taking the output of:
4405 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4406 * then removing tailcallelim + the global opts, and adding a second gvn.
4408 opts = g_strdup ("-instcombine -simplifycfg");
4409 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -jump-threading -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 -jump-threading -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
4411 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4412 printf ("Executing opt: %s\n", command);
4413 if (system (command) != 0) {
4419 llc_target_args = g_strdup (LLC_TARGET_ARGS);
4421 command = g_strdup_printf ("llc %s -f -relocation-model=pic -unwind-tables -o %s temp.opt.bc", llc_target_args, acfg->tmpfname);
4422 g_free (llc_target_args);
4424 printf ("Executing llc: %s\n", command);
4426 if (system (command) != 0) {
4433 emit_code (MonoAotCompile *acfg)
4437 char end_symbol [256];
4440 #if defined(TARGET_POWERPC64)
4441 sprintf (symbol, ".Lgot_addr");
4442 emit_section_change (acfg, ".text", 0);
4443 emit_alignment (acfg, 8);
4444 emit_label (acfg, symbol);
4445 emit_pointer (acfg, acfg->got_symbol);
4449 * This global symbol is used to compute the address of each method using the
4450 * code_offsets array. It is also used to compute the memory ranges occupied by
4451 * AOT code, so it must be equal to the address of the first emitted method.
4453 sprintf (symbol, "methods");
4454 emit_section_change (acfg, ".text", 0);
4455 emit_global (acfg, symbol, TRUE);
4456 emit_alignment (acfg, 8);
4458 for (i = 0; i < acfg->nmethods; ++i) {
4459 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4460 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4464 if (i == acfg->nmethods)
4465 /* No LLVM compiled methods */
4466 emit_label (acfg, symbol);
4468 emit_label (acfg, symbol);
4472 * Emit some padding so the local symbol for the first method doesn't have the
4473 * same address as 'methods'.
4475 emit_zero_bytes (acfg, 16);
4477 for (l = acfg->method_order; l != NULL; l = l->next) {
4481 i = GPOINTER_TO_UINT (l->data);
4483 cfg = acfg->cfgs [i];
4488 method = cfg->orig_method;
4490 /* Emit unbox trampoline */
4491 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4492 char call_target [256];
4494 if (!method->wrapper_type && !method->is_inflated) {
4495 g_assert (method->token);
4496 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4498 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4501 emit_section_change (acfg, ".text", 0);
4502 emit_global (acfg, symbol, TRUE);
4503 emit_label (acfg, symbol);
4505 sprintf (call_target, "%s", cfg->asm_symbol);
4507 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4510 if (cfg->compile_llvm)
4511 acfg->stats.llvm_count ++;
4513 emit_method_code (acfg, cfg);
4516 sprintf (symbol, "methods_end");
4517 emit_section_change (acfg, ".text", 0);
4518 emit_global (acfg, symbol, FALSE);
4519 emit_alignment (acfg, 8);
4520 emit_label (acfg, symbol);
4522 sprintf (symbol, "code_offsets");
4523 emit_section_change (acfg, ".text", 1);
4524 emit_global (acfg, symbol, FALSE);
4525 emit_alignment (acfg, 8);
4526 emit_label (acfg, symbol);
4528 acfg->stats.offsets_size += acfg->nmethods * 4;
4530 sprintf (end_symbol, "methods");
4531 for (i = 0; i < acfg->nmethods; ++i) {
4532 if (acfg->cfgs [i]) {
4533 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4535 emit_int32 (acfg, 0xffffffff);
4542 emit_info (MonoAotCompile *acfg)
4549 offsets = g_new0 (gint32, acfg->nmethods);
4551 for (l = acfg->method_order; l != NULL; l = l->next) {
4552 i = GPOINTER_TO_UINT (l->data);
4554 if (acfg->cfgs [i]) {
4555 emit_method_info (acfg, acfg->cfgs [i]);
4556 offsets [i] = acfg->cfgs [i]->method_info_offset;
4562 sprintf (symbol, "method_info_offsets");
4563 emit_section_change (acfg, ".text", 1);
4564 emit_global (acfg, symbol, FALSE);
4565 emit_alignment (acfg, 8);
4566 emit_label (acfg, symbol);
4568 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4573 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4575 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4576 #define mix(a,b,c) { \
4577 a -= c; a ^= rot(c, 4); c += b; \
4578 b -= a; b ^= rot(a, 6); a += c; \
4579 c -= b; c ^= rot(b, 8); b += a; \
4580 a -= c; a ^= rot(c,16); c += b; \
4581 b -= a; b ^= rot(a,19); a += c; \
4582 c -= b; c ^= rot(b, 4); b += a; \
4584 #define final(a,b,c) { \
4585 c ^= b; c -= rot(b,14); \
4586 a ^= c; a -= rot(c,11); \
4587 b ^= a; b -= rot(a,25); \
4588 c ^= b; c -= rot(b,16); \
4589 a ^= c; a -= rot(c,4); \
4590 b ^= a; b -= rot(a,14); \
4591 c ^= b; c -= rot(b,24); \
4595 mono_aot_type_hash (MonoType *t1)
4597 guint hash = t1->type;
4599 hash |= t1->byref << 6; /* do not collide with t1->type values */
4601 case MONO_TYPE_VALUETYPE:
4602 case MONO_TYPE_CLASS:
4603 case MONO_TYPE_SZARRAY:
4604 /* check if the distribution is good enough */
4605 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4607 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4608 case MONO_TYPE_ARRAY:
4609 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4610 case MONO_TYPE_GENERICINST:
4611 return ((hash << 5) - hash) ^ 0;
4617 * mono_aot_method_hash:
4619 * Return a hash code for methods which only depends on metadata.
4622 mono_aot_method_hash (MonoMethod *method)
4624 MonoMethodSignature *sig;
4628 guint32 *hashes_start, *hashes;
4631 /* Similar to the hash in mono_method_get_imt_slot () */
4633 sig = mono_method_signature (method);
4635 hashes_count = sig->param_count + 5;
4636 hashes_start = malloc (hashes_count * sizeof (guint32));
4637 hashes = hashes_start;
4639 /* Some wrappers are assigned to random classes */
4640 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4641 klass = method->klass;
4643 klass = mono_defaults.object_class;
4645 if (!method->wrapper_type) {
4646 char *full_name = mono_type_full_name (&klass->byval_arg);
4648 hashes [0] = mono_metadata_str_hash (full_name);
4652 hashes [0] = mono_metadata_str_hash (klass->name);
4653 hashes [1] = mono_metadata_str_hash (klass->name_space);
4655 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4656 /* The method name includes a stringified pointer */
4659 hashes [2] = mono_metadata_str_hash (method->name);
4660 hashes [3] = method->wrapper_type;
4661 hashes [4] = mono_aot_type_hash (sig->ret);
4662 for (i = 0; i < sig->param_count; i++) {
4663 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4666 /* Setup internal state */
4667 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4669 /* Handle most of the hashes */
4670 while (hashes_count > 3) {
4679 /* Handle the last 3 hashes (all the case statements fall through) */
4680 switch (hashes_count) {
4681 case 3 : c += hashes [2];
4682 case 2 : b += hashes [1];
4683 case 1 : a += hashes [0];
4685 case 0: /* nothing left to add */
4689 free (hashes_start);
4698 * mono_aot_wrapper_name:
4700 * Return a string which uniqely identifies the given wrapper method.
4703 mono_aot_wrapper_name (MonoMethod *method)
4705 char *name, *tmpsig, *klass_desc;
4707 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4709 switch (method->wrapper_type) {
4710 case MONO_WRAPPER_RUNTIME_INVOKE:
4711 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4712 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4714 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4717 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4718 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4719 g_free (klass_desc);
4729 * mono_aot_get_array_helper_from_wrapper;
4731 * Get the helper method in Array called by an array wrapper method.
4734 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4738 MonoGenericContext ctx;
4739 MonoType *args [16];
4740 char *mname, *iname, *s, *s2, *helper_name = NULL;
4742 prefix = "System.Collections.Generic";
4743 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4744 s2 = strstr (s, "`1.");
4750 //printf ("X: %s %s\n", iname, mname);
4752 if (!strcmp (iname, "IList"))
4753 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4755 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4756 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4758 g_free (helper_name);
4761 if (m->is_generic) {
4762 memset (&ctx, 0, sizeof (ctx));
4763 args [0] = &method->klass->element_class->byval_arg;
4764 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4765 m = mono_class_inflate_generic_method (m, &ctx);
4772 * mono_aot_tramp_info_create:
4774 * Create a MonoAotTrampInfo structure from the arguments.
4777 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4779 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4781 info->name = (char*)name;
4783 info->code_size = code_size;
4788 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4790 typedef struct HashEntry {
4791 guint32 key, value, index;
4792 struct HashEntry *next;
4796 * emit_extra_methods:
4798 * Emit methods which are not in the METHOD table, like wrappers.
4801 emit_extra_methods (MonoAotCompile *acfg)
4803 int i, table_size, buf_size;
4806 guint32 *info_offsets;
4809 HashEntry *entry, *new_entry;
4810 int nmethods, max_chain_length;
4813 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4815 /* Emit method info */
4817 for (i = 0; i < acfg->extra_methods->len; ++i) {
4818 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4819 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4826 p = buf = g_malloc (buf_size);
4831 if (method->wrapper_type) {
4833 * We encode some wrappers using their name, since encoding them
4834 * directly would be difficult. This also avoids creating the wrapper
4835 * methods at runtime, since they are not needed anyway.
4837 switch (method->wrapper_type) {
4838 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4839 case MONO_WRAPPER_SYNCHRONIZED:
4840 /* encode_method_ref () can handle these */
4842 case MONO_WRAPPER_RUNTIME_INVOKE:
4843 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4844 /* Direct wrapper, encode normally */
4848 name = mono_aot_wrapper_name (method);
4854 encode_value (1, p, &p);
4855 encode_value (method->wrapper_type, p, &p);
4856 strcpy ((char*)p, name);
4857 p += strlen (name ) + 1;
4860 encode_value (0, p, &p);
4861 encode_method_ref (acfg, method, p, &p);
4864 g_assert ((p - buf) < buf_size);
4866 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
4871 * Construct a chained hash table for mapping indexes in extra_method_info to
4874 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4875 table = g_ptr_array_sized_new (table_size);
4876 for (i = 0; i < table_size; ++i)
4877 g_ptr_array_add (table, NULL);
4878 chain_lengths = g_new0 (int, table_size);
4879 max_chain_length = 0;
4880 for (i = 0; i < acfg->extra_methods->len; ++i) {
4881 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4882 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4888 key = info_offsets [i];
4889 value = get_method_index (acfg, method);
4891 hash = mono_aot_method_hash (method) % table_size;
4893 chain_lengths [hash] ++;
4894 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4896 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
4897 new_entry->key = key;
4898 new_entry->value = value;
4900 entry = g_ptr_array_index (table, hash);
4901 if (entry == NULL) {
4902 new_entry->index = hash;
4903 g_ptr_array_index (table, hash) = new_entry;
4906 entry = entry->next;
4908 entry->next = new_entry;
4909 new_entry->index = table->len;
4910 g_ptr_array_add (table, new_entry);
4914 //printf ("MAX: %d\n", max_chain_length);
4916 /* Emit the table */
4917 sprintf (symbol, "extra_method_table");
4918 emit_section_change (acfg, ".text", 0);
4919 emit_global (acfg, symbol, FALSE);
4920 emit_alignment (acfg, 8);
4921 emit_label (acfg, symbol);
4923 emit_int32 (acfg, table_size);
4924 for (i = 0; i < table->len; ++i) {
4925 HashEntry *entry = g_ptr_array_index (table, i);
4927 if (entry == NULL) {
4928 emit_int32 (acfg, 0);
4929 emit_int32 (acfg, 0);
4930 emit_int32 (acfg, 0);
4932 //g_assert (entry->key > 0);
4933 emit_int32 (acfg, entry->key);
4934 emit_int32 (acfg, entry->value);
4936 emit_int32 (acfg, entry->next->index);
4938 emit_int32 (acfg, 0);
4943 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4944 * This is used by mono_aot_find_jit_info ().
4946 sprintf (symbol, "extra_method_info_offsets");
4947 emit_section_change (acfg, ".text", 0);
4948 emit_global (acfg, symbol, FALSE);
4949 emit_alignment (acfg, 8);
4950 emit_label (acfg, symbol);
4952 emit_int32 (acfg, acfg->extra_methods->len);
4953 for (i = 0; i < acfg->extra_methods->len; ++i) {
4954 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4956 emit_int32 (acfg, get_method_index (acfg, method));
4957 emit_int32 (acfg, info_offsets [i]);
4962 emit_exception_info (MonoAotCompile *acfg)
4968 offsets = g_new0 (gint32, acfg->nmethods);
4969 for (i = 0; i < acfg->nmethods; ++i) {
4970 if (acfg->cfgs [i]) {
4971 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4972 offsets [i] = acfg->cfgs [i]->ex_info_offset;
4978 sprintf (symbol, "ex_info_offsets");
4979 emit_section_change (acfg, ".text", 1);
4980 emit_global (acfg, symbol, FALSE);
4981 emit_alignment (acfg, 8);
4982 emit_label (acfg, symbol);
4984 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4989 emit_unwind_info (MonoAotCompile *acfg)
4995 * The unwind info contains a lot of duplicates so we emit each unique
4996 * entry once, and only store the offset from the start of the table in the
5000 sprintf (symbol, "unwind_info");
5001 emit_section_change (acfg, ".text", 1);
5002 emit_alignment (acfg, 8);
5003 emit_label (acfg, symbol);
5004 emit_global (acfg, symbol, FALSE);
5006 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5007 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5008 guint8 *unwind_info;
5009 guint32 unwind_info_len;
5013 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5016 encode_value (unwind_info_len, p, &p);
5017 emit_bytes (acfg, buf, p - buf);
5018 emit_bytes (acfg, unwind_info, unwind_info_len);
5020 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5025 emit_class_info (MonoAotCompile *acfg)
5031 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5032 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5033 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5035 sprintf (symbol, "class_info_offsets");
5036 emit_section_change (acfg, ".text", 1);
5037 emit_global (acfg, symbol, FALSE);
5038 emit_alignment (acfg, 8);
5039 emit_label (acfg, symbol);
5041 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5045 typedef struct ClassNameTableEntry {
5046 guint32 token, index;
5047 struct ClassNameTableEntry *next;
5048 } ClassNameTableEntry;
5051 emit_class_name_table (MonoAotCompile *acfg)
5054 guint32 token, hash;
5059 ClassNameTableEntry *entry, *new_entry;
5062 * Construct a chained hash table for mapping class names to typedef tokens.
5064 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5065 table = g_ptr_array_sized_new (table_size);
5066 for (i = 0; i < table_size; ++i)
5067 g_ptr_array_add (table, NULL);
5068 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5069 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5070 klass = mono_class_get (acfg->image, token);
5071 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5072 hash = mono_metadata_str_hash (full_name) % table_size;
5075 /* FIXME: Allocate from the mempool */
5076 new_entry = g_new0 (ClassNameTableEntry, 1);
5077 new_entry->token = token;
5079 entry = g_ptr_array_index (table, hash);
5080 if (entry == NULL) {
5081 new_entry->index = hash;
5082 g_ptr_array_index (table, hash) = new_entry;
5085 entry = entry->next;
5087 entry->next = new_entry;
5088 new_entry->index = table->len;
5089 g_ptr_array_add (table, new_entry);
5093 /* Emit the table */
5094 sprintf (symbol, "class_name_table");
5095 emit_section_change (acfg, ".text", 0);
5096 emit_global (acfg, symbol, FALSE);
5097 emit_alignment (acfg, 8);
5098 emit_label (acfg, symbol);
5100 /* FIXME: Optimize memory usage */
5101 g_assert (table_size < 65000);
5102 emit_int16 (acfg, table_size);
5103 g_assert (table->len < 65000);
5104 for (i = 0; i < table->len; ++i) {
5105 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5107 if (entry == NULL) {
5108 emit_int16 (acfg, 0);
5109 emit_int16 (acfg, 0);
5111 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5113 emit_int16 (acfg, entry->next->index);
5115 emit_int16 (acfg, 0);
5121 emit_image_table (MonoAotCompile *acfg)
5127 * The image table is small but referenced in a lot of places.
5128 * So we emit it at once, and reference its elements by an index.
5131 sprintf (symbol, "mono_image_table");
5132 emit_section_change (acfg, ".text", 1);
5133 emit_global (acfg, symbol, FALSE);
5134 emit_alignment (acfg, 8);
5135 emit_label (acfg, symbol);
5137 emit_int32 (acfg, acfg->image_table->len);
5138 for (i = 0; i < acfg->image_table->len; i++) {
5139 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5140 MonoAssemblyName *aname = &image->assembly->aname;
5142 /* FIXME: Support multi-module assemblies */
5143 g_assert (image->assembly->image == image);
5145 emit_string (acfg, image->assembly_name);
5146 emit_string (acfg, image->guid);
5147 emit_string (acfg, aname->culture ? aname->culture : "");
5148 emit_string (acfg, (const char*)aname->public_key_token);
5150 emit_alignment (acfg, 8);
5151 emit_int32 (acfg, aname->flags);
5152 emit_int32 (acfg, aname->major);
5153 emit_int32 (acfg, aname->minor);
5154 emit_int32 (acfg, aname->build);
5155 emit_int32 (acfg, aname->revision);
5160 emit_got_info (MonoAotCompile *acfg)
5163 int i, first_plt_got_patch, buf_size;
5165 guint32 *got_info_offsets;
5167 /* Add the patches needed by the PLT to the GOT */
5168 acfg->plt_got_offset_base = acfg->got_offset;
5169 first_plt_got_patch = acfg->got_patches->len;
5170 for (i = 1; i < acfg->plt_offset; ++i) {
5171 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
5173 g_ptr_array_add (acfg->got_patches, patch_info);
5176 acfg->got_offset += acfg->plt_offset;
5180 * - optimize offsets table.
5181 * - reduce number of exported symbols.
5182 * - emit info for a klass only once.
5183 * - determine when a method uses a GOT slot which is guaranteed to be already
5185 * - clean up and document the code.
5186 * - use String.Empty in class libs.
5189 /* Encode info required to decode shared GOT entries */
5190 buf_size = acfg->got_patches->len * 64;
5191 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5192 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5193 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5195 if (acfg->plt_offset)
5196 acfg->plt_got_info_offsets [0] = 0;
5197 for (i = 0; i < acfg->got_patches->len; ++i) {
5198 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5202 encode_value (ji->type, p, &p);
5203 encode_patch (acfg, ji, p, &p);
5205 g_assert (p - buf <= buf_size);
5206 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5208 if (i >= first_plt_got_patch)
5209 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5210 acfg->stats.got_info_size += p - buf;
5213 /* Emit got_info_offsets table */
5214 sprintf (symbol, "got_info_offsets");
5215 emit_section_change (acfg, ".text", 1);
5216 emit_global (acfg, symbol, FALSE);
5217 emit_alignment (acfg, 8);
5218 emit_label (acfg, symbol);
5220 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5221 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5225 emit_got (MonoAotCompile *acfg)
5230 /* Don't make GOT global so accesses to it don't need relocations */
5231 sprintf (symbol, "%s", acfg->got_symbol);
5232 emit_section_change (acfg, ".bss", 0);
5233 emit_alignment (acfg, 8);
5234 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5235 emit_label (acfg, symbol);
5236 if (acfg->got_offset > 0)
5237 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5239 sprintf (symbol, "got_end");
5240 emit_label (acfg, symbol);
5243 sprintf (symbol, "mono_aot_got_addr");
5244 emit_section_change (acfg, ".data", 0);
5245 emit_global (acfg, symbol, FALSE);
5246 emit_alignment (acfg, 8);
5247 emit_label (acfg, symbol);
5248 emit_pointer (acfg, acfg->got_symbol);
5251 typedef struct GlobalsTableEntry {
5252 guint32 value, index;
5253 struct GlobalsTableEntry *next;
5254 } GlobalsTableEntry;
5257 emit_globals_table (MonoAotCompile *acfg)
5263 GlobalsTableEntry *entry, *new_entry;
5266 * Construct a chained hash table for mapping global names to their index in
5267 * the globals table.
5269 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5270 table = g_ptr_array_sized_new (table_size);
5271 for (i = 0; i < table_size; ++i)
5272 g_ptr_array_add (table, NULL);
5273 for (i = 0; i < acfg->globals->len; ++i) {
5274 char *name = g_ptr_array_index (acfg->globals, i);
5276 hash = mono_metadata_str_hash (name) % table_size;
5278 /* FIXME: Allocate from the mempool */
5279 new_entry = g_new0 (GlobalsTableEntry, 1);
5280 new_entry->value = i;
5282 entry = g_ptr_array_index (table, hash);
5283 if (entry == NULL) {
5284 new_entry->index = hash;
5285 g_ptr_array_index (table, hash) = new_entry;
5288 entry = entry->next;
5290 entry->next = new_entry;
5291 new_entry->index = table->len;
5292 g_ptr_array_add (table, new_entry);
5296 /* Emit the table */
5297 sprintf (symbol, ".Lglobals_hash");
5298 emit_section_change (acfg, ".text", 0);
5299 emit_alignment (acfg, 8);
5300 emit_label (acfg, symbol);
5302 /* FIXME: Optimize memory usage */
5303 g_assert (table_size < 65000);
5304 emit_int16 (acfg, table_size);
5305 for (i = 0; i < table->len; ++i) {
5306 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5308 if (entry == NULL) {
5309 emit_int16 (acfg, 0);
5310 emit_int16 (acfg, 0);
5312 emit_int16 (acfg, entry->value + 1);
5314 emit_int16 (acfg, entry->next->index);
5316 emit_int16 (acfg, 0);
5320 /* Emit the names */
5321 for (i = 0; i < acfg->globals->len; ++i) {
5322 char *name = g_ptr_array_index (acfg->globals, i);
5324 sprintf (symbol, "name_%d", i);
5325 emit_section_change (acfg, ".text", 1);
5326 emit_label (acfg, symbol);
5327 emit_string (acfg, name);
5330 /* Emit the globals table */
5331 sprintf (symbol, ".Lglobals");
5332 emit_section_change (acfg, ".data", 0);
5333 /* This is not a global, since it is accessed by the init function */
5334 emit_alignment (acfg, 8);
5335 emit_label (acfg, symbol);
5337 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5338 emit_pointer (acfg, symbol);
5340 for (i = 0; i < acfg->globals->len; ++i) {
5341 char *name = g_ptr_array_index (acfg->globals, i);
5343 sprintf (symbol, "name_%d", i);
5344 emit_pointer (acfg, symbol);
5346 sprintf (symbol, "%s", name);
5347 emit_pointer (acfg, symbol);
5349 /* Null terminate the table */
5350 emit_int32 (acfg, 0);
5351 emit_int32 (acfg, 0);
5355 emit_globals (MonoAotCompile *acfg)
5359 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5361 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5363 if (acfg->aot_opts.bind_to_runtime_version) {
5364 build_info = mono_get_runtime_build_info ();
5365 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5366 g_free (build_info);
5368 emit_string_symbol (acfg, "mono_runtime_version", "");
5372 * When static linking, we emit a global which will point to the symbol table.
5374 if (acfg->aot_opts.static_link) {
5378 /* Emit a string holding the assembly name */
5379 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5381 emit_globals_table (acfg);
5384 * Emit a global symbol which can be passed by an embedding app to
5385 * mono_aot_register_module ().
5387 #if defined(__MACH__)
5388 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5390 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5393 /* Get rid of characters which cannot occur in symbols */
5395 for (p = symbol; *p; ++p) {
5396 if (!(isalnum (*p) || *p == '_'))
5399 acfg->static_linking_symbol = g_strdup (symbol);
5400 emit_global_inner (acfg, symbol, FALSE);
5401 emit_alignment (acfg, 8);
5402 emit_label (acfg, symbol);
5403 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5404 emit_pointer (acfg, symbol);
5409 emit_autoreg (MonoAotCompile *acfg)
5414 * Emit a function into the .ctor section which will be called by the ELF
5415 * loader to register this module with the runtime.
5417 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5420 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5422 arch_emit_autoreg (acfg, symbol);
5428 emit_mem_end (MonoAotCompile *acfg)
5432 sprintf (symbol, "mem_end");
5433 emit_section_change (acfg, ".text", 1);
5434 emit_global (acfg, symbol, FALSE);
5435 emit_alignment (acfg, 8);
5436 emit_label (acfg, symbol);
5440 * Emit a structure containing all the information not stored elsewhere.
5443 emit_file_info (MonoAotCompile *acfg)
5448 sprintf (symbol, "mono_aot_file_info");
5449 emit_section_change (acfg, ".data", 0);
5450 emit_alignment (acfg, 8);
5451 emit_label (acfg, symbol);
5452 emit_global (acfg, symbol, FALSE);
5454 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5455 emit_int32 (acfg, acfg->plt_got_offset_base);
5456 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5457 emit_int32 (acfg, acfg->plt_offset);
5458 emit_int32 (acfg, acfg->nmethods);
5459 emit_int32 (acfg, acfg->flags);
5460 emit_int32 (acfg, acfg->opts);
5462 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5463 emit_int32 (acfg, acfg->num_trampolines [i]);
5464 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5465 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5466 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5467 emit_int32 (acfg, acfg->trampoline_size [i]);
5471 emit_blob (MonoAotCompile *acfg)
5475 sprintf (symbol, "blob");
5476 emit_section_change (acfg, ".text", 1);
5477 emit_global (acfg, symbol, FALSE);
5478 emit_alignment (acfg, 8);
5479 emit_label (acfg, symbol);
5481 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5485 emit_dwarf_info (MonoAotCompile *acfg)
5487 #ifdef EMIT_DWARF_INFO
5489 char symbol [128], symbol2 [128];
5491 /* DIEs for methods */
5492 for (i = 0; i < acfg->nmethods; ++i) {
5493 MonoCompile *cfg = acfg->cfgs [i];
5498 // FIXME: LLVM doesn't define .Lme_...
5499 if (cfg->compile_llvm)
5502 sprintf (symbol, "%s", cfg->asm_symbol);
5503 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5505 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 ()));
5511 collect_methods (MonoAotCompile *acfg)
5514 MonoImage *image = acfg->image;
5516 /* Collect methods */
5517 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5519 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5521 method = mono_get_method (acfg->image, token, NULL);
5524 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5528 /* Load all methods eagerly to skip the slower lazy loading code */
5529 mono_class_setup_methods (method->klass);
5531 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5532 /* Compile the wrapper instead */
5533 /* We do this here instead of add_wrappers () because it is easy to do it here */
5534 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5538 /* FIXME: Some mscorlib methods don't have debug info */
5540 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5541 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5542 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5543 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5544 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5545 if (!mono_debug_lookup_method (method)) {
5546 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5553 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5554 add_method_with_index (acfg, method, i, FALSE);
5555 acfg->method_index ++;
5558 add_generic_instances (acfg);
5560 if (acfg->aot_opts.full_aot)
5561 add_wrappers (acfg);
5565 compile_methods (MonoAotCompile *acfg)
5569 if (acfg->aot_opts.nthreads > 0) {
5574 gpointer *user_data;
5575 MonoMethod **methods;
5577 methods_len = acfg->methods->len;
5579 len = acfg->methods->len / acfg->aot_opts.nthreads;
5582 * Partition the list of methods into fragments, and hand it to threads to
5585 threads = g_ptr_array_new ();
5586 /* Make a copy since acfg->methods is modified by compile_method () */
5587 methods = g_new0 (MonoMethod*, methods_len);
5588 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5589 for (i = 0; i < methods_len; ++i)
5590 methods [i] = g_ptr_array_index (acfg->methods, i);
5592 while (i < methods_len) {
5593 frag = g_ptr_array_new ();
5594 for (j = 0; j < len; ++j) {
5595 if (i < methods_len) {
5596 g_ptr_array_add (frag, methods [i]);
5601 user_data = g_new0 (gpointer, 3);
5602 user_data [0] = mono_domain_get ();
5603 user_data [1] = acfg;
5604 user_data [2] = frag;
5606 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5607 g_ptr_array_add (threads, handle);
5611 for (i = 0; i < threads->len; ++i) {
5612 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5618 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5619 for (i = methods_len; i < acfg->methods->len; ++i) {
5620 /* This can new methods to acfg->methods */
5621 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5626 compile_asm (MonoAotCompile *acfg)
5628 char *command, *objfile;
5629 char *outfile_name, *tmp_outfile_name;
5630 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5632 #if defined(TARGET_AMD64)
5633 #define AS_OPTIONS "--64"
5634 #elif defined(TARGET_POWERPC64)
5635 #define AS_OPTIONS "-a64 -mppc64"
5636 #define LD_OPTIONS "-m elf64ppc"
5637 #elif defined(sparc) && SIZEOF_VOID_P == 8
5638 #define AS_OPTIONS "-xarch=v9"
5640 #define AS_OPTIONS ""
5644 #define LD_OPTIONS ""
5648 #define EH_LD_OPTIONS "--eh-frame-hdr"
5650 #define EH_LD_OPTIONS ""
5653 if (acfg->aot_opts.asm_only) {
5654 printf ("Output file: '%s'.\n", acfg->tmpfname);
5655 if (acfg->aot_opts.static_link)
5656 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5660 if (acfg->aot_opts.static_link) {
5661 if (acfg->aot_opts.outfile)
5662 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5664 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5666 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5668 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5669 printf ("Executing the native assembler: %s\n", command);
5670 if (system (command) != 0) {
5678 if (acfg->aot_opts.static_link) {
5679 printf ("Output file: '%s'.\n", objfile);
5680 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5685 if (acfg->aot_opts.outfile)
5686 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5688 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5690 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5693 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5694 #elif defined(__ppc__) && defined(__MACH__)
5695 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5696 #elif defined(HOST_WIN32)
5697 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5699 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5701 printf ("Executing the native linker: %s\n", command);
5702 if (system (command) != 0) {
5703 g_free (tmp_outfile_name);
5704 g_free (outfile_name);
5712 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5713 printf ("Stripping the binary: %s\n", com);
5717 #if defined(TARGET_ARM) && !defined(__MACH__)
5719 * gas generates 'mapping symbols' each time code and data is mixed, which
5720 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5722 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5723 printf ("Stripping the binary: %s\n", command);
5724 if (system (command) != 0) {
5725 g_free (tmp_outfile_name);
5726 g_free (outfile_name);
5733 rename (tmp_outfile_name, outfile_name);
5735 g_free (tmp_outfile_name);
5736 g_free (outfile_name);
5739 if (acfg->aot_opts.save_temps)
5740 printf ("Retained input file.\n");
5742 unlink (acfg->tmpfname);
5747 static MonoAotCompile*
5748 acfg_create (MonoAssembly *ass, guint32 opts)
5750 MonoImage *image = ass->image;
5751 MonoAotCompile *acfg;
5754 acfg = g_new0 (MonoAotCompile, 1);
5755 acfg->methods = g_ptr_array_new ();
5756 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5757 acfg->method_depth = g_hash_table_new (NULL, NULL);
5758 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5759 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5760 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5761 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5762 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5763 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5764 acfg->got_patches = g_ptr_array_new ();
5765 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5766 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5767 acfg->image_hash = g_hash_table_new (NULL, NULL);
5768 acfg->image_table = g_ptr_array_new ();
5769 acfg->globals = g_ptr_array_new ();
5770 acfg->image = image;
5772 acfg->mempool = mono_mempool_new ();
5773 acfg->extra_methods = g_ptr_array_new ();
5774 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5775 acfg->unwind_ops = g_ptr_array_new ();
5776 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5777 InitializeCriticalSection (&acfg->mutex);
5783 acfg_free (MonoAotCompile *acfg)
5787 img_writer_destroy (acfg->w);
5788 for (i = 0; i < acfg->nmethods; ++i)
5790 g_free (acfg->cfgs [i]);
5791 g_free (acfg->cfgs);
5792 g_free (acfg->static_linking_symbol);
5793 g_free (acfg->got_symbol);
5794 g_free (acfg->plt_symbol);
5795 g_ptr_array_free (acfg->methods, TRUE);
5796 g_ptr_array_free (acfg->got_patches, TRUE);
5797 g_ptr_array_free (acfg->image_table, TRUE);
5798 g_ptr_array_free (acfg->globals, TRUE);
5799 g_ptr_array_free (acfg->unwind_ops, TRUE);
5800 g_hash_table_destroy (acfg->method_indexes);
5801 g_hash_table_destroy (acfg->method_depth);
5802 g_hash_table_destroy (acfg->plt_offset_to_patch);
5803 g_hash_table_destroy (acfg->patch_to_plt_offset);
5804 g_hash_table_destroy (acfg->patch_to_got_offset);
5805 g_hash_table_destroy (acfg->method_to_cfg);
5806 g_hash_table_destroy (acfg->token_info_hash);
5807 g_hash_table_destroy (acfg->image_hash);
5808 g_hash_table_destroy (acfg->unwind_info_offsets);
5809 g_hash_table_destroy (acfg->method_label_hash);
5810 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5811 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
5812 g_free (acfg->patch_to_got_offset_by_type);
5813 mono_mempool_destroy (acfg->mempool);
5818 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5820 MonoImage *image = ass->image;
5822 MonoAotCompile *acfg;
5823 char *outfile_name, *tmp_outfile_name, *p;
5827 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5829 acfg = acfg_create (ass, opts);
5831 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5832 acfg->aot_opts.write_symbols = TRUE;
5833 acfg->aot_opts.ntrampolines = 1024;
5834 acfg->aot_opts.nrgctx_trampolines = 1024;
5835 acfg->aot_opts.nimt_trampolines = 128;
5837 mono_aot_parse_options (aot_options, &acfg->aot_opts);
5839 if (acfg->aot_opts.static_link)
5840 acfg->aot_opts.autoreg = TRUE;
5842 //acfg->aot_opts.print_skipped_methods = TRUE;
5844 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5845 if (acfg->aot_opts.full_aot) {
5846 printf ("--aot=full is not supported on this platform.\n");
5851 if (acfg->aot_opts.static_link)
5852 acfg->aot_opts.asm_writer = TRUE;
5854 if (acfg->aot_opts.soft_debug) {
5855 MonoDebugOptions *opt = mini_get_debug_options ();
5857 opt->mdb_optimizations = TRUE;
5858 opt->gen_seq_points = TRUE;
5860 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
5861 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
5868 acfg->aot_opts.asm_writer = TRUE;
5869 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
5872 if (acfg->aot_opts.full_aot)
5873 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
5875 load_profile_files (acfg);
5877 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5878 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5879 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
5881 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
5883 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5884 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5886 /* Get rid of characters which cannot occur in symbols */
5887 for (p = acfg->got_symbol_base; *p; ++p) {
5888 if (!(isalnum (*p) || *p == '_'))
5891 for (p = acfg->plt_symbol; *p; ++p) {
5892 if (!(isalnum (*p) || *p == '_'))
5896 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
5898 acfg->method_index = 1;
5900 collect_methods (acfg);
5902 acfg->cfgs_size = acfg->methods->len + 32;
5903 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5905 /* PLT offset 0 is reserved for the PLT trampoline */
5906 acfg->plt_offset = 1;
5910 mono_llvm_create_aot_module (acfg->got_symbol_base);
5913 /* GOT offset 0 is reserved for the address of the current assembly */
5917 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5918 ji->type = MONO_PATCH_INFO_IMAGE;
5919 ji->data.image = acfg->image;
5921 get_got_offset (acfg, ji);
5923 /* Slot 1 is reserved for the mscorlib got addr */
5924 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5925 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5926 get_got_offset (acfg, ji);
5931 compile_methods (acfg);
5935 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5941 if (acfg->aot_opts.asm_only) {
5942 if (acfg->aot_opts.outfile)
5943 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5945 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5947 acfg->tmpfname = g_strdup ("temp.s");
5951 emit_llvm_file (acfg);
5954 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5955 if (acfg->aot_opts.outfile)
5956 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5958 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5961 * Can't use g_file_open_tmp () as it will be deleted at exit, and
5962 * it might be in another file system so the rename () won't work.
5964 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5966 acfg->fp = fopen (tmp_outfile_name, "w");
5968 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5972 acfg->w = img_writer_create (acfg->fp, TRUE);
5973 acfg->use_bin_writer = TRUE;
5976 /* Append to the .s file created by llvm */
5977 /* FIXME: Use multiple files instead */
5978 acfg->fp = fopen (acfg->tmpfname, "a+");
5980 if (acfg->aot_opts.asm_only) {
5981 if (acfg->aot_opts.outfile)
5982 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5984 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5985 acfg->fp = fopen (acfg->tmpfname, "w+");
5987 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5988 acfg->fp = fdopen (i, "w+");
5990 g_assert (acfg->fp);
5992 acfg->w = img_writer_create (acfg->fp, FALSE);
5994 tmp_outfile_name = NULL;
5995 outfile_name = NULL;
5999 * The prefix LLVM likes to put in front of symbol names on darwin.
6000 * The mach-os specs require this for globals, but LLVM puts them in front of all
6001 * symbols. We need to handle this, since we need to refer to LLVM generated
6004 acfg->llvm_label_prefix = "";
6006 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6008 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6010 /* Compute symbols for methods */
6011 for (i = 0; i < acfg->nmethods; ++i) {
6012 if (acfg->cfgs [i]) {
6013 MonoCompile *cfg = acfg->cfgs [i];
6014 int method_index = get_method_index (acfg, cfg->orig_method);
6016 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6020 if (!acfg->aot_opts.nodebug)
6021 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6023 img_writer_emit_start (acfg->w);
6026 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_arch_get_cie_program ());
6032 emit_extra_methods (acfg);
6034 emit_trampolines (acfg);
6036 emit_class_name_table (acfg);
6038 emit_got_info (acfg);
6040 emit_exception_info (acfg);
6042 emit_unwind_info (acfg);
6044 emit_class_info (acfg);
6048 emit_image_table (acfg);
6052 emit_file_info (acfg);
6056 emit_globals (acfg);
6058 emit_autoreg (acfg);
6061 emit_dwarf_info (acfg);
6062 mono_dwarf_writer_close (acfg->dwarf);
6065 emit_mem_end (acfg);
6069 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6072 g_assert (acfg->got_offset <= acfg->final_got_size);
6074 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);
6077 res = img_writer_emit_writeout (acfg->w);
6082 if (acfg->use_bin_writer) {
6083 int err = rename (tmp_outfile_name, outfile_name);
6086 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6090 res = compile_asm (acfg);
6097 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6099 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);
6100 if (acfg->stats.genericcount)
6101 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6102 if (acfg->stats.abscount)
6103 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6104 if (acfg->stats.lmfcount)
6105 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6106 if (acfg->stats.ocount)
6107 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6109 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6110 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);
6111 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6113 if (acfg->aot_opts.stats) {
6116 printf ("GOT slot distribution:\n");
6117 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6118 if (acfg->stats.got_slot_types [i])
6119 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6122 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);
6134 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)