2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - optimize the trampolines, generate more code in the arch files.
13 * - make things more consistent with how elf works, for example, use ELF
15 * Remaining generics sharing work:
16 * - optimize the size of the data which is encoded.
17 * - optimize the runtime loading of data:
18 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
19 * which loads the debugging+exception handling info for the method. This is a
20 * huge waste of time and code, since the rgctx structure is currently empty.
21 * - every shared method has a MonoGenericJitInfo structure which is only really
22 * used for handling catch clauses with open types, not a very common use case.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #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
547 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
550 #ifdef MONO_ARCH_AOT_SUPPORTED
552 * arch_emit_got_offset:
554 * The memory pointed to by CODE should hold native code for computing the GOT
555 * address. Emit this code while patching it with the offset between code and
556 * the GOT. CODE_SIZE is set to the number of bytes emitted.
559 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
561 #if defined(TARGET_POWERPC64)
562 g_assert (!acfg->use_bin_writer);
563 img_writer_emit_unset_mode (acfg->w);
565 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
566 * unsupported relocations. So we store the got address into the .Lgot_addr
567 * symbol which is in the text segment, compute its address, and load it.
569 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
570 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
571 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
572 fprintf (acfg->fp, "add 30, 30, 0\n");
573 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
574 acfg->label_generator ++;
576 #elif defined(TARGET_POWERPC)
577 g_assert (!acfg->use_bin_writer);
578 img_writer_emit_unset_mode (acfg->w);
579 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
580 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
581 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
582 acfg->label_generator ++;
585 guint32 offset = mono_arch_get_patch_offset (code);
586 emit_bytes (acfg, code, offset);
587 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
589 *code_size = offset + 4;
594 * arch_emit_got_access:
596 * The memory pointed to by CODE should hold native code for loading a GOT
597 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
598 * CODE_SIZE is set to the number of bytes emitted.
601 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
603 /* Emit beginning of instruction */
604 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
606 /* Emit the offset */
608 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
609 *code_size = mono_arch_get_patch_offset (code) + 4;
610 #elif defined(TARGET_X86)
611 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
612 *code_size = mono_arch_get_patch_offset (code) + 4;
613 #elif defined(TARGET_ARM)
614 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
615 *code_size = mono_arch_get_patch_offset (code) + 4;
616 #elif defined(TARGET_POWERPC)
622 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
623 g_assert (code - buf == 8);
624 emit_bytes (acfg, buf, code - buf);
625 *code_size = code - buf;
628 g_assert_not_reached ();
635 * arch_emit_plt_entry:
637 * Emit code for the PLT entry with index INDEX.
640 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
642 #if defined(TARGET_X86)
643 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
645 /* jmp *<offset>(%ebx) */
646 emit_byte (acfg, 0xff);
647 emit_byte (acfg, 0xa3);
648 emit_int32 (acfg, offset);
649 /* Used by mono_aot_get_plt_info_offset */
650 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
651 #elif defined(TARGET_AMD64)
653 * We can't emit jumps because they are 32 bits only so they can't be patched.
654 * So we make indirect calls through GOT entries which are patched by the AOT
655 * loader to point to .Lpd entries.
657 /* jmpq *<offset>(%rip) */
658 emit_byte (acfg, '\xff');
659 emit_byte (acfg, '\x25');
660 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
661 /* Used by mono_aot_get_plt_info_offset */
662 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
663 #elif defined(TARGET_ARM)
668 * - optimize OP_AOTCONST implementation
669 * - optimize the PLT entries
670 * - optimize SWITCH AOT implementation
673 if (acfg->use_bin_writer && FALSE) {
674 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
675 /* We only emit 1 relocation since we implement it ourselves anyway */
676 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
677 /* FIXME: A 2 instruction encoding is sufficient in most cases */
678 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
679 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
680 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
681 emit_bytes (acfg, buf, code - buf);
682 /* Used by mono_aot_get_plt_info_offset */
683 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
685 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
686 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
687 emit_bytes (acfg, buf, code - buf);
688 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
689 /* Used by mono_aot_get_plt_info_offset */
690 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
693 * The plt_got_info_offset is computed automatically by
694 * mono_aot_get_plt_info_offset (), so no need to save it here.
696 #elif defined(TARGET_POWERPC)
697 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
699 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
700 g_assert (!acfg->use_bin_writer);
701 img_writer_emit_unset_mode (acfg->w);
702 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
703 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
704 fprintf (acfg->fp, "add 11, 11, 30\n");
705 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
706 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
707 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
708 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
710 fprintf (acfg->fp, "mtctr 11\n");
711 fprintf (acfg->fp, "bctr\n");
712 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
714 g_assert_not_reached ();
719 * arch_emit_specific_trampoline:
721 * Emit code for a specific trampoline. OFFSET is the offset of the first of
722 * two GOT slots which contain the generic trampoline address and the trampoline
723 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
726 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
729 * The trampolines created here are variations of the specific
730 * trampolines created in mono_arch_create_specific_trampoline (). The
732 * - the generic trampoline address is taken from a got slot.
733 * - the offset of the got slot where the trampoline argument is stored
734 * is embedded in the instruction stream, and the generic trampoline
735 * can load the argument by loading the offset, adding it to the
736 * address of the trampoline to get the address of the got slot, and
737 * loading the argument from there.
738 * - all the trampolines should be of the same length.
740 #if defined(TARGET_AMD64)
741 /* This should be exactly 16 bytes long */
743 /* call *<offset>(%rip) */
744 emit_byte (acfg, '\x41');
745 emit_byte (acfg, '\xff');
746 emit_byte (acfg, '\x15');
747 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
748 /* This should be relative to the start of the trampoline */
749 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
750 emit_zero_bytes (acfg, 5);
751 #elif defined(TARGET_ARM)
755 /* This should be exactly 20 bytes long */
758 ARM_PUSH (code, 0x5fff);
759 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
760 /* Load the value from the GOT */
761 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
763 ARM_BLX_REG (code, ARMREG_R1);
765 g_assert (code - buf == 16);
768 emit_bytes (acfg, buf, code - buf);
770 * Only one offset is needed, since the second one would be equal to the
773 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
774 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
775 #elif defined(TARGET_POWERPC)
782 g_assert (!acfg->use_bin_writer);
785 * PPC has no ip relative addressing, so we need to compute the address
786 * of the mscorlib got. That is slow and complex, so instead, we store it
787 * in the second got slot of every aot image. The caller already computed
788 * the address of its got and placed it into r30.
790 img_writer_emit_unset_mode (acfg->w);
791 /* Load mscorlib got address */
792 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
793 /* Load generic trampoline address */
794 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
795 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
796 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
797 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
798 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
800 fprintf (acfg->fp, "mtctr 11\n");
801 /* Load trampoline argument */
802 /* On ppc, we pass it normally to the generic trampoline */
803 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
804 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
805 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
806 /* Branch to generic trampoline */
807 fprintf (acfg->fp, "bctr\n");
809 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
810 *tramp_size = 10 * 4;
814 #elif defined(TARGET_X86)
818 /* Similar to the PPC code above */
820 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
822 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
823 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
824 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
828 /* Load mscorlib got address */
829 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
830 /* Push trampoline argument */
831 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
832 /* Load generic trampoline address */
833 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
834 /* Branch to generic trampoline */
835 x86_jump_reg (code, X86_ECX);
837 emit_bytes (acfg, buf, code - buf);
840 g_assert (code - buf == *tramp_size);
842 g_assert_not_reached ();
847 * arch_emit_unbox_trampoline:
849 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
850 * CALL_TARGET is the symbol pointing to the native code of METHOD.
853 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
855 #if defined(TARGET_AMD64)
860 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
862 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
864 emit_bytes (acfg, buf, code - buf);
866 emit_byte (acfg, '\xe9');
867 emit_symbol_diff (acfg, call_target, ".", -4);
868 #elif defined(TARGET_X86)
873 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
878 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
880 emit_bytes (acfg, buf, code - buf);
883 emit_byte (acfg, '\xe9');
884 emit_symbol_diff (acfg, call_target, ".", -4);
885 #elif defined(TARGET_ARM)
892 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
895 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
897 emit_bytes (acfg, buf, code - buf);
899 if (acfg->use_bin_writer) {
906 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
907 emit_bytes (acfg, buf, 4);
909 fprintf (acfg->fp, "\n\tb %s\n", call_target);
911 #elif defined(TARGET_POWERPC)
914 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
917 g_assert (!acfg->use_bin_writer);
919 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
920 fprintf (acfg->fp, "\n\tb %s\n", call_target);
922 g_assert_not_reached ();
927 * arch_emit_static_rgctx_trampoline:
929 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
930 * two GOT slots which contain the rgctx argument, and the method to jump to.
931 * TRAMP_SIZE is set to the size of the emitted trampoline.
932 * These kinds of trampolines cannot be enumerated statically, since there could
933 * be one trampoline per method instantiation, so we emit the same code for all
934 * trampolines, and parameterize them using two GOT slots.
937 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
939 #if defined(TARGET_AMD64)
940 /* This should be exactly 13 bytes long */
943 /* mov <OFFSET>(%rip), %r10 */
944 emit_byte (acfg, '\x4d');
945 emit_byte (acfg, '\x8b');
946 emit_byte (acfg, '\x15');
947 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
949 /* jmp *<offset>(%rip) */
950 emit_byte (acfg, '\xff');
951 emit_byte (acfg, '\x25');
952 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
953 #elif defined(TARGET_ARM)
957 /* This should be exactly 24 bytes long */
960 /* Load rgctx value */
961 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
962 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
963 /* Load branch addr + branch */
964 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
965 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
967 g_assert (code - buf == 16);
970 emit_bytes (acfg, buf, code - buf);
971 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
972 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
973 #elif defined(TARGET_POWERPC)
980 g_assert (!acfg->use_bin_writer);
983 * PPC has no ip relative addressing, so we need to compute the address
984 * of the mscorlib got. That is slow and complex, so instead, we store it
985 * in the second got slot of every aot image. The caller already computed
986 * the address of its got and placed it into r30.
988 img_writer_emit_unset_mode (acfg->w);
989 /* Load mscorlib got address */
990 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
992 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
993 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
994 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
995 /* Load target address */
996 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
997 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
998 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
999 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1000 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1001 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1003 fprintf (acfg->fp, "mtctr 11\n");
1004 /* Branch to the target address */
1005 fprintf (acfg->fp, "bctr\n");
1007 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1008 *tramp_size = 11 * 4;
1010 *tramp_size = 9 * 4;
1013 #elif defined(TARGET_X86)
1017 /* Similar to the PPC code above */
1019 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1022 /* Load mscorlib got address */
1023 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1025 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1026 /* Branch to the target address */
1027 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1029 emit_bytes (acfg, buf, code - buf);
1032 g_assert (code - buf == *tramp_size);
1034 g_assert_not_reached ();
1039 * arch_emit_imt_thunk:
1041 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1042 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1043 * key is the IMT key, and ptr holds the address of a memory location holding
1044 * the address to branch to if the IMT arg matches the key. The array is
1045 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1047 * TRAMP_SIZE is set to the size of the emitted trampoline.
1050 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1052 #if defined(TARGET_AMD64)
1056 code = buf = g_malloc (256);
1058 /* FIXME: Optimize this, i.e. use binary search etc. */
1059 /* Maybe move the body into a separate function (slower, but much smaller) */
1061 /* R10 is a free register */
1064 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
1066 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1069 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
1071 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1074 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
1075 amd64_jump_code (code, labels [0]);
1078 mono_amd64_patch (labels [2], code);
1079 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
1080 amd64_jump_membase (code, AMD64_R10, 0);
1084 mono_amd64_patch (labels [1], code);
1085 x86_breakpoint (code);
1087 /* mov <OFFSET>(%rip), %r10 */
1088 emit_byte (acfg, '\x4d');
1089 emit_byte (acfg, '\x8b');
1090 emit_byte (acfg, '\x15');
1091 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1093 emit_bytes (acfg, buf, code - buf);
1095 *tramp_size = code - buf + 7;
1096 #elif defined(TARGET_X86)
1100 code = buf = g_malloc (256);
1102 /* Allocate a temporary stack slot */
1103 x86_push_reg (code, X86_EAX);
1105 x86_push_reg (code, X86_EAX);
1107 /* Load mscorlib got address */
1108 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1110 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1113 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1115 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1118 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1120 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1123 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1124 x86_jump_code (code, labels [0]);
1127 mono_x86_patch (labels [2], code);
1128 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1129 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1130 /* Save the target address to the temporary stack location */
1131 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1133 x86_pop_reg (code, X86_EAX);
1134 /* Jump to the target address */
1139 mono_x86_patch (labels [1], code);
1140 x86_breakpoint (code);
1142 emit_bytes (acfg, buf, code - buf);
1144 *tramp_size = code - buf;
1145 #elif defined(TARGET_ARM)
1147 guint8 *code, *code2, *labels [16];
1151 /* The IMT method is in v5 */
1153 /* Need at least two free registers, plus a slot for storing the pc */
1154 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1156 /* Load the parameter from the GOT */
1157 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1158 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1161 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1162 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1164 ARM_B_COND (code, ARMCOND_EQ, 0);
1166 /* End-of-loop check */
1167 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1169 ARM_B_COND (code, ARMCOND_EQ, 0);
1172 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1175 arm_patch (labels [4], labels [1]);
1178 arm_patch (labels [2], code);
1179 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1180 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1181 /* Save it to the third stack slot */
1182 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1183 /* Restore the registers and branch */
1184 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1187 arm_patch (labels [3], code);
1192 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1194 emit_bytes (acfg, buf, code - buf);
1195 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1197 *tramp_size = code - buf + 4;
1198 #elif defined(TARGET_POWERPC)
1200 guint8 *code, *labels [16];
1204 /* Load the mscorlib got address */
1205 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1206 /* Load the parameter from the GOT */
1207 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1208 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1210 /* Load and check key */
1212 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1213 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1215 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1217 /* End-of-loop check */
1218 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1220 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1223 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1226 mono_ppc_patch (labels [4], labels [1]);
1229 mono_ppc_patch (labels [2], code);
1230 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1231 /* r11 now contains the value of the vtable slot */
1232 /* this is not a function descriptor on ppc64 */
1233 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1234 ppc_mtctr (code, ppc_r11);
1235 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1238 mono_ppc_patch (labels [3], code);
1242 *tramp_size = code - buf;
1244 emit_bytes (acfg, buf, code - buf);
1246 g_assert_not_reached ();
1251 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1253 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1254 /* Based on code generated by gcc */
1255 img_writer_emit_unset_mode (acfg->w);
1258 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1259 ".section .ctors,\"aw\",@progbits\n"
1263 ".section .opd,\"aw\"\n"
1266 ".long .%s,.TOC.@tocbase32\n"
1269 ".type .%s,@function\n"
1271 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1273 ".section .ctors,\"aw\",@progbits\n"
1277 ".section .opd,\"aw\"\n"
1280 ".long .%1$s,.TOC.@tocbase32\n"
1281 ".size %1$s,.-%1$s\n"
1283 ".type .%1$s,@function\n"
1285 ".%1$s:\n", symbol);
1296 "lis 3, .Lglobals@h\n"
1297 "ori 3, 3, .Lglobals@l\n"
1298 "bl .mono_aot_register_module\n"
1306 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1308 ".size .%s,.-.%s\n", symbol, symbol);
1311 ".size .%1$s,.-.%1$s\n", symbol);
1317 /* END OF ARCH SPECIFIC CODE */
1320 mono_get_field_token (MonoClassField *field)
1322 MonoClass *klass = field->parent;
1325 for (i = 0; i < klass->field.count; ++i) {
1326 if (field == &klass->fields [i])
1327 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1330 g_assert_not_reached ();
1335 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1339 //printf ("ENCODE: %d 0x%x.\n", value, value);
1342 * Same encoding as the one used in the metadata, extended to handle values
1343 * greater than 0x1fffffff.
1345 if ((value >= 0) && (value <= 127))
1347 else if ((value >= 0) && (value <= 16383)) {
1348 p [0] = 0x80 | (value >> 8);
1349 p [1] = value & 0xff;
1351 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1352 p [0] = (value >> 24) | 0xc0;
1353 p [1] = (value >> 16) & 0xff;
1354 p [2] = (value >> 8) & 0xff;
1355 p [3] = value & 0xff;
1360 p [1] = (value >> 24) & 0xff;
1361 p [2] = (value >> 16) & 0xff;
1362 p [3] = (value >> 8) & 0xff;
1363 p [4] = value & 0xff;
1371 stream_init (MonoDynamicStream *sh)
1374 sh->alloc_size = 4096;
1375 sh->data = g_malloc (4096);
1377 /* So offsets are > 0 */
1382 make_room_in_stream (MonoDynamicStream *stream, int size)
1384 if (size <= stream->alloc_size)
1387 while (stream->alloc_size <= size) {
1388 if (stream->alloc_size < 4096)
1389 stream->alloc_size = 4096;
1391 stream->alloc_size *= 2;
1394 stream->data = g_realloc (stream->data, stream->alloc_size);
1398 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1402 make_room_in_stream (stream, stream->index + len);
1403 memcpy (stream->data + stream->index, data, len);
1404 idx = stream->index;
1405 stream->index += len;
1412 * Add data to the binary blob inside the aot image. Returns the offset inside the
1413 * blob where the data was stored.
1416 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1418 if (acfg->blob.alloc_size == 0)
1419 stream_init (&acfg->blob);
1421 return add_stream_data (&acfg->blob, (char*)data, data_len);
1425 * emit_offset_table:
1427 * Emit a table of increasing offsets in a compact form using differential encoding.
1428 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1429 * group size, the more compact the table becomes, but the slower it becomes to compute
1430 * a given entry. Returns the size of the table.
1433 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1435 gint32 current_offset;
1436 int i, buf_size, ngroups, index_entry_size;
1438 guint32 *index_offsets;
1440 ngroups = (noffsets + (group_size - 1)) / group_size;
1442 index_offsets = g_new0 (guint32, ngroups);
1444 buf_size = noffsets * 4;
1445 p = buf = g_malloc0 (buf_size);
1448 for (i = 0; i < noffsets; ++i) {
1449 //printf ("D: %d -> %d\n", i, offsets [i]);
1450 if ((i % group_size) == 0) {
1451 index_offsets [i / group_size] = p - buf;
1452 /* Emit the full value for these entries */
1453 encode_value (offsets [i], p, &p);
1455 /* The offsets are allowed to be non-increasing */
1456 //g_assert (offsets [i] >= current_offset);
1457 encode_value (offsets [i] - current_offset, p, &p);
1459 current_offset = offsets [i];
1462 if (ngroups && index_offsets [ngroups - 1] < 65000)
1463 index_entry_size = 2;
1465 index_entry_size = 4;
1467 /* Emit the header */
1468 emit_int32 (acfg, noffsets);
1469 emit_int32 (acfg, group_size);
1470 emit_int32 (acfg, ngroups);
1471 emit_int32 (acfg, index_entry_size);
1473 /* Emit the index */
1474 for (i = 0; i < ngroups; ++i) {
1475 if (index_entry_size == 2)
1476 emit_int16 (acfg, index_offsets [i]);
1478 emit_int32 (acfg, index_offsets [i]);
1482 emit_bytes (acfg, buf, p - buf);
1484 return (int)(p - buf) + (ngroups * 4);
1488 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1492 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1496 index = g_hash_table_size (cfg->image_hash);
1497 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1498 g_ptr_array_add (cfg->image_table, image);
1504 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1507 MonoClass *k = NULL;
1509 /* FIXME: Search referenced images as well */
1510 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1511 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1516 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1517 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1523 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1528 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1529 * standard metadata encoding.
1532 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1536 if (klass->generic_class) {
1538 g_assert (klass->type_token);
1540 /* Find a typespec for a class if possible */
1541 token = find_typespec_for_class (acfg, klass);
1543 encode_value (token, p, &p);
1544 encode_value (get_image_index (acfg, acfg->image), p, &p);
1546 MonoClass *gclass = klass->generic_class->container_class;
1547 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1550 /* Encode it ourselves */
1552 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1553 encode_value (MONO_TYPE_GENERICINST, p, &p);
1554 encode_klass_ref (acfg, gclass, p, &p);
1555 encode_value (inst->type_argc, p, &p);
1556 for (i = 0; i < inst->type_argc; ++i)
1557 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1559 } else if (klass->type_token) {
1560 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1561 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1562 encode_value (get_image_index (acfg, klass->image), p, &p);
1563 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1564 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1565 g_assert (container);
1568 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1569 encode_value (klass->byval_arg.type, p, &p);
1571 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1573 encode_value (container->is_method, p, &p);
1574 if (container->is_method)
1575 encode_method_ref (acfg, container->owner.method, p, &p);
1577 encode_klass_ref (acfg, container->owner.klass, p, &p);
1580 g_assert (klass->rank > 0);
1581 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1582 encode_value (get_image_index (acfg, klass->image), p, &p);
1583 encode_value (klass->rank, p, &p);
1584 encode_klass_ref (acfg, klass->element_class, p, &p);
1590 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1592 guint32 token = mono_get_field_token (field);
1595 encode_klass_ref (cfg, field->parent, p, &p);
1596 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1597 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1602 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1606 MonoGenericInst *inst;
1608 /* Encode the context */
1609 inst = context->class_inst;
1610 encode_value (inst ? 1 : 0, p, &p);
1612 encode_value (inst->type_argc, p, &p);
1613 for (i = 0; i < inst->type_argc; ++i)
1614 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1616 inst = context->method_inst;
1617 encode_value (inst ? 1 : 0, p, &p);
1619 encode_value (inst->type_argc, p, &p);
1620 for (i = 0; i < inst->type_argc; ++i)
1621 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1627 #define MAX_IMAGE_INDEX 250
1630 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1632 guint32 image_index = get_image_index (acfg, method->klass->image);
1633 guint32 token = method->token;
1634 MonoJumpInfoToken *ji;
1639 * The encoding for most methods is as follows:
1640 * - image index encoded as a leb128
1641 * - token index encoded as a leb128
1642 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1643 * types of method encodings.
1646 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1648 /* Mark methods which can't use aot trampolines because they need the further
1649 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1651 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1652 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1653 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1656 * Some wrapper methods are shared using their signature, encode their
1657 * stringified signature instead.
1658 * FIXME: Optimize disk usage
1661 if (method->wrapper_type) {
1662 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1663 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1664 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1665 name = mono_aot_wrapper_name (method);
1666 } else if (mono_marshal_method_from_wrapper (method) != method) {
1667 /* Direct wrapper, encode it normally */
1669 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1672 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1673 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1674 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1676 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1677 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1678 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1680 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1681 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1682 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1688 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1689 strcpy ((char*)p, name);
1690 p += strlen (name) + 1;
1692 } else if (method->wrapper_type) {
1693 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1695 encode_value (method->wrapper_type, p, &p);
1697 switch (method->wrapper_type) {
1698 case MONO_WRAPPER_REMOTING_INVOKE:
1699 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1700 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1703 m = mono_marshal_method_from_wrapper (method);
1705 encode_method_ref (acfg, m, p, &p);
1708 case MONO_WRAPPER_PROXY_ISINST:
1709 case MONO_WRAPPER_LDFLD:
1710 case MONO_WRAPPER_LDFLDA:
1711 case MONO_WRAPPER_STFLD:
1712 case MONO_WRAPPER_ISINST: {
1713 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1714 encode_klass_ref (acfg, proxy_class, p, &p);
1717 case MONO_WRAPPER_LDFLD_REMOTE:
1718 case MONO_WRAPPER_STFLD_REMOTE:
1720 case MONO_WRAPPER_ALLOC: {
1721 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1723 g_assert (info->alloc_type != -1);
1724 encode_value (info->alloc_type, p, &p);
1727 case MONO_WRAPPER_WRITE_BARRIER:
1729 case MONO_WRAPPER_STELEMREF:
1731 case MONO_WRAPPER_UNKNOWN:
1732 if (strcmp (method->name, "FastMonitorEnter") == 0)
1733 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1734 else if (strcmp (method->name, "FastMonitorExit") == 0)
1735 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1737 g_assert_not_reached ();
1739 case MONO_WRAPPER_SYNCHRONIZED:
1740 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1741 case MONO_WRAPPER_RUNTIME_INVOKE: {
1744 m = mono_marshal_method_from_wrapper (method);
1746 g_assert (m != method);
1747 encode_method_ref (acfg, m, p, &p);
1750 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1751 if (!strcmp (method->name, "ElementAddr")) {
1752 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1755 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1756 encode_value (info->rank, p, &p);
1757 encode_value (info->elem_size, p, &p);
1759 g_assert_not_reached ();
1763 g_assert_not_reached ();
1765 } else if (mono_method_signature (method)->is_inflated) {
1767 * This is a generic method, find the original token which referenced it and
1769 * Obtain the token from information recorded by the JIT.
1771 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1773 image_index = get_image_index (acfg, ji->image);
1774 g_assert (image_index < MAX_IMAGE_INDEX);
1777 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1778 encode_value (image_index, p, &p);
1779 encode_value (token, p, &p);
1781 MonoMethod *declaring;
1782 MonoGenericContext *context = mono_method_get_context (method);
1784 g_assert (method->is_inflated);
1785 declaring = ((MonoMethodInflated*)method)->declaring;
1788 * This might be a non-generic method of a generic instance, which
1789 * doesn't have a token since the reference is generated by the JIT
1790 * like Nullable:Box/Unbox, or by generic sharing.
1793 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1794 /* Encode the klass */
1795 encode_klass_ref (acfg, method->klass, p, &p);
1796 /* Encode the method */
1797 image_index = get_image_index (acfg, method->klass->image);
1798 g_assert (image_index < MAX_IMAGE_INDEX);
1799 g_assert (declaring->token);
1800 token = declaring->token;
1801 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1802 encode_value (image_index, p, &p);
1803 encode_value (token, p, &p);
1804 encode_generic_context (acfg, context, p, &p);
1806 } else if (token == 0) {
1807 /* This might be a method of a constructed type like int[,].Set */
1808 /* Obtain the token from information recorded by the JIT */
1809 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1811 image_index = get_image_index (acfg, ji->image);
1812 g_assert (image_index < MAX_IMAGE_INDEX);
1815 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1816 encode_value (image_index, p, &p);
1817 encode_value (token, p, &p);
1820 g_assert (method->klass->rank);
1822 /* Encode directly */
1823 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1824 encode_klass_ref (acfg, method->klass, p, &p);
1825 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1826 encode_value (0, p, &p);
1827 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1828 encode_value (1, p, &p);
1829 else if (!strcmp (method->name, "Get"))
1830 encode_value (2, p, &p);
1831 else if (!strcmp (method->name, "Address"))
1832 encode_value (3, p, &p);
1833 else if (!strcmp (method->name, "Set"))
1834 encode_value (4, p, &p);
1836 g_assert_not_reached ();
1839 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1840 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1846 compare_patches (gconstpointer a, gconstpointer b)
1850 i = (*(MonoJumpInfo**)a)->ip.i;
1851 j = (*(MonoJumpInfo**)b)->ip.i;
1865 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1868 static inline gboolean
1869 is_plt_patch (MonoJumpInfo *patch_info)
1871 switch (patch_info->type) {
1872 case MONO_PATCH_INFO_METHOD:
1873 case MONO_PATCH_INFO_INTERNAL_METHOD:
1874 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1875 case MONO_PATCH_INFO_ICALL_ADDR:
1876 case MONO_PATCH_INFO_CLASS_INIT:
1877 case MONO_PATCH_INFO_RGCTX_FETCH:
1878 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1879 case MONO_PATCH_INFO_MONITOR_ENTER:
1880 case MONO_PATCH_INFO_MONITOR_EXIT:
1881 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1889 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1893 if (is_plt_patch (patch_info)) {
1894 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1896 // FIXME: This breaks the calculation of final_got_size
1897 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1899 * Allocate a separate PLT slot for each such patch, since some plt
1900 * entries will refer to the method itself, and some will refer to the
1909 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1911 g_assert (!acfg->final_got_size);
1913 res = acfg->plt_offset;
1914 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1915 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1916 acfg->plt_offset ++;
1926 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1927 * JI could be found if it exists, otherwise allocates a new one.
1930 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1934 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1936 return got_offset - 1;
1938 got_offset = acfg->got_offset;
1939 acfg->got_offset ++;
1941 if (acfg->final_got_size)
1942 g_assert (got_offset < acfg->final_got_size);
1944 acfg->stats.got_slots ++;
1945 acfg->stats.got_slot_types [ji->type] ++;
1947 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1948 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1949 g_ptr_array_add (acfg->got_patches, ji);
1954 /* Add a method to the list of methods which need to be emitted */
1956 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1959 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1960 g_ptr_array_add (acfg->methods, method);
1961 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1962 acfg->nmethods = acfg->methods->len + 1;
1965 if (method->wrapper_type || extra)
1966 g_ptr_array_add (acfg->extra_methods, method);
1970 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1972 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1980 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1984 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1988 index = acfg->method_index;
1989 add_method_with_index (acfg, method, index, extra);
1991 /* FIXME: Fix quadratic behavior */
1992 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1994 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1996 acfg->method_index ++;
2002 add_method (MonoAotCompile *acfg, MonoMethod *method)
2004 return add_method_full (acfg, method, FALSE, 0);
2008 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2010 add_method_full (acfg, method, TRUE, 0);
2014 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2016 add_method_full (acfg, method, TRUE, depth);
2020 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2022 MonoAotCompile *acfg = user_data;
2023 MonoJitICallInfo *callinfo = value;
2024 MonoMethod *wrapper;
2030 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2031 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2034 add_method (acfg, wrapper);
2038 get_runtime_invoke_sig (MonoMethodSignature *sig)
2040 MonoMethodBuilder *mb;
2043 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2044 m = mono_mb_create_method (mb, sig, 16);
2045 return mono_marshal_get_runtime_invoke (m, FALSE);
2049 can_marshal_struct (MonoClass *klass)
2051 MonoClassField *field;
2052 gboolean can_marshal = TRUE;
2053 gpointer iter = NULL;
2055 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2058 /* Only allow a few field types to avoid asserts in the marshalling code */
2059 while ((field = mono_class_get_fields (klass, &iter))) {
2060 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2063 switch (field->type->type) {
2068 case MONO_TYPE_BOOLEAN:
2071 case MONO_TYPE_CHAR:
2079 case MONO_TYPE_STRING:
2081 case MONO_TYPE_VALUETYPE:
2082 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2083 can_marshal = FALSE;
2086 can_marshal = FALSE;
2092 /* Its hard to compute whenever these can be marshalled or not */
2093 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2100 add_wrappers (MonoAotCompile *acfg)
2102 MonoMethod *method, *m;
2104 MonoMethodSignature *sig, *csig;
2108 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2109 * so there is only one wrapper of a given type, or inlining their contents into their
2114 * FIXME: This depends on the fact that different wrappers have different
2118 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2120 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2121 gboolean skip = FALSE;
2123 method = mono_get_method (acfg->image, token, NULL);
2125 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2126 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2127 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2130 if (method->is_generic || method->klass->generic_container)
2133 /* Skip methods which can not be handled by get_runtime_invoke () */
2134 sig = mono_method_signature (method);
2135 if ((sig->ret->type == MONO_TYPE_PTR) ||
2136 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2139 for (j = 0; j < sig->param_count; j++) {
2140 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2144 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2145 if (!method->klass->contextbound) {
2146 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2147 gboolean has_nullable = FALSE;
2149 for (j = 0; j < sig->param_count; j++) {
2150 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2151 has_nullable = TRUE;
2154 if (info && !has_nullable) {
2155 /* Supported by the dynamic runtime-invoke wrapper */
2163 //printf ("%s\n", mono_method_full_name (method, TRUE));
2164 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2168 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2169 #ifdef MONO_ARCH_HAVE_TLS_GET
2170 MonoMethodDesc *desc;
2171 MonoMethod *orig_method;
2175 /* Runtime invoke wrappers */
2177 /* void runtime-invoke () [.cctor] */
2178 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2179 csig->ret = &mono_defaults.void_class->byval_arg;
2180 add_method (acfg, get_runtime_invoke_sig (csig));
2182 /* void runtime-invoke () [Finalize] */
2183 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2185 csig->ret = &mono_defaults.void_class->byval_arg;
2186 add_method (acfg, get_runtime_invoke_sig (csig));
2188 /* void runtime-invoke (string) [exception ctor] */
2189 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2191 csig->ret = &mono_defaults.void_class->byval_arg;
2192 csig->params [0] = &mono_defaults.string_class->byval_arg;
2193 add_method (acfg, get_runtime_invoke_sig (csig));
2195 /* void runtime-invoke (string, string) [exception ctor] */
2196 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2198 csig->ret = &mono_defaults.void_class->byval_arg;
2199 csig->params [0] = &mono_defaults.string_class->byval_arg;
2200 csig->params [1] = &mono_defaults.string_class->byval_arg;
2201 add_method (acfg, get_runtime_invoke_sig (csig));
2203 /* string runtime-invoke () [Exception.ToString ()] */
2204 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2206 csig->ret = &mono_defaults.string_class->byval_arg;
2207 add_method (acfg, get_runtime_invoke_sig (csig));
2209 /* void runtime-invoke (string, Exception) [exception ctor] */
2210 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2212 csig->ret = &mono_defaults.void_class->byval_arg;
2213 csig->params [0] = &mono_defaults.string_class->byval_arg;
2214 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2215 add_method (acfg, get_runtime_invoke_sig (csig));
2217 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2218 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2220 csig->ret = &(mono_class_from_name (
2221 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2222 csig->params [0] = &mono_defaults.string_class->byval_arg;
2223 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2224 add_method (acfg, get_runtime_invoke_sig (csig));
2226 /* runtime-invoke used by finalizers */
2227 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2229 /* This is used by mono_runtime_capture_context () */
2230 method = mono_get_context_capture_method ();
2232 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2234 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2235 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2238 /* JIT icall wrappers */
2239 /* FIXME: locking */
2240 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2243 add_method (acfg, mono_marshal_get_stelemref ());
2245 #ifdef MONO_ARCH_HAVE_TLS_GET
2246 /* Managed Allocators */
2247 nallocators = mono_gc_get_managed_allocator_types ();
2248 for (i = 0; i < nallocators; ++i) {
2249 m = mono_gc_get_managed_allocator_by_type (i);
2251 add_method (acfg, m);
2254 /* Monitor Enter/Exit */
2255 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2256 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2257 g_assert (orig_method);
2258 mono_method_desc_free (desc);
2259 method = mono_monitor_get_fast_path (orig_method);
2261 add_method (acfg, method);
2263 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2264 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2265 g_assert (orig_method);
2266 mono_method_desc_free (desc);
2267 method = mono_monitor_get_fast_path (orig_method);
2269 add_method (acfg, method);
2274 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2275 * we use the original method instead at runtime.
2276 * Since full-aot doesn't support remoting, this is not a problem.
2279 /* remoting-invoke wrappers */
2280 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2281 MonoMethodSignature *sig;
2283 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2284 method = mono_get_method (acfg->image, token, NULL);
2286 sig = mono_method_signature (method);
2288 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2289 m = mono_marshal_get_remoting_invoke_with_check (method);
2291 add_method (acfg, m);
2296 /* delegate-invoke wrappers */
2297 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2300 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2301 klass = mono_class_get (acfg->image, token);
2303 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2304 method = mono_get_delegate_invoke (klass);
2306 m = mono_marshal_get_delegate_invoke (method, NULL);
2308 add_method (acfg, m);
2310 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2311 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2313 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2314 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2318 /* Synchronized wrappers */
2319 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2320 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2321 method = mono_get_method (acfg->image, token, NULL);
2323 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2324 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2327 /* pinvoke wrappers */
2328 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2330 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2332 method = mono_get_method (acfg->image, token, NULL);
2334 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2335 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2336 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2340 /* native-to-managed wrappers */
2341 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2343 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2344 MonoCustomAttrInfo *cattr;
2347 method = mono_get_method (acfg->image, token, NULL);
2350 * Only generate native-to-managed wrappers for methods which have an
2351 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2352 * name to avoid defining a new assembly to contain it.
2354 cattr = mono_custom_attrs_from_method (method);
2357 for (j = 0; j < cattr->num_attrs; ++j)
2358 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2360 if (j < cattr->num_attrs) {
2361 MonoCustomAttrEntry *e = &cattr->attrs [j];
2362 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2363 const char *p = (const char*)e->data;
2369 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2371 g_assert (sig->param_count == 1);
2372 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2375 * Decode the cattr manually since we can't create objects
2376 * during aot compilation.
2382 /* From load_cattr_value () in reflection.c */
2383 slen = mono_metadata_decode_value (p, &p);
2384 n = g_memdup (p, slen + 1);
2386 t = mono_reflection_type_from_name (n, acfg->image);
2390 klass = mono_class_from_mono_type (t);
2391 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2393 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, NULL));
2397 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2398 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2399 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2403 /* StructureToPtr/PtrToStructure wrappers */
2404 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2407 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2408 klass = mono_class_get (acfg->image, token);
2410 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2411 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2412 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2418 has_type_vars (MonoClass *klass)
2420 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2423 return has_type_vars (klass->element_class);
2424 if (klass->generic_class) {
2425 MonoGenericContext *context = &klass->generic_class->context;
2426 if (context->class_inst) {
2429 for (i = 0; i < context->class_inst->type_argc; ++i)
2430 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2438 method_has_type_vars (MonoMethod *method)
2440 if (has_type_vars (method->klass))
2443 if (method->is_inflated) {
2444 MonoGenericContext *context = mono_method_get_context (method);
2445 if (context->method_inst) {
2448 for (i = 0; i < context->method_inst->type_argc; ++i)
2449 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2457 * add_generic_class:
2459 * Add all methods of a generic class.
2462 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2467 mono_class_init (klass);
2469 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2472 if (has_type_vars (klass))
2475 if (!klass->generic_class && !klass->rank)
2479 while ((method = mono_class_get_methods (klass, &iter))) {
2480 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2484 if (method->is_generic)
2489 * FIXME: Instances which are referenced by these methods are not added,
2490 * for example Array.Resize<int> for List<int>.Add ().
2492 add_extra_method (acfg, method);
2495 if (klass->delegate) {
2496 method = mono_get_delegate_invoke (klass);
2498 method = mono_marshal_get_delegate_invoke (method, NULL);
2500 add_method (acfg, method);
2504 * For ICollection<T>, add instances of the helper methods
2505 * in Array, since a T[] could be cast to ICollection<T>.
2507 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2508 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2509 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2510 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2514 if (!strcmp (klass->name, "IEnumerator`1"))
2515 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2517 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2519 /* Add the T[]/InternalEnumerator class */
2520 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2524 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2525 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2529 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2530 add_generic_class (acfg, nclass);
2534 while ((method = mono_class_get_methods (array_class, &iter))) {
2535 if (strstr (method->name, name_prefix)) {
2536 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2537 add_extra_method (acfg, m);
2541 g_free (name_prefix);
2544 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2545 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2546 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2547 MonoClass *icomparable, *gcomparer;
2548 MonoGenericContext ctx;
2549 MonoType *args [16];
2551 memset (&ctx, 0, sizeof (ctx));
2553 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2554 g_assert (icomparable);
2555 args [0] = &tclass->byval_arg;
2556 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2558 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2559 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2560 g_assert (gcomparer);
2561 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2567 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2570 MonoGenericContext ctx;
2571 MonoType *args [16];
2573 memset (&ctx, 0, sizeof (ctx));
2575 for (i = 0; i < ninsts; ++i) {
2576 args [0] = insts [i];
2577 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2578 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2583 * add_generic_instances:
2585 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2588 add_generic_instances (MonoAotCompile *acfg)
2593 MonoMethodHeader *header;
2594 MonoMethodSignature *sig;
2595 MonoGenericContext *context;
2597 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2598 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2599 method = mono_get_method (acfg->image, token, NULL);
2601 if (method->klass->image != acfg->image)
2604 context = mono_method_get_context (method);
2606 if (context && ((context->class_inst && context->class_inst->is_open)))
2610 * For open methods, create an instantiation which can be passed to the JIT.
2611 * FIXME: Handle class_inst as well.
2613 if (context && context->method_inst && context->method_inst->is_open) {
2614 MonoGenericContext shared_context;
2615 MonoGenericInst *inst;
2616 MonoType **type_argv;
2618 MonoMethod *declaring_method;
2619 gboolean supported = TRUE;
2621 /* Check that the context doesn't contain open constructed types */
2622 if (context->class_inst) {
2623 inst = context->class_inst;
2624 for (i = 0; i < inst->type_argc; ++i) {
2625 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2627 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2631 if (context->method_inst) {
2632 inst = context->method_inst;
2633 for (i = 0; i < inst->type_argc; ++i) {
2634 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2636 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2644 memset (&shared_context, 0, sizeof (MonoGenericContext));
2646 inst = context->class_inst;
2648 type_argv = g_new0 (MonoType*, inst->type_argc);
2649 for (i = 0; i < inst->type_argc; ++i) {
2650 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2651 type_argv [i] = &mono_defaults.object_class->byval_arg;
2653 type_argv [i] = inst->type_argv [i];
2656 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2660 inst = context->method_inst;
2662 type_argv = g_new0 (MonoType*, inst->type_argc);
2663 for (i = 0; i < inst->type_argc; ++i) {
2664 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2665 type_argv [i] = &mono_defaults.object_class->byval_arg;
2667 type_argv [i] = inst->type_argv [i];
2670 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2674 if (method->is_generic || method->klass->generic_container)
2675 declaring_method = method;
2677 declaring_method = mono_method_get_declaring_generic_method (method);
2679 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2683 * If the method is fully sharable, it was already added in place of its
2684 * generic definition.
2686 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2690 * FIXME: Partially shared methods are not shared here, so we end up with
2691 * many identical methods.
2693 add_extra_method (acfg, method);
2696 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2699 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2701 klass = mono_class_get (acfg->image, token);
2702 if (!klass || klass->rank)
2705 add_generic_class (acfg, klass);
2708 /* Add types of args/locals */
2709 for (i = 0; i < acfg->methods->len; ++i) {
2712 method = g_ptr_array_index (acfg->methods, i);
2714 sig = mono_method_signature (method);
2717 for (j = 0; j < sig->param_count; ++j)
2718 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2719 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2722 header = mono_method_get_header (method);
2725 for (j = 0; j < header->num_locals; ++j)
2726 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2727 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2731 if (acfg->image == mono_defaults.corlib) {
2733 MonoType *insts [256];
2736 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2737 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2738 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2739 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2740 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2741 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2742 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2743 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2744 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2745 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2746 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2747 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2749 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2750 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2752 add_instances_of (acfg, klass, insts, ninsts);
2753 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2755 add_instances_of (acfg, klass, insts, ninsts);
2757 /* Add instances of the array generic interfaces for primitive types */
2758 /* This will add instances of the InternalArray_ helper methods in Array too */
2759 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2761 add_instances_of (acfg, klass, insts, ninsts);
2762 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2764 add_instances_of (acfg, klass, insts, ninsts);
2765 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2767 add_instances_of (acfg, klass, insts, ninsts);
2770 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2771 * used for all instances of GetGenericValueImpl by the AOT runtime.
2774 MonoGenericContext ctx;
2775 MonoType *args [16];
2776 MonoMethod *get_method;
2777 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2779 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2782 memset (&ctx, 0, sizeof (ctx));
2783 args [0] = &mono_defaults.object_class->byval_arg;
2784 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2785 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2792 * is_direct_callable:
2794 * Return whenever the method identified by JI is directly callable without
2795 * going through the PLT.
2798 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2800 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2801 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2803 gboolean direct_callable = TRUE;
2805 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2806 direct_callable = FALSE;
2807 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2808 // FIXME: Maybe call the wrapper directly ?
2809 direct_callable = FALSE;
2811 if (direct_callable)
2820 * emit_and_reloc_code:
2822 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2823 * is true, calls are made through the GOT too. This is used for emitting trampolines
2824 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2825 * since trampolines are needed to make PTL work.
2828 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2830 int i, pindex, start_index, method_index;
2832 MonoJumpInfo *patch_info;
2833 MonoMethodHeader *header;
2834 gboolean skip, direct_call;
2836 char direct_call_target [128];
2839 header = mono_method_get_header (method);
2841 method_index = get_method_index (acfg, method);
2844 /* Collect and sort relocations */
2845 patches = g_ptr_array_new ();
2846 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2847 g_ptr_array_add (patches, patch_info);
2848 g_ptr_array_sort (patches, compare_patches);
2851 for (i = 0; i < code_len; i++) {
2853 for (pindex = start_index; pindex < patches->len; ++pindex) {
2854 patch_info = g_ptr_array_index (patches, pindex);
2855 if (patch_info->ip.i >= i)
2859 #ifdef MONO_ARCH_AOT_SUPPORTED
2861 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2862 start_index = pindex;
2864 switch (patch_info->type) {
2865 case MONO_PATCH_INFO_NONE:
2867 case MONO_PATCH_INFO_GOT_OFFSET: {
2870 arch_emit_got_offset (acfg, code + i, &code_size);
2873 patch_info->type = MONO_PATCH_INFO_NONE;
2878 * If this patch is a call, try emitting a direct call instead of
2879 * through a PLT entry. This is possible if the called method is in
2880 * the same assembly and requires no initialization.
2882 direct_call = FALSE;
2883 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2884 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2885 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2886 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2888 sprintf (direct_call_target, callee_cfg->asm_symbol);
2889 patch_info->type = MONO_PATCH_INFO_NONE;
2890 acfg->stats.direct_calls ++;
2893 acfg->stats.all_calls ++;
2896 if (!got_only && !direct_call) {
2897 int plt_offset = get_plt_offset (acfg, patch_info);
2898 if (plt_offset != -1) {
2899 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2901 sprintf (direct_call_target, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
2903 /* Nullify the patch */
2904 patch_info->type = MONO_PATCH_INFO_NONE;
2911 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2916 got_slot = get_got_offset (acfg, patch_info);
2918 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2925 #endif /* MONO_ARCH_AOT_SUPPORTED */
2928 /* Find next patch */
2930 for (pindex = start_index; pindex < patches->len; ++pindex) {
2931 patch_info = g_ptr_array_index (patches, pindex);
2932 if (patch_info->ip.i >= i)
2936 /* Try to emit multiple bytes at once */
2937 if (pindex < patches->len && patch_info->ip.i > i) {
2938 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2939 i = patch_info->ip.i - 1;
2941 emit_bytes (acfg, code + i, 1);
2950 * Modify SYMBOL so it only includes characters permissible in symbols.
2953 sanitize_symbol (char *symbol)
2955 int i, len = strlen (symbol);
2957 for (i = 0; i < len; ++i)
2958 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2963 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2965 char *name1, *name2, *cached;
2966 int i, j, len, count;
2968 name1 = mono_method_full_name (method, TRUE);
2969 len = strlen (name1);
2970 name2 = malloc (strlen (prefix) + len + 16);
2971 memcpy (name2, prefix, strlen (prefix));
2972 j = strlen (prefix);
2973 for (i = 0; i < len; ++i) {
2974 if (isalnum (name1 [i])) {
2975 name2 [j ++] = name1 [i];
2976 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2978 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2981 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2990 while (g_hash_table_lookup (cache, name2)) {
2991 sprintf (name2 + j, "_%d", count);
2995 cached = g_strdup (name2);
2996 g_hash_table_insert (cache, cached, cached);
3002 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3007 char *debug_sym = NULL;
3009 int func_alignment = AOT_FUNC_ALIGNMENT;
3010 MonoMethodHeader *header;
3012 method = cfg->orig_method;
3013 code = cfg->native_code;
3014 header = mono_method_get_header (method);
3016 method_index = get_method_index (acfg, method);
3018 /* Make the labels local */
3019 sprintf (symbol, "%s", cfg->asm_symbol);
3021 emit_section_change (acfg, ".text", 0);
3022 emit_alignment (acfg, func_alignment);
3023 emit_label (acfg, symbol);
3025 if (acfg->aot_opts.write_symbols) {
3027 * Write a C style symbol for every method, this has two uses:
3028 * - it works on platforms where the dwarf debugging info is not
3030 * - it allows the setting of breakpoints of aot-ed methods.
3032 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3034 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3035 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3036 emit_label (acfg, debug_sym);
3039 if (cfg->verbose_level > 0)
3040 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3042 acfg->stats.code_size += cfg->code_len;
3044 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3046 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3050 if (acfg->aot_opts.write_symbols) {
3051 emit_symbol_size (acfg, debug_sym, ".");
3055 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3056 emit_label (acfg, symbol);
3062 * Encode PATCH_INFO into its disk representation.
3065 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3069 switch (patch_info->type) {
3070 case MONO_PATCH_INFO_NONE:
3072 case MONO_PATCH_INFO_IMAGE:
3073 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3075 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3077 case MONO_PATCH_INFO_METHOD_REL:
3078 encode_value ((gint)patch_info->data.offset, p, &p);
3080 case MONO_PATCH_INFO_SWITCH: {
3081 gpointer *table = (gpointer *)patch_info->data.table->table;
3084 encode_value (patch_info->data.table->table_size, p, &p);
3085 for (k = 0; k < patch_info->data.table->table_size; k++)
3086 encode_value ((int)(gssize)table [k], p, &p);
3089 case MONO_PATCH_INFO_METHODCONST:
3090 case MONO_PATCH_INFO_METHOD:
3091 case MONO_PATCH_INFO_METHOD_JUMP:
3092 case MONO_PATCH_INFO_ICALL_ADDR:
3093 case MONO_PATCH_INFO_METHOD_RGCTX:
3094 encode_method_ref (acfg, patch_info->data.method, p, &p);
3096 case MONO_PATCH_INFO_INTERNAL_METHOD:
3097 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3098 guint32 len = strlen (patch_info->data.name);
3100 encode_value (len, p, &p);
3102 memcpy (p, patch_info->data.name, len);
3107 case MONO_PATCH_INFO_LDSTR: {
3108 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3109 guint32 token = patch_info->data.token->token;
3110 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3111 encode_value (image_index, p, &p);
3112 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3115 case MONO_PATCH_INFO_RVA:
3116 case MONO_PATCH_INFO_DECLSEC:
3117 case MONO_PATCH_INFO_LDTOKEN:
3118 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3119 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3120 encode_value (patch_info->data.token->token, p, &p);
3121 encode_value (patch_info->data.token->has_context, p, &p);
3122 if (patch_info->data.token->has_context)
3123 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3125 case MONO_PATCH_INFO_EXC_NAME: {
3126 MonoClass *ex_class;
3129 mono_class_from_name (mono_defaults.exception_class->image,
3130 "System", patch_info->data.target);
3131 g_assert (ex_class);
3132 encode_klass_ref (acfg, ex_class, p, &p);
3135 case MONO_PATCH_INFO_R4:
3136 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3138 case MONO_PATCH_INFO_R8:
3139 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3140 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3142 case MONO_PATCH_INFO_VTABLE:
3143 case MONO_PATCH_INFO_CLASS:
3144 case MONO_PATCH_INFO_IID:
3145 case MONO_PATCH_INFO_ADJUSTED_IID:
3146 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3148 case MONO_PATCH_INFO_CLASS_INIT:
3149 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3150 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3152 case MONO_PATCH_INFO_FIELD:
3153 case MONO_PATCH_INFO_SFLDA:
3154 encode_field_info (acfg, patch_info->data.field, p, &p);
3156 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3158 case MONO_PATCH_INFO_RGCTX_FETCH: {
3159 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3161 encode_method_ref (acfg, entry->method, p, &p);
3162 encode_value (entry->in_mrgctx, p, &p);
3163 encode_value (entry->info_type, p, &p);
3164 encode_value (entry->data->type, p, &p);
3165 encode_patch (acfg, entry->data, p, &p);
3168 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3169 case MONO_PATCH_INFO_MONITOR_ENTER:
3170 case MONO_PATCH_INFO_MONITOR_EXIT:
3171 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3173 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3174 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3175 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3178 g_warning ("unable to handle jump info %d", patch_info->type);
3179 g_assert_not_reached ();
3186 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3189 guint32 pindex, offset;
3190 MonoJumpInfo *patch_info;
3192 encode_value (n_patches, p, &p);
3194 for (pindex = 0; pindex < patches->len; ++pindex) {
3195 patch_info = g_ptr_array_index (patches, pindex);
3197 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3201 offset = get_got_offset (acfg, patch_info);
3202 encode_value (offset, p, &p);
3209 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3213 int pindex, buf_size, n_patches;
3216 MonoJumpInfo *patch_info;
3217 MonoMethodHeader *header;
3218 guint32 method_index;
3220 guint32 first_got_offset;
3222 method = cfg->orig_method;
3223 code = cfg->native_code;
3224 header = mono_method_get_header (method);
3226 method_index = get_method_index (acfg, method);
3228 /* Sort relocations */
3229 patches = g_ptr_array_new ();
3230 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3231 g_ptr_array_add (patches, patch_info);
3232 g_ptr_array_sort (patches, compare_patches);
3234 first_got_offset = acfg->cfgs [method_index]->got_offset;
3236 /**********************/
3237 /* Encode method info */
3238 /**********************/
3240 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3241 p = buf = g_malloc (buf_size);
3243 if (mono_class_get_cctor (method->klass))
3244 encode_klass_ref (acfg, method->klass, p, &p);
3246 /* Not needed when loading the method */
3247 encode_value (0, p, &p);
3250 if (cfg->opt & MONO_OPT_SHARED) {
3251 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3252 for (l = cfg->ldstr_list; l; l = l->next) {
3253 encode_value ((long)l->data, p, &p);
3257 /* Used only in shared mode */
3258 g_assert (!cfg->ldstr_list);
3261 for (pindex = 0; pindex < patches->len; ++pindex) {
3262 patch_info = g_ptr_array_index (patches, pindex);
3264 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3265 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3266 patch_info->type = MONO_PATCH_INFO_NONE;
3271 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3272 /* Stored in a GOT slot initialized at module load time */
3273 patch_info->type = MONO_PATCH_INFO_NONE;
3277 if (is_plt_patch (patch_info)) {
3278 /* Calls are made through the PLT */
3279 patch_info->type = MONO_PATCH_INFO_NONE;
3287 g_assert (cfg->has_got_slots);
3289 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3291 acfg->stats.info_size += p - buf;
3293 g_assert (p - buf < buf_size);
3295 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3300 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3302 guint32 cache_index;
3305 /* Reuse the unwind module to canonize and store unwind info entries */
3306 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3308 /* Use +/- 1 to distinguish 0s from missing entries */
3309 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3317 * It would be easier to use assembler symbols, but the caller needs an
3320 offset = acfg->unwind_info_offset;
3321 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3322 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3325 encode_value (encoded_len, p, &p);
3327 acfg->unwind_info_offset += encoded_len + (p - buf);
3333 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3336 int i, k, buf_size, method_index;
3337 guint32 debug_info_size;
3339 MonoMethodHeader *header;
3340 guint8 *p, *buf, *debug_info;
3341 MonoJitInfo *jinfo = cfg->jit_info;
3343 gboolean use_unwind_ops = FALSE;
3344 MonoSeqPointInfo *seq_points;
3346 method = cfg->orig_method;
3347 code = cfg->native_code;
3348 header = mono_method_get_header (method);
3350 method_index = get_method_index (acfg, method);
3352 if (!acfg->aot_opts.nodebug) {
3353 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3356 debug_info_size = 0;
3359 seq_points = cfg->seq_point_info;
3361 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3362 p = buf = g_malloc (buf_size);
3364 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3365 use_unwind_ops = cfg->unwind_ops != NULL;
3368 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0);
3370 encode_value (flags, p, &p);
3372 if (use_unwind_ops) {
3373 guint32 encoded_len;
3377 * This is a duplicate of the data in the .debug_frame section, but that
3378 * section cannot be accessed using the dl interface.
3380 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3381 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3384 encode_value (jinfo->used_regs, p, &p);
3387 /*Encode the number of holes before the number of clauses to make decoding easier*/
3388 if (jinfo->has_try_block_holes) {
3389 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3390 encode_value (table->num_holes, p, &p);
3393 /* Exception table */
3394 if (cfg->compile_llvm) {
3395 /* The assembly might be CIL stripped so emit the data ourselves */
3396 if (header->num_clauses)
3397 encode_value (header->num_clauses, p, &p);
3399 for (k = 0; k < header->num_clauses; ++k) {
3400 MonoExceptionClause *clause;
3402 clause = &header->clauses [k];
3404 encode_value (clause->flags, p, &p);
3405 if (clause->data.catch_class) {
3406 encode_value (1, p, &p);
3407 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3409 encode_value (0, p, &p);
3413 if (jinfo->num_clauses)
3414 encode_value (jinfo->num_clauses, p, &p);
3416 for (k = 0; k < jinfo->num_clauses; ++k) {
3417 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3419 encode_value (ei->flags, p, &p);
3420 encode_value (ei->exvar_offset, p, &p);
3422 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3423 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3425 if (ei->data.catch_class) {
3426 encode_value (1, p, &p);
3427 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3429 encode_value (0, p, &p);
3433 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3434 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3435 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3439 if (jinfo->has_generic_jit_info) {
3440 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3442 encode_value (gi->has_this ? 1 : 0, p, &p);
3443 encode_value (gi->this_reg, p, &p);
3444 encode_value (gi->this_offset, p, &p);
3447 * Need to encode jinfo->method too, since it is not equal to 'method'
3448 * when using generic sharing.
3450 encode_method_ref (acfg, jinfo->method, p, &p);
3453 if (jinfo->has_try_block_holes) {
3454 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3455 for (i = 0; i < table->num_holes; ++i) {
3456 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3457 encode_value (hole->clause, p, &p);
3458 encode_value (hole->length, p, &p);
3459 encode_value (hole->offset, p, &p);
3464 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3466 encode_value (seq_points->len, p, &p);
3467 last_il_offset = last_native_offset = 0;
3468 for (i = 0; i < seq_points->len; ++i) {
3469 SeqPoint *sp = &seq_points->seq_points [i];
3470 il_offset = sp->il_offset;
3471 native_offset = sp->native_offset;
3472 encode_value (il_offset - last_il_offset, p, &p);
3473 encode_value (native_offset - last_native_offset, p, &p);
3474 last_il_offset = il_offset;
3475 last_native_offset = native_offset;
3477 encode_value (sp->next_len, p, &p);
3478 for (j = 0; j < sp->next_len; ++j)
3479 encode_value (sp->next [j], p, &p);
3484 g_assert (debug_info_size < buf_size);
3486 encode_value (debug_info_size, p, &p);
3487 if (debug_info_size) {
3488 memcpy (p, debug_info, debug_info_size);
3489 p += debug_info_size;
3490 g_free (debug_info);
3493 acfg->stats.ex_info_size += p - buf;
3495 g_assert (p - buf < buf_size);
3498 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3503 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3505 MonoClass *klass = mono_class_get (acfg->image, token);
3507 int i, buf_size, res;
3508 gboolean no_special_static, cant_encode;
3509 gpointer iter = NULL;
3511 buf_size = 10240 + (klass->vtable_size * 16);
3512 p = buf = g_malloc (buf_size);
3516 mono_class_init (klass);
3518 mono_class_get_nested_types (klass, &iter);
3519 g_assert (klass->nested_classes_inited);
3521 mono_class_setup_vtable (klass);
3524 * Emit all the information which is required for creating vtables so
3525 * the runtime does not need to create the MonoMethod structures which
3526 * take up a lot of space.
3529 no_special_static = !mono_class_has_special_static_fields (klass);
3531 /* Check whenever we have enough info to encode the vtable */
3532 cant_encode = FALSE;
3533 for (i = 0; i < klass->vtable_size; ++i) {
3534 MonoMethod *cm = klass->vtable [i];
3536 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3540 if (klass->generic_container || cant_encode) {
3541 encode_value (-1, p, &p);
3543 encode_value (klass->vtable_size, p, &p);
3544 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);
3545 if (klass->has_cctor)
3546 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3547 if (klass->has_finalize)
3548 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3550 encode_value (klass->instance_size, p, &p);
3551 encode_value (mono_class_data_size (klass), p, &p);
3552 encode_value (klass->packing_size, p, &p);
3553 encode_value (klass->min_align, p, &p);
3555 for (i = 0; i < klass->vtable_size; ++i) {
3556 MonoMethod *cm = klass->vtable [i];
3559 encode_method_ref (acfg, cm, p, &p);
3561 encode_value (0, p, &p);
3565 acfg->stats.class_info_size += p - buf;
3567 g_assert (p - buf < buf_size);
3568 res = add_to_blob (acfg, buf, p - buf);
3575 * Calls made from AOTed code are routed through a table of jumps similar to the
3576 * ELF PLT (Program Linkage Table). The differences are the following:
3577 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3578 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3579 * jumps. This means the jumps need to be patched when the address of the callee is
3580 * known. Initially the PLT entries jump to code which transfers control to the
3581 * AOT runtime through the first PLT entry.
3584 emit_plt (MonoAotCompile *acfg)
3590 cache = g_hash_table_new (g_str_hash, g_str_equal);
3593 sprintf (symbol, "plt");
3595 emit_section_change (acfg, ".text", 0);
3596 emit_global (acfg, symbol, TRUE);
3598 /* This section will be made read-write by the AOT loader */
3599 emit_alignment (acfg, mono_pagesize ());
3601 emit_alignment (acfg, 16);
3603 emit_label (acfg, symbol);
3604 emit_label (acfg, acfg->plt_symbol);
3606 for (i = 0; i < acfg->plt_offset; ++i) {
3608 char *debug_sym = NULL;
3611 sprintf (label, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, i);
3615 * If the target is directly callable, alias the plt symbol to point to
3617 * FIXME: Use this to simplify emit_and_reloc_code ().
3618 * FIXME: Avoid the got slot.
3619 * FIXME: Add support to the binary writer.
3621 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3622 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3623 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3624 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3629 emit_label (acfg, label);
3631 if (acfg->aot_opts.write_symbols) {
3632 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3636 case MONO_PATCH_INFO_METHOD:
3637 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3639 case MONO_PATCH_INFO_INTERNAL_METHOD:
3640 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3642 case MONO_PATCH_INFO_CLASS_INIT:
3643 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3644 sanitize_symbol (debug_sym);
3646 case MONO_PATCH_INFO_RGCTX_FETCH:
3647 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3649 case MONO_PATCH_INFO_ICALL_ADDR: {
3650 char *s = get_debug_sym (ji->data.method, "", cache);
3652 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3656 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3657 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3659 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3660 debug_sym = g_strdup_printf ("plt__generic_class_init");
3667 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3668 emit_label (acfg, debug_sym);
3674 * The first plt entry is used to transfer code to the AOT loader.
3676 arch_emit_plt_entry (acfg, i);
3679 emit_symbol_size (acfg, debug_sym, ".");
3684 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3686 sprintf (symbol, "plt_end");
3687 emit_global (acfg, symbol, TRUE);
3688 emit_label (acfg, symbol);
3690 g_hash_table_destroy (cache);
3693 static G_GNUC_UNUSED void
3694 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3695 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3697 char start_symbol [256];
3699 guint32 buf_size, info_offset;
3700 MonoJumpInfo *patch_info;
3706 sprintf (start_symbol, "%s", name);
3708 emit_section_change (acfg, ".text", 0);
3709 emit_global (acfg, start_symbol, TRUE);
3710 emit_alignment (acfg, 16);
3711 emit_label (acfg, start_symbol);
3713 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3714 emit_label (acfg, symbol);
3717 * The code should access everything through the GOT, so we pass
3720 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3722 emit_symbol_size (acfg, start_symbol, ".");
3726 /* Sort relocations */
3727 patches = g_ptr_array_new ();
3728 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3729 if (patch_info->type != MONO_PATCH_INFO_NONE)
3730 g_ptr_array_add (patches, patch_info);
3731 g_ptr_array_sort (patches, compare_patches);
3733 buf_size = patches->len * 128 + 128;
3734 buf = g_malloc (buf_size);
3737 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3738 g_assert (p - buf < buf_size);
3740 sprintf (symbol, "%s_p", name);
3742 info_offset = add_to_blob (acfg, buf, p - buf);
3744 emit_section_change (acfg, ".text", 0);
3745 emit_global (acfg, symbol, FALSE);
3746 emit_label (acfg, symbol);
3748 emit_int32 (acfg, info_offset);
3750 /* Emit debug info */
3754 sprintf (symbol, "%s", name);
3755 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3758 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3763 emit_trampolines (MonoAotCompile *acfg)
3766 int i, tramp_got_offset;
3767 MonoAotTrampoline ntype;
3768 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3776 if (!acfg->aot_opts.full_aot)
3779 g_assert (acfg->image->assembly);
3781 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3782 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3783 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3785 * Emit the generic trampolines.
3787 * We could save some code by treating the generic trampolines as a wrapper
3788 * method, but that approach has its own complexities, so we choose the simpler
3791 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3792 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3794 /* Emit trampoline code */
3796 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3798 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3801 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3802 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3803 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3804 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3805 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3806 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3807 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3810 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3811 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3813 /* Emit the exception related code pieces */
3814 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3815 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3816 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3817 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3818 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3819 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3820 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3821 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3822 #ifdef MONO_ARCH_HAVE_THROW_EXCEPTION_BY_NAME
3823 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3824 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3826 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3827 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3829 #if defined(TARGET_AMD64)
3830 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3831 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3834 for (i = 0; i < 128; ++i) {
3837 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3838 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3839 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3840 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3842 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3843 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3844 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3845 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3851 /* delegate_invoke_impl trampolines */
3852 l = mono_arch_get_delegate_invoke_impls ();
3854 MonoAotTrampInfo *info = l->data;
3856 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3861 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3863 /* Emit trampolines which are numerous */
3866 * These include the following:
3867 * - specific trampolines
3868 * - static rgctx invoke trampolines
3870 * These trampolines have the same code, they are parameterized by GOT
3872 * They are defined in this file, in the arch_... routines instead of
3873 * in tramp-<ARCH>.c, since it is easier to do it this way.
3877 * When running in aot-only mode, we can't create specific trampolines at
3878 * runtime, so we create a few, and save them in the AOT file.
3879 * Normal trampolines embed their argument as a literal inside the
3880 * trampoline code, we can't do that here, so instead we embed an offset
3881 * which needs to be added to the trampoline address to get the address of
3882 * the GOT slot which contains the argument value.
3883 * The generated trampolines jump to the generic trampolines using another
3884 * GOT slot, which will be setup by the AOT loader to point to the
3885 * generic trampoline code of the given type.
3889 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3893 emit_section_change (acfg, ".text", 0);
3895 tramp_got_offset = acfg->got_offset;
3897 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3899 case MONO_AOT_TRAMP_SPECIFIC:
3900 sprintf (symbol, "specific_trampolines");
3902 case MONO_AOT_TRAMP_STATIC_RGCTX:
3903 sprintf (symbol, "static_rgctx_trampolines");
3905 case MONO_AOT_TRAMP_IMT_THUNK:
3906 sprintf (symbol, "imt_thunks");
3909 g_assert_not_reached ();
3912 emit_global (acfg, symbol, TRUE);
3913 emit_alignment (acfg, 16);
3914 emit_label (acfg, symbol);
3916 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3918 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3922 case MONO_AOT_TRAMP_SPECIFIC:
3923 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3924 tramp_got_offset += 2;
3926 case MONO_AOT_TRAMP_STATIC_RGCTX:
3927 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3928 tramp_got_offset += 2;
3930 case MONO_AOT_TRAMP_IMT_THUNK:
3931 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3932 tramp_got_offset += 1;
3935 g_assert_not_reached ();
3938 if (!acfg->trampoline_size [ntype]) {
3939 g_assert (tramp_size);
3940 acfg->trampoline_size [ntype] = tramp_size;
3945 /* Reserve some entries at the end of the GOT for our use */
3946 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3949 acfg->got_offset += acfg->num_trampoline_got_entries;
3953 str_begins_with (const char *str1, const char *str2)
3955 int len = strlen (str2);
3956 return strncmp (str1, str2, len) == 0;
3960 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3962 gchar **args, **ptr;
3964 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3965 for (ptr = args; ptr && *ptr; ptr ++) {
3966 const char *arg = *ptr;
3968 if (str_begins_with (arg, "outfile=")) {
3969 opts->outfile = g_strdup (arg + strlen ("outfile="));
3970 } else if (str_begins_with (arg, "save-temps")) {
3971 opts->save_temps = TRUE;
3972 } else if (str_begins_with (arg, "keep-temps")) {
3973 opts->save_temps = TRUE;
3974 } else if (str_begins_with (arg, "write-symbols")) {
3975 opts->write_symbols = TRUE;
3976 } else if (str_begins_with (arg, "metadata-only")) {
3977 opts->metadata_only = TRUE;
3978 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3979 opts->bind_to_runtime_version = TRUE;
3980 } else if (str_begins_with (arg, "full")) {
3981 opts->full_aot = TRUE;
3982 } else if (str_begins_with (arg, "threads=")) {
3983 opts->nthreads = atoi (arg + strlen ("threads="));
3984 } else if (str_begins_with (arg, "static")) {
3985 opts->static_link = TRUE;
3986 opts->no_dlsym = TRUE;
3987 } else if (str_begins_with (arg, "asmonly")) {
3988 opts->asm_only = TRUE;
3989 } else if (str_begins_with (arg, "asmwriter")) {
3990 opts->asm_writer = TRUE;
3991 } else if (str_begins_with (arg, "nodebug")) {
3992 opts->nodebug = TRUE;
3993 } else if (str_begins_with (arg, "ntrampolines=")) {
3994 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3995 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
3996 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
3997 } else if (str_begins_with (arg, "nimt-trampolines=")) {
3998 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
3999 } else if (str_begins_with (arg, "autoreg")) {
4000 opts->autoreg = TRUE;
4001 } else if (str_begins_with (arg, "tool-prefix=")) {
4002 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4003 } else if (str_begins_with (arg, "soft-debug")) {
4004 opts->soft_debug = TRUE;
4005 } else if (str_begins_with (arg, "print-skipped")) {
4006 opts->print_skipped_methods = TRUE;
4007 } else if (str_begins_with (arg, "stats")) {
4010 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4019 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4021 MonoMethod *method = (MonoMethod*)key;
4022 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4023 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4024 MonoAotCompile *acfg = user_data;
4026 new_ji->image = ji->image;
4027 new_ji->token = ji->token;
4028 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4032 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4034 if (klass->type_token)
4036 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4039 return can_encode_class (acfg, klass->element_class);
4044 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4046 switch (patch_info->type) {
4047 case MONO_PATCH_INFO_METHOD:
4048 case MONO_PATCH_INFO_METHODCONST: {
4049 MonoMethod *method = patch_info->data.method;
4051 if (method->wrapper_type) {
4052 switch (method->wrapper_type) {
4053 case MONO_WRAPPER_NONE:
4054 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4055 case MONO_WRAPPER_XDOMAIN_INVOKE:
4056 case MONO_WRAPPER_STFLD:
4057 case MONO_WRAPPER_LDFLD:
4058 case MONO_WRAPPER_LDFLDA:
4059 case MONO_WRAPPER_LDFLD_REMOTE:
4060 case MONO_WRAPPER_STFLD_REMOTE:
4061 case MONO_WRAPPER_STELEMREF:
4062 case MONO_WRAPPER_ISINST:
4063 case MONO_WRAPPER_PROXY_ISINST:
4064 case MONO_WRAPPER_ALLOC:
4065 case MONO_WRAPPER_REMOTING_INVOKE:
4066 case MONO_WRAPPER_UNKNOWN:
4067 case MONO_WRAPPER_WRITE_BARRIER:
4069 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4070 if (!strcmp (method->name, "ElementAddr"))
4075 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4079 if (!method->token) {
4080 /* The method is part of a constructed type like Int[,].Set (). */
4081 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4082 if (method->klass->rank)
4090 case MONO_PATCH_INFO_VTABLE:
4091 case MONO_PATCH_INFO_CLASS_INIT:
4092 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4093 case MONO_PATCH_INFO_CLASS:
4094 case MONO_PATCH_INFO_IID:
4095 case MONO_PATCH_INFO_ADJUSTED_IID:
4096 if (!can_encode_class (acfg, patch_info->data.klass)) {
4097 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4101 case MONO_PATCH_INFO_RGCTX_FETCH: {
4102 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4104 if (!can_encode_patch (acfg, entry->data))
4116 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4121 * AOT compile a given method.
4122 * This function might be called by multiple threads, so it must be thread-safe.
4125 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4128 MonoJumpInfo *patch_info;
4131 MonoMethod *wrapped;
4133 if (acfg->aot_opts.metadata_only)
4136 mono_acfg_lock (acfg);
4137 index = get_method_index (acfg, method);
4138 mono_acfg_unlock (acfg);
4140 /* fixme: maybe we can also precompile wrapper methods */
4141 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4142 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4143 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4144 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4148 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4151 wrapped = mono_marshal_method_from_wrapper (method);
4152 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4153 // FIXME: The wrapper should be generic too, but it is not
4156 InterlockedIncrement (&acfg->stats.mcount);
4159 if (method->is_generic || method->klass->generic_container) {
4160 InterlockedIncrement (&acfg->stats.genericcount);
4165 //acfg->aot_opts.print_skipped_methods = TRUE;
4168 * Since these methods are the only ones which are compiled with
4169 * AOT support, and they are not used by runtime startup/shutdown code,
4170 * the runtime will not see AOT methods during AOT compilation,so it
4171 * does not need to support them by creating a fake GOT etc.
4173 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4174 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4175 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4176 InterlockedIncrement (&acfg->stats.genericcount);
4179 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4180 /* Let the exception happen at runtime */
4184 if (cfg->disable_aot) {
4185 if (acfg->aot_opts.print_skipped_methods)
4186 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4187 InterlockedIncrement (&acfg->stats.ocount);
4188 mono_destroy_compile (cfg);
4192 /* Nullify patches which need no aot processing */
4193 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4194 switch (patch_info->type) {
4195 case MONO_PATCH_INFO_LABEL:
4196 case MONO_PATCH_INFO_BB:
4197 patch_info->type = MONO_PATCH_INFO_NONE;
4204 /* Collect method->token associations from the cfg */
4205 mono_acfg_lock (acfg);
4206 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4207 mono_acfg_unlock (acfg);
4210 * Check for absolute addresses.
4213 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4214 switch (patch_info->type) {
4215 case MONO_PATCH_INFO_ABS:
4216 /* unable to handle this */
4225 if (acfg->aot_opts.print_skipped_methods)
4226 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4227 InterlockedIncrement (&acfg->stats.abscount);
4228 mono_destroy_compile (cfg);
4232 /* Lock for the rest of the code */
4233 mono_acfg_lock (acfg);
4236 * Check for methods/klasses we can't encode.
4239 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4240 if (!can_encode_patch (acfg, patch_info))
4245 if (acfg->aot_opts.print_skipped_methods)
4246 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4247 acfg->stats.ocount++;
4248 mono_destroy_compile (cfg);
4249 mono_acfg_unlock (acfg);
4253 /* Adds generic instances referenced by this method */
4255 * The depth is used to avoid infinite loops when generic virtual recursion is
4258 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4260 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4261 switch (patch_info->type) {
4262 case MONO_PATCH_INFO_METHOD: {
4263 MonoMethod *m = patch_info->data.method;
4264 if (m->is_inflated) {
4265 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4266 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4267 !method_has_type_vars (m)) {
4268 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4269 if (acfg->aot_opts.full_aot)
4270 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4272 add_extra_method_with_depth (acfg, m, depth + 1);
4275 add_generic_class (acfg, m->klass);
4277 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4278 add_extra_method_with_depth (acfg, m, depth + 1);
4281 case MONO_PATCH_INFO_VTABLE: {
4282 MonoClass *klass = patch_info->data.klass;
4284 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4285 add_generic_class (acfg, klass);
4294 /* Determine whenever the method has GOT slots */
4295 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4296 switch (patch_info->type) {
4297 case MONO_PATCH_INFO_GOT_OFFSET:
4298 case MONO_PATCH_INFO_NONE:
4300 case MONO_PATCH_INFO_IMAGE:
4301 /* The assembly is stored in GOT slot 0 */
4302 if (patch_info->data.image != acfg->image)
4303 cfg->has_got_slots = TRUE;
4306 if (!is_plt_patch (patch_info))
4307 cfg->has_got_slots = TRUE;
4312 if (!cfg->has_got_slots)
4313 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4316 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4318 /* Make a copy of the patch info which is in the mempool */
4320 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4322 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4323 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4326 patches = new_patch_info;
4328 patches_end->next = new_patch_info;
4329 patches_end = new_patch_info;
4331 cfg->patch_info = patches;
4333 /* Make a copy of the unwind info */
4335 GSList *l, *unwind_ops;
4339 for (l = cfg->unwind_ops; l; l = l->next) {
4340 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4341 memcpy (op, l->data, sizeof (MonoUnwindOp));
4342 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4344 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4346 /* Make a copy of the argument/local info */
4348 MonoInst **args, **locals;
4349 MonoMethodSignature *sig;
4350 MonoMethodHeader *header;
4353 sig = mono_method_signature (method);
4354 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4355 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4356 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4357 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4361 header = mono_method_get_header (method);
4362 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4363 for (i = 0; i < header->num_locals; ++i) {
4364 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4365 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4367 cfg->locals = locals;
4370 /* Free some fields used by cfg to conserve memory */
4371 mono_mempool_destroy (cfg->mempool);
4372 cfg->mempool = NULL;
4373 g_free (cfg->varinfo);
4374 cfg->varinfo = NULL;
4378 mono_regstate_free (cfg->rs);
4382 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4384 while (index >= acfg->cfgs_size) {
4385 MonoCompile **new_cfgs;
4388 new_size = acfg->cfgs_size * 2;
4389 new_cfgs = g_new0 (MonoCompile*, new_size);
4390 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4391 g_free (acfg->cfgs);
4392 acfg->cfgs = new_cfgs;
4393 acfg->cfgs_size = new_size;
4395 acfg->cfgs [index] = cfg;
4397 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4400 if (cfg->orig_method->wrapper_type)
4401 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4404 mono_acfg_unlock (acfg);
4406 InterlockedIncrement (&acfg->stats.ccount);
4410 compile_thread_main (gpointer *user_data)
4412 MonoDomain *domain = user_data [0];
4413 MonoAotCompile *acfg = user_data [1];
4414 GPtrArray *methods = user_data [2];
4417 mono_thread_attach (domain);
4419 for (i = 0; i < methods->len; ++i)
4420 compile_method (acfg, g_ptr_array_index (methods, i));
4424 load_profile_files (MonoAotCompile *acfg)
4428 int file_index, res, method_index, i;
4435 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4437 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4442 infile = fopen (tmp, "r");
4445 printf ("Using profile data file '%s'\n", tmp);
4450 res = fscanf (infile, "%32s\n", ver);
4451 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4452 printf ("Profile file has wrong version or invalid.\n");
4459 MonoMethodDesc *desc;
4462 if (fgets (name, 1023, infile) == NULL)
4465 /* Kill the newline */
4466 if (strlen (name) > 0)
4467 name [strlen (name) - 1] = '\0';
4469 desc = mono_method_desc_new (name, TRUE);
4471 method = mono_method_desc_search_in_image (desc, acfg->image);
4473 if (method && mono_method_get_token (method)) {
4474 token = mono_method_get_token (method);
4475 method_index = mono_metadata_token_index (token) - 1;
4477 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4478 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4481 //printf ("No method found matching '%s'.\n", name);
4487 /* Add missing methods */
4489 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4490 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4491 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4493 unordered = g_list_reverse (unordered);
4494 if (acfg->method_order)
4495 g_list_last (acfg->method_order)->next = unordered;
4497 acfg->method_order = unordered;
4500 /* Used by the LLVM backend */
4502 mono_aot_get_got_offset (MonoJumpInfo *ji)
4504 return get_got_offset (llvm_acfg, ji);
4508 mono_aot_get_method_name (MonoCompile *cfg)
4510 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4512 return g_strdup_printf ("m_%x", method_index);
4516 mono_aot_get_method_debug_name (MonoCompile *cfg)
4518 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4522 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4524 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4528 ji->data.target = data;
4530 if (!can_encode_patch (llvm_acfg, ji))
4533 offset = get_plt_offset (llvm_acfg, ji);
4535 return g_strdup_printf ("%sp_%d", llvm_acfg->temp_prefix, offset);
4539 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4543 mono_acfg_lock (llvm_acfg);
4544 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4545 mono_acfg_unlock (llvm_acfg);
4555 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4559 emit_llvm_file (MonoAotCompile *acfg)
4561 char *command, *opts;
4563 MonoJumpInfo *patch_info;
4564 char *llc_target_args;
4567 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4571 /* Compute the final size of the got */
4572 for (i = 0; i < acfg->nmethods; ++i) {
4573 if (acfg->cfgs [i]) {
4574 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4575 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4576 if (!is_plt_patch (patch_info))
4577 get_got_offset (acfg, patch_info);
4579 get_plt_offset (acfg, patch_info);
4585 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4587 if (acfg->aot_opts.full_aot) {
4591 * Need to add the got entries used by the trampolines.
4592 * This is only a conservative approximation.
4594 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4595 /* For the generic + rgctx trampolines */
4596 acfg->final_got_size += 200;
4597 /* For the specific trampolines */
4598 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4599 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4604 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4607 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4608 * a lot of time, and doesn't seem to save much space.
4609 * The following optimizations cannot be enabled:
4611 * The opt list below was produced by taking the output of:
4612 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4613 * then removing tailcallelim + the global opts, and adding a second gvn.
4615 opts = g_strdup ("-instcombine -simplifycfg");
4616 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");
4618 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4619 printf ("Executing opt: %s\n", command);
4620 if (system (command) != 0) {
4626 llc_target_args = g_strdup (LLC_TARGET_ARGS);
4628 command = g_strdup_printf ("llc %s -f -relocation-model=pic -unwind-tables -o %s temp.opt.bc", llc_target_args, acfg->tmpfname);
4629 g_free (llc_target_args);
4631 printf ("Executing llc: %s\n", command);
4633 if (system (command) != 0) {
4640 emit_code (MonoAotCompile *acfg)
4644 char end_symbol [256];
4647 #if defined(TARGET_POWERPC64)
4648 sprintf (symbol, ".Lgot_addr");
4649 emit_section_change (acfg, ".text", 0);
4650 emit_alignment (acfg, 8);
4651 emit_label (acfg, symbol);
4652 emit_pointer (acfg, acfg->got_symbol);
4656 * This global symbol is used to compute the address of each method using the
4657 * code_offsets array. It is also used to compute the memory ranges occupied by
4658 * AOT code, so it must be equal to the address of the first emitted method.
4660 sprintf (symbol, "methods");
4661 emit_section_change (acfg, ".text", 0);
4662 emit_global (acfg, symbol, TRUE);
4663 emit_alignment (acfg, 8);
4665 for (i = 0; i < acfg->nmethods; ++i) {
4666 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4667 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4671 if (i == acfg->nmethods)
4672 /* No LLVM compiled methods */
4673 emit_label (acfg, symbol);
4675 emit_label (acfg, symbol);
4679 * Emit some padding so the local symbol for the first method doesn't have the
4680 * same address as 'methods'.
4682 emit_zero_bytes (acfg, 16);
4684 for (l = acfg->method_order; l != NULL; l = l->next) {
4688 i = GPOINTER_TO_UINT (l->data);
4690 cfg = acfg->cfgs [i];
4695 method = cfg->orig_method;
4697 /* Emit unbox trampoline */
4698 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4699 char call_target [256];
4701 if (!method->wrapper_type && !method->is_inflated) {
4702 g_assert (method->token);
4703 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4705 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4708 emit_section_change (acfg, ".text", 0);
4709 emit_global (acfg, symbol, TRUE);
4710 emit_label (acfg, symbol);
4712 sprintf (call_target, "%s", cfg->asm_symbol);
4714 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4717 if (cfg->compile_llvm)
4718 acfg->stats.llvm_count ++;
4720 emit_method_code (acfg, cfg);
4723 sprintf (symbol, "methods_end");
4724 emit_section_change (acfg, ".text", 0);
4725 emit_global (acfg, symbol, FALSE);
4726 emit_alignment (acfg, 8);
4727 emit_label (acfg, symbol);
4729 sprintf (symbol, "code_offsets");
4730 emit_section_change (acfg, ".text", 1);
4731 emit_global (acfg, symbol, FALSE);
4732 emit_alignment (acfg, 8);
4733 emit_label (acfg, symbol);
4735 acfg->stats.offsets_size += acfg->nmethods * 4;
4737 sprintf (end_symbol, "methods");
4738 for (i = 0; i < acfg->nmethods; ++i) {
4739 if (acfg->cfgs [i]) {
4740 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4742 emit_int32 (acfg, 0xffffffff);
4749 emit_info (MonoAotCompile *acfg)
4756 offsets = g_new0 (gint32, acfg->nmethods);
4758 for (l = acfg->method_order; l != NULL; l = l->next) {
4759 i = GPOINTER_TO_UINT (l->data);
4761 if (acfg->cfgs [i]) {
4762 emit_method_info (acfg, acfg->cfgs [i]);
4763 offsets [i] = acfg->cfgs [i]->method_info_offset;
4769 sprintf (symbol, "method_info_offsets");
4770 emit_section_change (acfg, ".text", 1);
4771 emit_global (acfg, symbol, FALSE);
4772 emit_alignment (acfg, 8);
4773 emit_label (acfg, symbol);
4775 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4780 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4782 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4783 #define mix(a,b,c) { \
4784 a -= c; a ^= rot(c, 4); c += b; \
4785 b -= a; b ^= rot(a, 6); a += c; \
4786 c -= b; c ^= rot(b, 8); b += a; \
4787 a -= c; a ^= rot(c,16); c += b; \
4788 b -= a; b ^= rot(a,19); a += c; \
4789 c -= b; c ^= rot(b, 4); b += a; \
4791 #define final(a,b,c) { \
4792 c ^= b; c -= rot(b,14); \
4793 a ^= c; a -= rot(c,11); \
4794 b ^= a; b -= rot(a,25); \
4795 c ^= b; c -= rot(b,16); \
4796 a ^= c; a -= rot(c,4); \
4797 b ^= a; b -= rot(a,14); \
4798 c ^= b; c -= rot(b,24); \
4802 mono_aot_type_hash (MonoType *t1)
4804 guint hash = t1->type;
4806 hash |= t1->byref << 6; /* do not collide with t1->type values */
4808 case MONO_TYPE_VALUETYPE:
4809 case MONO_TYPE_CLASS:
4810 case MONO_TYPE_SZARRAY:
4811 /* check if the distribution is good enough */
4812 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4814 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4815 case MONO_TYPE_ARRAY:
4816 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4817 case MONO_TYPE_GENERICINST:
4818 return ((hash << 5) - hash) ^ 0;
4824 * mono_aot_method_hash:
4826 * Return a hash code for methods which only depends on metadata.
4829 mono_aot_method_hash (MonoMethod *method)
4831 MonoMethodSignature *sig;
4835 guint32 *hashes_start, *hashes;
4838 /* Similar to the hash in mono_method_get_imt_slot () */
4840 sig = mono_method_signature (method);
4842 hashes_count = sig->param_count + 5;
4843 hashes_start = malloc (hashes_count * sizeof (guint32));
4844 hashes = hashes_start;
4846 /* Some wrappers are assigned to random classes */
4847 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4848 klass = method->klass;
4850 klass = mono_defaults.object_class;
4852 if (!method->wrapper_type) {
4853 char *full_name = mono_type_full_name (&klass->byval_arg);
4855 hashes [0] = mono_metadata_str_hash (full_name);
4859 hashes [0] = mono_metadata_str_hash (klass->name);
4860 hashes [1] = mono_metadata_str_hash (klass->name_space);
4862 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4863 /* The method name includes a stringified pointer */
4866 hashes [2] = mono_metadata_str_hash (method->name);
4867 hashes [3] = method->wrapper_type;
4868 hashes [4] = mono_aot_type_hash (sig->ret);
4869 for (i = 0; i < sig->param_count; i++) {
4870 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4873 /* Setup internal state */
4874 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4876 /* Handle most of the hashes */
4877 while (hashes_count > 3) {
4886 /* Handle the last 3 hashes (all the case statements fall through) */
4887 switch (hashes_count) {
4888 case 3 : c += hashes [2];
4889 case 2 : b += hashes [1];
4890 case 1 : a += hashes [0];
4892 case 0: /* nothing left to add */
4896 free (hashes_start);
4905 * mono_aot_wrapper_name:
4907 * Return a string which uniqely identifies the given wrapper method.
4910 mono_aot_wrapper_name (MonoMethod *method)
4912 char *name, *tmpsig, *klass_desc;
4914 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4916 switch (method->wrapper_type) {
4917 case MONO_WRAPPER_RUNTIME_INVOKE:
4918 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4919 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4921 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4924 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4925 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4926 g_free (klass_desc);
4936 * mono_aot_get_array_helper_from_wrapper;
4938 * Get the helper method in Array called by an array wrapper method.
4941 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4945 MonoGenericContext ctx;
4946 MonoType *args [16];
4947 char *mname, *iname, *s, *s2, *helper_name = NULL;
4949 prefix = "System.Collections.Generic";
4950 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4951 s2 = strstr (s, "`1.");
4957 //printf ("X: %s %s\n", iname, mname);
4959 if (!strcmp (iname, "IList"))
4960 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4962 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4963 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4965 g_free (helper_name);
4968 if (m->is_generic) {
4969 memset (&ctx, 0, sizeof (ctx));
4970 args [0] = &method->klass->element_class->byval_arg;
4971 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4972 m = mono_class_inflate_generic_method (m, &ctx);
4979 * mono_aot_tramp_info_create:
4981 * Create a MonoAotTrampInfo structure from the arguments.
4984 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4986 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4988 info->name = (char*)name;
4990 info->code_size = code_size;
4995 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4997 typedef struct HashEntry {
4998 guint32 key, value, index;
4999 struct HashEntry *next;
5003 * emit_extra_methods:
5005 * Emit methods which are not in the METHOD table, like wrappers.
5008 emit_extra_methods (MonoAotCompile *acfg)
5010 int i, table_size, buf_size;
5013 guint32 *info_offsets;
5016 HashEntry *entry, *new_entry;
5017 int nmethods, max_chain_length;
5020 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5022 /* Emit method info */
5024 for (i = 0; i < acfg->extra_methods->len; ++i) {
5025 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5026 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5033 p = buf = g_malloc (buf_size);
5037 method = cfg->method_to_register;
5040 if (method->wrapper_type) {
5042 * We encode some wrappers using their name, since encoding them
5043 * directly would be difficult. This also avoids creating the wrapper
5044 * methods at runtime, since they are not needed anyway.
5046 switch (method->wrapper_type) {
5047 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5048 case MONO_WRAPPER_SYNCHRONIZED:
5049 /* encode_method_ref () can handle these */
5051 case MONO_WRAPPER_RUNTIME_INVOKE:
5052 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5053 /* Direct wrapper, encode normally */
5057 name = mono_aot_wrapper_name (method);
5063 encode_value (1, p, &p);
5064 encode_value (method->wrapper_type, p, &p);
5065 strcpy ((char*)p, name);
5066 p += strlen (name ) + 1;
5069 encode_value (0, p, &p);
5070 encode_method_ref (acfg, method, p, &p);
5073 g_assert ((p - buf) < buf_size);
5075 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5080 * Construct a chained hash table for mapping indexes in extra_method_info to
5083 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5084 table = g_ptr_array_sized_new (table_size);
5085 for (i = 0; i < table_size; ++i)
5086 g_ptr_array_add (table, NULL);
5087 chain_lengths = g_new0 (int, table_size);
5088 max_chain_length = 0;
5089 for (i = 0; i < acfg->extra_methods->len; ++i) {
5090 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5091 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5097 key = info_offsets [i];
5098 value = get_method_index (acfg, method);
5100 hash = mono_aot_method_hash (method) % table_size;
5102 chain_lengths [hash] ++;
5103 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5105 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5106 new_entry->key = key;
5107 new_entry->value = value;
5109 entry = g_ptr_array_index (table, hash);
5110 if (entry == NULL) {
5111 new_entry->index = hash;
5112 g_ptr_array_index (table, hash) = new_entry;
5115 entry = entry->next;
5117 entry->next = new_entry;
5118 new_entry->index = table->len;
5119 g_ptr_array_add (table, new_entry);
5123 //printf ("MAX: %d\n", max_chain_length);
5125 /* Emit the table */
5126 sprintf (symbol, "extra_method_table");
5127 emit_section_change (acfg, ".text", 0);
5128 emit_global (acfg, symbol, FALSE);
5129 emit_alignment (acfg, 8);
5130 emit_label (acfg, symbol);
5132 emit_int32 (acfg, table_size);
5133 for (i = 0; i < table->len; ++i) {
5134 HashEntry *entry = g_ptr_array_index (table, i);
5136 if (entry == NULL) {
5137 emit_int32 (acfg, 0);
5138 emit_int32 (acfg, 0);
5139 emit_int32 (acfg, 0);
5141 //g_assert (entry->key > 0);
5142 emit_int32 (acfg, entry->key);
5143 emit_int32 (acfg, entry->value);
5145 emit_int32 (acfg, entry->next->index);
5147 emit_int32 (acfg, 0);
5152 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5153 * This is used by mono_aot_find_jit_info ().
5155 sprintf (symbol, "extra_method_info_offsets");
5156 emit_section_change (acfg, ".text", 0);
5157 emit_global (acfg, symbol, FALSE);
5158 emit_alignment (acfg, 8);
5159 emit_label (acfg, symbol);
5161 emit_int32 (acfg, acfg->extra_methods->len);
5162 for (i = 0; i < acfg->extra_methods->len; ++i) {
5163 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5165 emit_int32 (acfg, get_method_index (acfg, method));
5166 emit_int32 (acfg, info_offsets [i]);
5171 emit_exception_info (MonoAotCompile *acfg)
5177 offsets = g_new0 (gint32, acfg->nmethods);
5178 for (i = 0; i < acfg->nmethods; ++i) {
5179 if (acfg->cfgs [i]) {
5180 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5181 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5187 sprintf (symbol, "ex_info_offsets");
5188 emit_section_change (acfg, ".text", 1);
5189 emit_global (acfg, symbol, FALSE);
5190 emit_alignment (acfg, 8);
5191 emit_label (acfg, symbol);
5193 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5198 emit_unwind_info (MonoAotCompile *acfg)
5204 * The unwind info contains a lot of duplicates so we emit each unique
5205 * entry once, and only store the offset from the start of the table in the
5209 sprintf (symbol, "unwind_info");
5210 emit_section_change (acfg, ".text", 1);
5211 emit_alignment (acfg, 8);
5212 emit_label (acfg, symbol);
5213 emit_global (acfg, symbol, FALSE);
5215 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5216 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5217 guint8 *unwind_info;
5218 guint32 unwind_info_len;
5222 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5225 encode_value (unwind_info_len, p, &p);
5226 emit_bytes (acfg, buf, p - buf);
5227 emit_bytes (acfg, unwind_info, unwind_info_len);
5229 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5234 emit_class_info (MonoAotCompile *acfg)
5240 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5241 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5242 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5244 sprintf (symbol, "class_info_offsets");
5245 emit_section_change (acfg, ".text", 1);
5246 emit_global (acfg, symbol, FALSE);
5247 emit_alignment (acfg, 8);
5248 emit_label (acfg, symbol);
5250 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5254 typedef struct ClassNameTableEntry {
5255 guint32 token, index;
5256 struct ClassNameTableEntry *next;
5257 } ClassNameTableEntry;
5260 emit_class_name_table (MonoAotCompile *acfg)
5263 guint32 token, hash;
5268 ClassNameTableEntry *entry, *new_entry;
5271 * Construct a chained hash table for mapping class names to typedef tokens.
5273 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5274 table = g_ptr_array_sized_new (table_size);
5275 for (i = 0; i < table_size; ++i)
5276 g_ptr_array_add (table, NULL);
5277 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5278 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5279 klass = mono_class_get (acfg->image, token);
5280 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5281 hash = mono_metadata_str_hash (full_name) % table_size;
5284 /* FIXME: Allocate from the mempool */
5285 new_entry = g_new0 (ClassNameTableEntry, 1);
5286 new_entry->token = token;
5288 entry = g_ptr_array_index (table, hash);
5289 if (entry == NULL) {
5290 new_entry->index = hash;
5291 g_ptr_array_index (table, hash) = new_entry;
5294 entry = entry->next;
5296 entry->next = new_entry;
5297 new_entry->index = table->len;
5298 g_ptr_array_add (table, new_entry);
5302 /* Emit the table */
5303 sprintf (symbol, "class_name_table");
5304 emit_section_change (acfg, ".text", 0);
5305 emit_global (acfg, symbol, FALSE);
5306 emit_alignment (acfg, 8);
5307 emit_label (acfg, symbol);
5309 /* FIXME: Optimize memory usage */
5310 g_assert (table_size < 65000);
5311 emit_int16 (acfg, table_size);
5312 g_assert (table->len < 65000);
5313 for (i = 0; i < table->len; ++i) {
5314 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5316 if (entry == NULL) {
5317 emit_int16 (acfg, 0);
5318 emit_int16 (acfg, 0);
5320 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5322 emit_int16 (acfg, entry->next->index);
5324 emit_int16 (acfg, 0);
5330 emit_image_table (MonoAotCompile *acfg)
5336 * The image table is small but referenced in a lot of places.
5337 * So we emit it at once, and reference its elements by an index.
5340 sprintf (symbol, "mono_image_table");
5341 emit_section_change (acfg, ".text", 1);
5342 emit_global (acfg, symbol, FALSE);
5343 emit_alignment (acfg, 8);
5344 emit_label (acfg, symbol);
5346 emit_int32 (acfg, acfg->image_table->len);
5347 for (i = 0; i < acfg->image_table->len; i++) {
5348 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5349 MonoAssemblyName *aname = &image->assembly->aname;
5351 /* FIXME: Support multi-module assemblies */
5352 g_assert (image->assembly->image == image);
5354 emit_string (acfg, image->assembly_name);
5355 emit_string (acfg, image->guid);
5356 emit_string (acfg, aname->culture ? aname->culture : "");
5357 emit_string (acfg, (const char*)aname->public_key_token);
5359 emit_alignment (acfg, 8);
5360 emit_int32 (acfg, aname->flags);
5361 emit_int32 (acfg, aname->major);
5362 emit_int32 (acfg, aname->minor);
5363 emit_int32 (acfg, aname->build);
5364 emit_int32 (acfg, aname->revision);
5369 emit_got_info (MonoAotCompile *acfg)
5372 int i, first_plt_got_patch, buf_size;
5374 guint32 *got_info_offsets;
5376 /* Add the patches needed by the PLT to the GOT */
5377 acfg->plt_got_offset_base = acfg->got_offset;
5378 first_plt_got_patch = acfg->got_patches->len;
5379 for (i = 1; i < acfg->plt_offset; ++i) {
5380 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
5382 g_ptr_array_add (acfg->got_patches, patch_info);
5385 acfg->got_offset += acfg->plt_offset;
5389 * - optimize offsets table.
5390 * - reduce number of exported symbols.
5391 * - emit info for a klass only once.
5392 * - determine when a method uses a GOT slot which is guaranteed to be already
5394 * - clean up and document the code.
5395 * - use String.Empty in class libs.
5398 /* Encode info required to decode shared GOT entries */
5399 buf_size = acfg->got_patches->len * 128;
5400 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5401 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5402 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5404 if (acfg->plt_offset)
5405 acfg->plt_got_info_offsets [0] = 0;
5406 for (i = 0; i < acfg->got_patches->len; ++i) {
5407 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5411 encode_value (ji->type, p, &p);
5412 encode_patch (acfg, ji, p, &p);
5414 g_assert (p - buf <= buf_size);
5415 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5417 if (i >= first_plt_got_patch)
5418 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5419 acfg->stats.got_info_size += p - buf;
5422 /* Emit got_info_offsets table */
5423 sprintf (symbol, "got_info_offsets");
5424 emit_section_change (acfg, ".text", 1);
5425 emit_global (acfg, symbol, FALSE);
5426 emit_alignment (acfg, 8);
5427 emit_label (acfg, symbol);
5429 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5430 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5434 emit_got (MonoAotCompile *acfg)
5439 /* Don't make GOT global so accesses to it don't need relocations */
5440 sprintf (symbol, "%s", acfg->got_symbol);
5441 emit_section_change (acfg, ".bss", 0);
5442 emit_alignment (acfg, 8);
5443 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5444 emit_label (acfg, symbol);
5445 if (acfg->got_offset > 0)
5446 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5448 sprintf (symbol, "got_end");
5449 emit_label (acfg, symbol);
5452 sprintf (symbol, "mono_aot_got_addr");
5453 emit_section_change (acfg, ".data", 0);
5454 emit_global (acfg, symbol, FALSE);
5455 emit_alignment (acfg, 8);
5456 emit_label (acfg, symbol);
5457 emit_pointer (acfg, acfg->got_symbol);
5460 typedef struct GlobalsTableEntry {
5461 guint32 value, index;
5462 struct GlobalsTableEntry *next;
5463 } GlobalsTableEntry;
5466 emit_globals_table (MonoAotCompile *acfg)
5472 GlobalsTableEntry *entry, *new_entry;
5475 * Construct a chained hash table for mapping global names to their index in
5476 * the globals table.
5478 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5479 table = g_ptr_array_sized_new (table_size);
5480 for (i = 0; i < table_size; ++i)
5481 g_ptr_array_add (table, NULL);
5482 for (i = 0; i < acfg->globals->len; ++i) {
5483 char *name = g_ptr_array_index (acfg->globals, i);
5485 hash = mono_metadata_str_hash (name) % table_size;
5487 /* FIXME: Allocate from the mempool */
5488 new_entry = g_new0 (GlobalsTableEntry, 1);
5489 new_entry->value = i;
5491 entry = g_ptr_array_index (table, hash);
5492 if (entry == NULL) {
5493 new_entry->index = hash;
5494 g_ptr_array_index (table, hash) = new_entry;
5497 entry = entry->next;
5499 entry->next = new_entry;
5500 new_entry->index = table->len;
5501 g_ptr_array_add (table, new_entry);
5505 /* Emit the table */
5506 sprintf (symbol, ".Lglobals_hash");
5507 emit_section_change (acfg, ".text", 0);
5508 emit_alignment (acfg, 8);
5509 emit_label (acfg, symbol);
5511 /* FIXME: Optimize memory usage */
5512 g_assert (table_size < 65000);
5513 emit_int16 (acfg, table_size);
5514 for (i = 0; i < table->len; ++i) {
5515 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5517 if (entry == NULL) {
5518 emit_int16 (acfg, 0);
5519 emit_int16 (acfg, 0);
5521 emit_int16 (acfg, entry->value + 1);
5523 emit_int16 (acfg, entry->next->index);
5525 emit_int16 (acfg, 0);
5529 /* Emit the names */
5530 for (i = 0; i < acfg->globals->len; ++i) {
5531 char *name = g_ptr_array_index (acfg->globals, i);
5533 sprintf (symbol, "name_%d", i);
5534 emit_section_change (acfg, ".text", 1);
5535 emit_label (acfg, symbol);
5536 emit_string (acfg, name);
5539 /* Emit the globals table */
5540 sprintf (symbol, ".Lglobals");
5541 emit_section_change (acfg, ".data", 0);
5542 /* This is not a global, since it is accessed by the init function */
5543 emit_alignment (acfg, 8);
5544 emit_label (acfg, symbol);
5546 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5547 emit_pointer (acfg, symbol);
5549 for (i = 0; i < acfg->globals->len; ++i) {
5550 char *name = g_ptr_array_index (acfg->globals, i);
5552 sprintf (symbol, "name_%d", i);
5553 emit_pointer (acfg, symbol);
5555 sprintf (symbol, "%s", name);
5556 emit_pointer (acfg, symbol);
5558 /* Null terminate the table */
5559 emit_int32 (acfg, 0);
5560 emit_int32 (acfg, 0);
5564 emit_globals (MonoAotCompile *acfg)
5568 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5570 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5572 if (acfg->aot_opts.bind_to_runtime_version) {
5573 build_info = mono_get_runtime_build_info ();
5574 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5575 g_free (build_info);
5577 emit_string_symbol (acfg, "mono_runtime_version", "");
5581 * When static linking, we emit a global which will point to the symbol table.
5583 if (acfg->aot_opts.static_link) {
5587 /* Emit a string holding the assembly name */
5588 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5590 emit_globals_table (acfg);
5593 * Emit a global symbol which can be passed by an embedding app to
5594 * mono_aot_register_module ().
5596 #if defined(__MACH__)
5597 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5599 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5602 /* Get rid of characters which cannot occur in symbols */
5604 for (p = symbol; *p; ++p) {
5605 if (!(isalnum (*p) || *p == '_'))
5608 acfg->static_linking_symbol = g_strdup (symbol);
5609 emit_global_inner (acfg, symbol, FALSE);
5610 emit_alignment (acfg, 8);
5611 emit_label (acfg, symbol);
5612 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5613 emit_pointer (acfg, symbol);
5618 emit_autoreg (MonoAotCompile *acfg)
5623 * Emit a function into the .ctor section which will be called by the ELF
5624 * loader to register this module with the runtime.
5626 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5629 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5631 arch_emit_autoreg (acfg, symbol);
5637 emit_mem_end (MonoAotCompile *acfg)
5641 sprintf (symbol, "mem_end");
5642 emit_section_change (acfg, ".text", 1);
5643 emit_global (acfg, symbol, FALSE);
5644 emit_alignment (acfg, 8);
5645 emit_label (acfg, symbol);
5649 * Emit a structure containing all the information not stored elsewhere.
5652 emit_file_info (MonoAotCompile *acfg)
5657 sprintf (symbol, "mono_aot_file_info");
5658 emit_section_change (acfg, ".data", 0);
5659 emit_alignment (acfg, 8);
5660 emit_label (acfg, symbol);
5661 emit_global (acfg, symbol, FALSE);
5663 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5664 emit_int32 (acfg, acfg->plt_got_offset_base);
5665 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5666 emit_int32 (acfg, acfg->plt_offset);
5667 emit_int32 (acfg, acfg->nmethods);
5668 emit_int32 (acfg, acfg->flags);
5669 emit_int32 (acfg, acfg->opts);
5671 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5672 emit_int32 (acfg, acfg->num_trampolines [i]);
5673 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5674 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5675 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5676 emit_int32 (acfg, acfg->trampoline_size [i]);
5680 emit_blob (MonoAotCompile *acfg)
5684 sprintf (symbol, "blob");
5685 emit_section_change (acfg, ".text", 1);
5686 emit_global (acfg, symbol, FALSE);
5687 emit_alignment (acfg, 8);
5688 emit_label (acfg, symbol);
5690 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5694 emit_dwarf_info (MonoAotCompile *acfg)
5696 #ifdef EMIT_DWARF_INFO
5698 char symbol [128], symbol2 [128];
5700 /* DIEs for methods */
5701 for (i = 0; i < acfg->nmethods; ++i) {
5702 MonoCompile *cfg = acfg->cfgs [i];
5707 // FIXME: LLVM doesn't define .Lme_...
5708 if (cfg->compile_llvm)
5711 sprintf (symbol, "%s", cfg->asm_symbol);
5712 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5714 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 ()));
5720 collect_methods (MonoAotCompile *acfg)
5723 MonoImage *image = acfg->image;
5725 /* Collect methods */
5726 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5728 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5730 method = mono_get_method (acfg->image, token, NULL);
5733 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5737 /* Load all methods eagerly to skip the slower lazy loading code */
5738 mono_class_setup_methods (method->klass);
5740 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5741 /* Compile the wrapper instead */
5742 /* We do this here instead of add_wrappers () because it is easy to do it here */
5743 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5747 /* FIXME: Some mscorlib methods don't have debug info */
5749 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5750 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5751 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5752 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5753 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5754 if (!mono_debug_lookup_method (method)) {
5755 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5762 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5763 add_method_with_index (acfg, method, i, FALSE);
5764 acfg->method_index ++;
5767 add_generic_instances (acfg);
5769 if (acfg->aot_opts.full_aot)
5770 add_wrappers (acfg);
5774 compile_methods (MonoAotCompile *acfg)
5778 if (acfg->aot_opts.nthreads > 0) {
5783 gpointer *user_data;
5784 MonoMethod **methods;
5786 methods_len = acfg->methods->len;
5788 len = acfg->methods->len / acfg->aot_opts.nthreads;
5791 * Partition the list of methods into fragments, and hand it to threads to
5794 threads = g_ptr_array_new ();
5795 /* Make a copy since acfg->methods is modified by compile_method () */
5796 methods = g_new0 (MonoMethod*, methods_len);
5797 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5798 for (i = 0; i < methods_len; ++i)
5799 methods [i] = g_ptr_array_index (acfg->methods, i);
5801 while (i < methods_len) {
5802 frag = g_ptr_array_new ();
5803 for (j = 0; j < len; ++j) {
5804 if (i < methods_len) {
5805 g_ptr_array_add (frag, methods [i]);
5810 user_data = g_new0 (gpointer, 3);
5811 user_data [0] = mono_domain_get ();
5812 user_data [1] = acfg;
5813 user_data [2] = frag;
5815 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5816 g_ptr_array_add (threads, handle);
5820 for (i = 0; i < threads->len; ++i) {
5821 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5827 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5828 for (i = methods_len; i < acfg->methods->len; ++i) {
5829 /* This can new methods to acfg->methods */
5830 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5835 compile_asm (MonoAotCompile *acfg)
5837 char *command, *objfile;
5838 char *outfile_name, *tmp_outfile_name;
5839 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5841 #if defined(TARGET_AMD64)
5842 #define AS_OPTIONS "--64"
5843 #elif defined(TARGET_POWERPC64)
5844 #define AS_OPTIONS "-a64 -mppc64"
5845 #define LD_OPTIONS "-m elf64ppc"
5846 #elif defined(sparc) && SIZEOF_VOID_P == 8
5847 #define AS_OPTIONS "-xarch=v9"
5849 #define AS_OPTIONS ""
5853 #define LD_OPTIONS ""
5857 #define EH_LD_OPTIONS "--eh-frame-hdr"
5859 #define EH_LD_OPTIONS ""
5862 if (acfg->aot_opts.asm_only) {
5863 printf ("Output file: '%s'.\n", acfg->tmpfname);
5864 if (acfg->aot_opts.static_link)
5865 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5869 if (acfg->aot_opts.static_link) {
5870 if (acfg->aot_opts.outfile)
5871 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5873 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5875 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5877 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5878 printf ("Executing the native assembler: %s\n", command);
5879 if (system (command) != 0) {
5887 if (acfg->aot_opts.static_link) {
5888 printf ("Output file: '%s'.\n", objfile);
5889 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5894 if (acfg->aot_opts.outfile)
5895 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5897 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5899 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5902 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5903 #elif defined(__ppc__) && defined(__MACH__)
5904 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5905 #elif defined(HOST_WIN32)
5906 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5908 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5910 printf ("Executing the native linker: %s\n", command);
5911 if (system (command) != 0) {
5912 g_free (tmp_outfile_name);
5913 g_free (outfile_name);
5921 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5922 printf ("Stripping the binary: %s\n", com);
5926 #if defined(TARGET_ARM) && !defined(__MACH__)
5928 * gas generates 'mapping symbols' each time code and data is mixed, which
5929 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5931 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5932 printf ("Stripping the binary: %s\n", command);
5933 if (system (command) != 0) {
5934 g_free (tmp_outfile_name);
5935 g_free (outfile_name);
5942 rename (tmp_outfile_name, outfile_name);
5944 g_free (tmp_outfile_name);
5945 g_free (outfile_name);
5948 if (acfg->aot_opts.save_temps)
5949 printf ("Retained input file.\n");
5951 unlink (acfg->tmpfname);
5956 static MonoAotCompile*
5957 acfg_create (MonoAssembly *ass, guint32 opts)
5959 MonoImage *image = ass->image;
5960 MonoAotCompile *acfg;
5963 acfg = g_new0 (MonoAotCompile, 1);
5964 acfg->methods = g_ptr_array_new ();
5965 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5966 acfg->method_depth = g_hash_table_new (NULL, NULL);
5967 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5968 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5969 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5970 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5971 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5972 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5973 acfg->got_patches = g_ptr_array_new ();
5974 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5975 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5976 acfg->image_hash = g_hash_table_new (NULL, NULL);
5977 acfg->image_table = g_ptr_array_new ();
5978 acfg->globals = g_ptr_array_new ();
5979 acfg->image = image;
5981 acfg->mempool = mono_mempool_new ();
5982 acfg->extra_methods = g_ptr_array_new ();
5983 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5984 acfg->unwind_ops = g_ptr_array_new ();
5985 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5986 InitializeCriticalSection (&acfg->mutex);
5992 acfg_free (MonoAotCompile *acfg)
5996 img_writer_destroy (acfg->w);
5997 for (i = 0; i < acfg->nmethods; ++i)
5999 g_free (acfg->cfgs [i]);
6000 g_free (acfg->cfgs);
6001 g_free (acfg->static_linking_symbol);
6002 g_free (acfg->got_symbol);
6003 g_free (acfg->plt_symbol);
6004 g_ptr_array_free (acfg->methods, TRUE);
6005 g_ptr_array_free (acfg->got_patches, TRUE);
6006 g_ptr_array_free (acfg->image_table, TRUE);
6007 g_ptr_array_free (acfg->globals, TRUE);
6008 g_ptr_array_free (acfg->unwind_ops, TRUE);
6009 g_hash_table_destroy (acfg->method_indexes);
6010 g_hash_table_destroy (acfg->method_depth);
6011 g_hash_table_destroy (acfg->plt_offset_to_patch);
6012 g_hash_table_destroy (acfg->patch_to_plt_offset);
6013 g_hash_table_destroy (acfg->patch_to_got_offset);
6014 g_hash_table_destroy (acfg->method_to_cfg);
6015 g_hash_table_destroy (acfg->token_info_hash);
6016 g_hash_table_destroy (acfg->image_hash);
6017 g_hash_table_destroy (acfg->unwind_info_offsets);
6018 g_hash_table_destroy (acfg->method_label_hash);
6019 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6020 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6021 g_free (acfg->patch_to_got_offset_by_type);
6022 mono_mempool_destroy (acfg->mempool);
6027 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6029 MonoImage *image = ass->image;
6031 MonoAotCompile *acfg;
6032 char *outfile_name, *tmp_outfile_name, *p;
6036 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6038 acfg = acfg_create (ass, opts);
6040 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6041 acfg->aot_opts.write_symbols = TRUE;
6042 acfg->aot_opts.ntrampolines = 1024;
6043 acfg->aot_opts.nrgctx_trampolines = 1024;
6044 acfg->aot_opts.nimt_trampolines = 128;
6046 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6048 if (acfg->aot_opts.static_link)
6049 acfg->aot_opts.autoreg = TRUE;
6051 //acfg->aot_opts.print_skipped_methods = TRUE;
6053 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6054 if (acfg->aot_opts.full_aot) {
6055 printf ("--aot=full is not supported on this platform.\n");
6060 if (acfg->aot_opts.static_link)
6061 acfg->aot_opts.asm_writer = TRUE;
6063 if (acfg->aot_opts.soft_debug) {
6064 MonoDebugOptions *opt = mini_get_debug_options ();
6066 opt->mdb_optimizations = TRUE;
6067 opt->gen_seq_points = TRUE;
6069 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6070 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6077 acfg->aot_opts.asm_writer = TRUE;
6078 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6081 if (acfg->aot_opts.full_aot)
6082 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6084 load_profile_files (acfg);
6086 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6087 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6088 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6090 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6092 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6093 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6095 /* Get rid of characters which cannot occur in symbols */
6096 for (p = acfg->got_symbol_base; *p; ++p) {
6097 if (!(isalnum (*p) || *p == '_'))
6100 for (p = acfg->plt_symbol; *p; ++p) {
6101 if (!(isalnum (*p) || *p == '_'))
6105 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6107 acfg->method_index = 1;
6109 collect_methods (acfg);
6111 acfg->cfgs_size = acfg->methods->len + 32;
6112 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6114 /* PLT offset 0 is reserved for the PLT trampoline */
6115 acfg->plt_offset = 1;
6119 mono_llvm_create_aot_module (acfg->got_symbol_base);
6122 /* GOT offset 0 is reserved for the address of the current assembly */
6126 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6127 ji->type = MONO_PATCH_INFO_IMAGE;
6128 ji->data.image = acfg->image;
6130 get_got_offset (acfg, ji);
6132 /* Slot 1 is reserved for the mscorlib got addr */
6133 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6134 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6135 get_got_offset (acfg, ji);
6140 compile_methods (acfg);
6144 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6150 if (acfg->aot_opts.asm_only) {
6151 if (acfg->aot_opts.outfile)
6152 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6154 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6156 acfg->tmpfname = g_strdup ("temp.s");
6160 emit_llvm_file (acfg);
6163 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6164 if (acfg->aot_opts.outfile)
6165 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6167 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6170 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6171 * it might be in another file system so the rename () won't work.
6173 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6175 acfg->fp = fopen (tmp_outfile_name, "w");
6177 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6181 acfg->w = img_writer_create (acfg->fp, TRUE);
6182 acfg->use_bin_writer = TRUE;
6185 /* Append to the .s file created by llvm */
6186 /* FIXME: Use multiple files instead */
6187 acfg->fp = fopen (acfg->tmpfname, "a+");
6189 if (acfg->aot_opts.asm_only) {
6190 if (acfg->aot_opts.outfile)
6191 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6193 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6194 acfg->fp = fopen (acfg->tmpfname, "w+");
6196 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6197 acfg->fp = fdopen (i, "w+");
6199 g_assert (acfg->fp);
6201 acfg->w = img_writer_create (acfg->fp, FALSE);
6203 tmp_outfile_name = NULL;
6204 outfile_name = NULL;
6208 * The prefix LLVM likes to put in front of symbol names on darwin.
6209 * The mach-os specs require this for globals, but LLVM puts them in front of all
6210 * symbols. We need to handle this, since we need to refer to LLVM generated
6213 acfg->llvm_label_prefix = "";
6215 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6217 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6219 /* Compute symbols for methods */
6220 for (i = 0; i < acfg->nmethods; ++i) {
6221 if (acfg->cfgs [i]) {
6222 MonoCompile *cfg = acfg->cfgs [i];
6223 int method_index = get_method_index (acfg, cfg->orig_method);
6225 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6229 if (!acfg->aot_opts.nodebug)
6230 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6232 img_writer_emit_start (acfg->w);
6235 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6241 emit_extra_methods (acfg);
6243 emit_trampolines (acfg);
6245 emit_class_name_table (acfg);
6247 emit_got_info (acfg);
6249 emit_exception_info (acfg);
6251 emit_unwind_info (acfg);
6253 emit_class_info (acfg);
6257 emit_image_table (acfg);
6261 emit_file_info (acfg);
6265 emit_globals (acfg);
6267 emit_autoreg (acfg);
6270 emit_dwarf_info (acfg);
6271 mono_dwarf_writer_close (acfg->dwarf);
6274 emit_mem_end (acfg);
6278 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6281 g_assert (acfg->got_offset <= acfg->final_got_size);
6283 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);
6286 res = img_writer_emit_writeout (acfg->w);
6291 if (acfg->use_bin_writer) {
6292 int err = rename (tmp_outfile_name, outfile_name);
6295 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6299 res = compile_asm (acfg);
6306 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6308 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);
6309 if (acfg->stats.genericcount)
6310 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6311 if (acfg->stats.abscount)
6312 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6313 if (acfg->stats.lmfcount)
6314 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6315 if (acfg->stats.ocount)
6316 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6318 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6319 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);
6320 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6322 if (acfg->aot_opts.stats) {
6325 printf ("GOT slot distribution:\n");
6326 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6327 if (acfg->stats.got_slot_types [i])
6328 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6331 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);
6343 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)