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 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
826 /* Load mscorlib got address */
827 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
828 /* Push trampoline argument */
829 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
830 /* Load generic trampoline address */
831 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
832 /* Branch to generic trampoline */
833 x86_jump_reg (code, X86_ECX);
835 emit_bytes (acfg, buf, code - buf);
838 g_assert (code - buf == *tramp_size);
840 g_assert_not_reached ();
845 * arch_emit_unbox_trampoline:
847 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
848 * CALL_TARGET is the symbol pointing to the native code of METHOD.
851 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
853 #if defined(TARGET_AMD64)
858 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
860 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
862 emit_bytes (acfg, buf, code - buf);
864 emit_byte (acfg, '\xe9');
865 emit_symbol_diff (acfg, call_target, ".", -4);
866 #elif defined(TARGET_X86)
871 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
876 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
878 emit_bytes (acfg, buf, code - buf);
881 emit_byte (acfg, '\xe9');
882 emit_symbol_diff (acfg, call_target, ".", -4);
883 #elif defined(TARGET_ARM)
890 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
893 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
895 emit_bytes (acfg, buf, code - buf);
897 if (acfg->use_bin_writer) {
904 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
905 emit_bytes (acfg, buf, 4);
907 fprintf (acfg->fp, "\n\tb %s\n", call_target);
909 #elif defined(TARGET_POWERPC)
912 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
915 g_assert (!acfg->use_bin_writer);
917 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
918 fprintf (acfg->fp, "\n\tb %s\n", call_target);
920 g_assert_not_reached ();
925 * arch_emit_static_rgctx_trampoline:
927 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
928 * two GOT slots which contain the rgctx argument, and the method to jump to.
929 * TRAMP_SIZE is set to the size of the emitted trampoline.
930 * These kinds of trampolines cannot be enumerated statically, since there could
931 * be one trampoline per method instantiation, so we emit the same code for all
932 * trampolines, and parameterize them using two GOT slots.
935 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
937 #if defined(TARGET_AMD64)
938 /* This should be exactly 13 bytes long */
941 /* mov <OFFSET>(%rip), %r10 */
942 emit_byte (acfg, '\x4d');
943 emit_byte (acfg, '\x8b');
944 emit_byte (acfg, '\x15');
945 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
947 /* jmp *<offset>(%rip) */
948 emit_byte (acfg, '\xff');
949 emit_byte (acfg, '\x25');
950 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
951 #elif defined(TARGET_ARM)
955 /* This should be exactly 24 bytes long */
958 /* Load rgctx value */
959 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
960 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
961 /* Load branch addr + branch */
962 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
963 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
965 g_assert (code - buf == 16);
968 emit_bytes (acfg, buf, code - buf);
969 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
970 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
971 #elif defined(TARGET_POWERPC)
978 g_assert (!acfg->use_bin_writer);
981 * PPC has no ip relative addressing, so we need to compute the address
982 * of the mscorlib got. That is slow and complex, so instead, we store it
983 * in the second got slot of every aot image. The caller already computed
984 * the address of its got and placed it into r30.
986 img_writer_emit_unset_mode (acfg->w);
987 /* Load mscorlib got address */
988 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
990 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
991 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
992 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
993 /* Load target address */
994 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
995 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
996 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
997 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
998 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
999 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1001 fprintf (acfg->fp, "mtctr 11\n");
1002 /* Branch to the target address */
1003 fprintf (acfg->fp, "bctr\n");
1005 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1006 *tramp_size = 11 * 4;
1008 *tramp_size = 9 * 4;
1011 #elif defined(TARGET_X86)
1015 /* Similar to the PPC code above */
1017 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1020 /* Load mscorlib got address */
1021 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1023 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1024 /* Branch to the target address */
1025 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1027 emit_bytes (acfg, buf, code - buf);
1030 g_assert (code - buf == *tramp_size);
1032 g_assert_not_reached ();
1037 * arch_emit_imt_thunk:
1039 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1040 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1041 * key is the IMT key, and ptr holds the address of a memory location holding
1042 * the address to branch to if the IMT arg matches the key. The array is
1043 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1045 * TRAMP_SIZE is set to the size of the emitted trampoline.
1048 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1050 #if defined(TARGET_AMD64)
1054 code = buf = g_malloc (256);
1056 /* FIXME: Optimize this, i.e. use binary search etc. */
1057 /* Maybe move the body into a separate function (slower, but much smaller) */
1059 /* R10 is a free register */
1062 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
1064 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1067 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
1069 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1072 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
1073 amd64_jump_code (code, labels [0]);
1076 mono_amd64_patch (labels [2], code);
1077 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
1078 amd64_jump_membase (code, AMD64_R10, 0);
1082 mono_amd64_patch (labels [1], code);
1083 x86_breakpoint (code);
1085 /* mov <OFFSET>(%rip), %r10 */
1086 emit_byte (acfg, '\x4d');
1087 emit_byte (acfg, '\x8b');
1088 emit_byte (acfg, '\x15');
1089 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1091 emit_bytes (acfg, buf, code - buf);
1093 *tramp_size = code - buf + 7;
1094 #elif defined(TARGET_X86)
1098 code = buf = g_malloc (256);
1100 /* Allocate a temporary stack slot */
1101 x86_push_reg (code, X86_EAX);
1103 x86_push_reg (code, X86_EAX);
1105 /* Load mscorlib got address */
1106 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1108 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1111 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1113 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1116 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1118 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1121 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1122 x86_jump_code (code, labels [0]);
1125 mono_x86_patch (labels [2], code);
1126 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1127 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1128 /* Save the target address to the temporary stack location */
1129 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1131 x86_pop_reg (code, X86_EAX);
1132 /* Jump to the target address */
1137 mono_x86_patch (labels [1], code);
1138 x86_breakpoint (code);
1140 emit_bytes (acfg, buf, code - buf);
1142 *tramp_size = code - buf;
1143 #elif defined(TARGET_ARM)
1145 guint8 *code, *code2, *labels [16];
1149 /* The IMT method is in v5 */
1151 /* Need at least two free registers, plus a slot for storing the pc */
1152 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1154 /* Load the parameter from the GOT */
1155 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1156 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1159 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1160 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1162 ARM_B_COND (code, ARMCOND_EQ, 0);
1164 /* End-of-loop check */
1165 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1167 ARM_B_COND (code, ARMCOND_EQ, 0);
1170 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1173 arm_patch (labels [4], labels [1]);
1176 arm_patch (labels [2], code);
1177 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1178 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1179 /* Save it to the third stack slot */
1180 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1181 /* Restore the registers and branch */
1182 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1185 arm_patch (labels [3], code);
1190 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1192 emit_bytes (acfg, buf, code - buf);
1193 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1195 *tramp_size = code - buf + 4;
1196 #elif defined(TARGET_POWERPC)
1198 guint8 *code, *labels [16];
1202 /* Load the mscorlib got address */
1203 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1204 /* Load the parameter from the GOT */
1205 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1206 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1208 /* Load and check key */
1210 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1211 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1213 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1215 /* End-of-loop check */
1216 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1218 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1221 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1224 mono_ppc_patch (labels [4], labels [1]);
1227 mono_ppc_patch (labels [2], code);
1228 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1229 /* r11 now contains the value of the vtable slot */
1230 /* this is not a function descriptor on ppc64 */
1231 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1232 ppc_mtctr (code, ppc_r11);
1233 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1236 mono_ppc_patch (labels [3], code);
1240 *tramp_size = code - buf;
1242 emit_bytes (acfg, buf, code - buf);
1244 g_assert_not_reached ();
1249 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1251 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1252 /* Based on code generated by gcc */
1253 img_writer_emit_unset_mode (acfg->w);
1256 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1257 ".section .ctors,\"aw\",@progbits\n"
1261 ".section .opd,\"aw\"\n"
1264 ".long .%s,.TOC.@tocbase32\n"
1267 ".type .%s,@function\n"
1269 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1271 ".section .ctors,\"aw\",@progbits\n"
1275 ".section .opd,\"aw\"\n"
1278 ".long .%1$s,.TOC.@tocbase32\n"
1279 ".size %1$s,.-%1$s\n"
1281 ".type .%1$s,@function\n"
1283 ".%1$s:\n", symbol);
1294 "lis 3, .Lglobals@h\n"
1295 "ori 3, 3, .Lglobals@l\n"
1296 "bl .mono_aot_register_module\n"
1304 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1306 ".size .%s,.-.%s\n", symbol, symbol);
1309 ".size .%1$s,.-.%1$s\n", symbol);
1315 /* END OF ARCH SPECIFIC CODE */
1318 mono_get_field_token (MonoClassField *field)
1320 MonoClass *klass = field->parent;
1323 for (i = 0; i < klass->field.count; ++i) {
1324 if (field == &klass->fields [i])
1325 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1328 g_assert_not_reached ();
1333 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1337 //printf ("ENCODE: %d 0x%x.\n", value, value);
1340 * Same encoding as the one used in the metadata, extended to handle values
1341 * greater than 0x1fffffff.
1343 if ((value >= 0) && (value <= 127))
1345 else if ((value >= 0) && (value <= 16383)) {
1346 p [0] = 0x80 | (value >> 8);
1347 p [1] = value & 0xff;
1349 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1350 p [0] = (value >> 24) | 0xc0;
1351 p [1] = (value >> 16) & 0xff;
1352 p [2] = (value >> 8) & 0xff;
1353 p [3] = value & 0xff;
1358 p [1] = (value >> 24) & 0xff;
1359 p [2] = (value >> 16) & 0xff;
1360 p [3] = (value >> 8) & 0xff;
1361 p [4] = value & 0xff;
1369 stream_init (MonoDynamicStream *sh)
1372 sh->alloc_size = 4096;
1373 sh->data = g_malloc (4096);
1375 /* So offsets are > 0 */
1380 make_room_in_stream (MonoDynamicStream *stream, int size)
1382 if (size <= stream->alloc_size)
1385 while (stream->alloc_size <= size) {
1386 if (stream->alloc_size < 4096)
1387 stream->alloc_size = 4096;
1389 stream->alloc_size *= 2;
1392 stream->data = g_realloc (stream->data, stream->alloc_size);
1396 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1400 make_room_in_stream (stream, stream->index + len);
1401 memcpy (stream->data + stream->index, data, len);
1402 idx = stream->index;
1403 stream->index += len;
1410 * Add data to the binary blob inside the aot image. Returns the offset inside the
1411 * blob where the data was stored.
1414 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1416 if (acfg->blob.alloc_size == 0)
1417 stream_init (&acfg->blob);
1419 return add_stream_data (&acfg->blob, (char*)data, data_len);
1423 * emit_offset_table:
1425 * Emit a table of increasing offsets in a compact form using differential encoding.
1426 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1427 * group size, the more compact the table becomes, but the slower it becomes to compute
1428 * a given entry. Returns the size of the table.
1431 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1433 gint32 current_offset;
1434 int i, buf_size, ngroups, index_entry_size;
1436 guint32 *index_offsets;
1438 ngroups = (noffsets + (group_size - 1)) / group_size;
1440 index_offsets = g_new0 (guint32, ngroups);
1442 buf_size = noffsets * 4;
1443 p = buf = g_malloc0 (buf_size);
1446 for (i = 0; i < noffsets; ++i) {
1447 //printf ("D: %d -> %d\n", i, offsets [i]);
1448 if ((i % group_size) == 0) {
1449 index_offsets [i / group_size] = p - buf;
1450 /* Emit the full value for these entries */
1451 encode_value (offsets [i], p, &p);
1453 /* The offsets are allowed to be non-increasing */
1454 //g_assert (offsets [i] >= current_offset);
1455 encode_value (offsets [i] - current_offset, p, &p);
1457 current_offset = offsets [i];
1460 if (ngroups && index_offsets [ngroups - 1] < 65000)
1461 index_entry_size = 2;
1463 index_entry_size = 4;
1465 /* Emit the header */
1466 emit_int32 (acfg, noffsets);
1467 emit_int32 (acfg, group_size);
1468 emit_int32 (acfg, ngroups);
1469 emit_int32 (acfg, index_entry_size);
1471 /* Emit the index */
1472 for (i = 0; i < ngroups; ++i) {
1473 if (index_entry_size == 2)
1474 emit_int16 (acfg, index_offsets [i]);
1476 emit_int32 (acfg, index_offsets [i]);
1480 emit_bytes (acfg, buf, p - buf);
1482 return (int)(p - buf) + (ngroups * 4);
1486 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1490 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1494 index = g_hash_table_size (cfg->image_hash);
1495 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1496 g_ptr_array_add (cfg->image_table, image);
1502 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1505 MonoClass *k = NULL;
1507 /* FIXME: Search referenced images as well */
1508 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1509 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1514 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1515 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1521 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1526 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1527 * standard metadata encoding.
1530 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1534 if (klass->generic_class) {
1536 g_assert (klass->type_token);
1538 /* Find a typespec for a class if possible */
1539 token = find_typespec_for_class (acfg, klass);
1541 encode_value (token, p, &p);
1542 encode_value (get_image_index (acfg, acfg->image), p, &p);
1544 MonoClass *gclass = klass->generic_class->container_class;
1545 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1548 /* Encode it ourselves */
1550 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1551 encode_value (MONO_TYPE_GENERICINST, p, &p);
1552 encode_klass_ref (acfg, gclass, p, &p);
1553 encode_value (inst->type_argc, p, &p);
1554 for (i = 0; i < inst->type_argc; ++i)
1555 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1557 } else if (klass->type_token) {
1558 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1559 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1560 encode_value (get_image_index (acfg, klass->image), p, &p);
1561 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1562 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1563 g_assert (container);
1566 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1567 encode_value (klass->byval_arg.type, p, &p);
1569 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1571 encode_value (container->is_method, p, &p);
1572 if (container->is_method)
1573 encode_method_ref (acfg, container->owner.method, p, &p);
1575 encode_klass_ref (acfg, container->owner.klass, p, &p);
1578 g_assert (klass->rank > 0);
1579 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1580 encode_value (get_image_index (acfg, klass->image), p, &p);
1581 encode_value (klass->rank, p, &p);
1582 encode_klass_ref (acfg, klass->element_class, p, &p);
1588 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1590 guint32 token = mono_get_field_token (field);
1593 encode_klass_ref (cfg, field->parent, p, &p);
1594 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1595 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1600 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1604 MonoGenericInst *inst;
1606 /* Encode the context */
1607 inst = context->class_inst;
1608 encode_value (inst ? 1 : 0, p, &p);
1610 encode_value (inst->type_argc, p, &p);
1611 for (i = 0; i < inst->type_argc; ++i)
1612 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1614 inst = context->method_inst;
1615 encode_value (inst ? 1 : 0, p, &p);
1617 encode_value (inst->type_argc, p, &p);
1618 for (i = 0; i < inst->type_argc; ++i)
1619 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1625 #define MAX_IMAGE_INDEX 250
1628 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1630 guint32 image_index = get_image_index (acfg, method->klass->image);
1631 guint32 token = method->token;
1632 MonoJumpInfoToken *ji;
1637 * The encoding for most methods is as follows:
1638 * - image index encoded as a leb128
1639 * - token index encoded as a leb128
1640 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1641 * types of method encodings.
1644 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1646 /* Mark methods which can't use aot trampolines because they need the further
1647 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1649 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1650 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1651 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1654 * Some wrapper methods are shared using their signature, encode their
1655 * stringified signature instead.
1656 * FIXME: Optimize disk usage
1659 if (method->wrapper_type) {
1660 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1661 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1662 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1663 name = mono_aot_wrapper_name (method);
1664 } else if (mono_marshal_method_from_wrapper (method) != method) {
1665 /* Direct wrapper, encode it normally */
1667 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1670 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1671 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1672 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1674 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1675 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1676 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1678 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1679 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1680 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1686 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1687 strcpy ((char*)p, name);
1688 p += strlen (name) + 1;
1690 } else if (method->wrapper_type) {
1691 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1693 encode_value (method->wrapper_type, p, &p);
1695 switch (method->wrapper_type) {
1696 case MONO_WRAPPER_REMOTING_INVOKE:
1697 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1698 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1701 m = mono_marshal_method_from_wrapper (method);
1703 encode_method_ref (acfg, m, p, &p);
1706 case MONO_WRAPPER_PROXY_ISINST:
1707 case MONO_WRAPPER_LDFLD:
1708 case MONO_WRAPPER_LDFLDA:
1709 case MONO_WRAPPER_STFLD:
1710 case MONO_WRAPPER_ISINST: {
1711 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1712 encode_klass_ref (acfg, proxy_class, p, &p);
1715 case MONO_WRAPPER_LDFLD_REMOTE:
1716 case MONO_WRAPPER_STFLD_REMOTE:
1718 case MONO_WRAPPER_ALLOC: {
1719 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1721 g_assert (info->alloc_type != -1);
1722 encode_value (info->alloc_type, p, &p);
1725 case MONO_WRAPPER_WRITE_BARRIER:
1727 case MONO_WRAPPER_STELEMREF:
1729 case MONO_WRAPPER_UNKNOWN:
1730 if (strcmp (method->name, "FastMonitorEnter") == 0)
1731 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1732 else if (strcmp (method->name, "FastMonitorExit") == 0)
1733 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1735 g_assert_not_reached ();
1737 case MONO_WRAPPER_SYNCHRONIZED:
1738 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1739 case MONO_WRAPPER_RUNTIME_INVOKE: {
1742 m = mono_marshal_method_from_wrapper (method);
1744 g_assert (m != method);
1745 encode_method_ref (acfg, m, p, &p);
1748 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1749 if (!strcmp (method->name, "ElementAddr")) {
1750 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1753 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1754 encode_value (info->rank, p, &p);
1755 encode_value (info->elem_size, p, &p);
1757 g_assert_not_reached ();
1761 g_assert_not_reached ();
1763 } else if (mono_method_signature (method)->is_inflated) {
1765 * This is a generic method, find the original token which referenced it and
1767 * Obtain the token from information recorded by the JIT.
1769 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1771 image_index = get_image_index (acfg, ji->image);
1772 g_assert (image_index < MAX_IMAGE_INDEX);
1775 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1776 encode_value (image_index, p, &p);
1777 encode_value (token, p, &p);
1779 MonoMethod *declaring;
1780 MonoGenericContext *context = mono_method_get_context (method);
1782 g_assert (method->is_inflated);
1783 declaring = ((MonoMethodInflated*)method)->declaring;
1786 * This might be a non-generic method of a generic instance, which
1787 * doesn't have a token since the reference is generated by the JIT
1788 * like Nullable:Box/Unbox, or by generic sharing.
1791 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1792 /* Encode the klass */
1793 encode_klass_ref (acfg, method->klass, p, &p);
1794 /* Encode the method */
1795 image_index = get_image_index (acfg, method->klass->image);
1796 g_assert (image_index < MAX_IMAGE_INDEX);
1797 g_assert (declaring->token);
1798 token = declaring->token;
1799 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1800 encode_value (image_index, p, &p);
1801 encode_value (token, p, &p);
1802 encode_generic_context (acfg, context, p, &p);
1804 } else if (token == 0) {
1805 /* This might be a method of a constructed type like int[,].Set */
1806 /* Obtain the token from information recorded by the JIT */
1807 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1809 image_index = get_image_index (acfg, ji->image);
1810 g_assert (image_index < MAX_IMAGE_INDEX);
1813 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1814 encode_value (image_index, p, &p);
1815 encode_value (token, p, &p);
1818 g_assert (method->klass->rank);
1820 /* Encode directly */
1821 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1822 encode_klass_ref (acfg, method->klass, p, &p);
1823 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1824 encode_value (0, p, &p);
1825 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1826 encode_value (1, p, &p);
1827 else if (!strcmp (method->name, "Get"))
1828 encode_value (2, p, &p);
1829 else if (!strcmp (method->name, "Address"))
1830 encode_value (3, p, &p);
1831 else if (!strcmp (method->name, "Set"))
1832 encode_value (4, p, &p);
1834 g_assert_not_reached ();
1837 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1838 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1844 compare_patches (gconstpointer a, gconstpointer b)
1848 i = (*(MonoJumpInfo**)a)->ip.i;
1849 j = (*(MonoJumpInfo**)b)->ip.i;
1863 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1866 static inline gboolean
1867 is_plt_patch (MonoJumpInfo *patch_info)
1869 switch (patch_info->type) {
1870 case MONO_PATCH_INFO_METHOD:
1871 case MONO_PATCH_INFO_INTERNAL_METHOD:
1872 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1873 case MONO_PATCH_INFO_ICALL_ADDR:
1874 case MONO_PATCH_INFO_CLASS_INIT:
1875 case MONO_PATCH_INFO_RGCTX_FETCH:
1876 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1877 case MONO_PATCH_INFO_MONITOR_ENTER:
1878 case MONO_PATCH_INFO_MONITOR_EXIT:
1879 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1887 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1891 if (is_plt_patch (patch_info)) {
1892 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1894 // FIXME: This breaks the calculation of final_got_size
1895 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1897 * Allocate a separate PLT slot for each such patch, since some plt
1898 * entries will refer to the method itself, and some will refer to the
1907 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1909 g_assert (!acfg->final_got_size);
1911 res = acfg->plt_offset;
1912 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1913 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1914 acfg->plt_offset ++;
1924 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1925 * JI could be found if it exists, otherwise allocates a new one.
1928 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1932 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1934 return got_offset - 1;
1936 got_offset = acfg->got_offset;
1937 acfg->got_offset ++;
1939 if (acfg->final_got_size)
1940 g_assert (got_offset < acfg->final_got_size);
1942 acfg->stats.got_slots ++;
1943 acfg->stats.got_slot_types [ji->type] ++;
1945 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1946 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1947 g_ptr_array_add (acfg->got_patches, ji);
1952 /* Add a method to the list of methods which need to be emitted */
1954 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1957 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1958 g_ptr_array_add (acfg->methods, method);
1959 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1960 acfg->nmethods = acfg->methods->len + 1;
1963 if (method->wrapper_type || extra)
1964 g_ptr_array_add (acfg->extra_methods, method);
1968 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1970 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1978 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1982 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1986 index = acfg->method_index;
1987 add_method_with_index (acfg, method, index, extra);
1989 /* FIXME: Fix quadratic behavior */
1990 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1992 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1994 acfg->method_index ++;
2000 add_method (MonoAotCompile *acfg, MonoMethod *method)
2002 return add_method_full (acfg, method, FALSE, 0);
2006 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2008 add_method_full (acfg, method, TRUE, 0);
2012 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2014 add_method_full (acfg, method, TRUE, depth);
2018 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2020 MonoAotCompile *acfg = user_data;
2021 MonoJitICallInfo *callinfo = value;
2022 MonoMethod *wrapper;
2028 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2029 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2032 add_method (acfg, wrapper);
2036 get_runtime_invoke_sig (MonoMethodSignature *sig)
2038 MonoMethodBuilder *mb;
2041 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2042 m = mono_mb_create_method (mb, sig, 16);
2043 return mono_marshal_get_runtime_invoke (m, FALSE);
2047 can_marshal_struct (MonoClass *klass)
2049 MonoClassField *field;
2050 gboolean can_marshal = TRUE;
2051 gpointer iter = NULL;
2053 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2056 /* Only allow a few field types to avoid asserts in the marshalling code */
2057 while ((field = mono_class_get_fields (klass, &iter))) {
2058 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2061 switch (field->type->type) {
2066 case MONO_TYPE_BOOLEAN:
2069 case MONO_TYPE_CHAR:
2077 case MONO_TYPE_STRING:
2079 case MONO_TYPE_VALUETYPE:
2080 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2081 can_marshal = FALSE;
2084 can_marshal = FALSE;
2090 /* Its hard to compute whenever these can be marshalled or not */
2091 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2098 add_wrappers (MonoAotCompile *acfg)
2100 MonoMethod *method, *m;
2102 MonoMethodSignature *sig, *csig;
2106 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2107 * so there is only one wrapper of a given type, or inlining their contents into their
2112 * FIXME: This depends on the fact that different wrappers have different
2116 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2118 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2119 gboolean skip = FALSE;
2121 method = mono_get_method (acfg->image, token, NULL);
2123 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2124 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2125 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2128 if (method->is_generic || method->klass->generic_container)
2131 /* Skip methods which can not be handled by get_runtime_invoke () */
2132 sig = mono_method_signature (method);
2133 if ((sig->ret->type == MONO_TYPE_PTR) ||
2134 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2137 for (j = 0; j < sig->param_count; j++) {
2138 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2142 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2143 if (!method->klass->contextbound) {
2144 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2145 gboolean has_nullable = FALSE;
2147 for (j = 0; j < sig->param_count; j++) {
2148 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2149 has_nullable = TRUE;
2152 if (info && !has_nullable) {
2153 /* Supported by the dynamic runtime-invoke wrapper */
2161 //printf ("%s\n", mono_method_full_name (method, TRUE));
2162 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2166 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2167 #ifdef MONO_ARCH_HAVE_TLS_GET
2168 MonoMethodDesc *desc;
2169 MonoMethod *orig_method;
2173 /* Runtime invoke wrappers */
2175 /* void runtime-invoke () [.cctor] */
2176 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2177 csig->ret = &mono_defaults.void_class->byval_arg;
2178 add_method (acfg, get_runtime_invoke_sig (csig));
2180 /* void runtime-invoke () [Finalize] */
2181 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2183 csig->ret = &mono_defaults.void_class->byval_arg;
2184 add_method (acfg, get_runtime_invoke_sig (csig));
2186 /* void runtime-invoke (string) [exception ctor] */
2187 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2189 csig->ret = &mono_defaults.void_class->byval_arg;
2190 csig->params [0] = &mono_defaults.string_class->byval_arg;
2191 add_method (acfg, get_runtime_invoke_sig (csig));
2193 /* void runtime-invoke (string, string) [exception ctor] */
2194 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2196 csig->ret = &mono_defaults.void_class->byval_arg;
2197 csig->params [0] = &mono_defaults.string_class->byval_arg;
2198 csig->params [1] = &mono_defaults.string_class->byval_arg;
2199 add_method (acfg, get_runtime_invoke_sig (csig));
2201 /* string runtime-invoke () [Exception.ToString ()] */
2202 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2204 csig->ret = &mono_defaults.string_class->byval_arg;
2205 add_method (acfg, get_runtime_invoke_sig (csig));
2207 /* void runtime-invoke (string, Exception) [exception ctor] */
2208 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2210 csig->ret = &mono_defaults.void_class->byval_arg;
2211 csig->params [0] = &mono_defaults.string_class->byval_arg;
2212 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2213 add_method (acfg, get_runtime_invoke_sig (csig));
2215 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2216 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2218 csig->ret = &(mono_class_from_name (
2219 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2220 csig->params [0] = &mono_defaults.string_class->byval_arg;
2221 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2222 add_method (acfg, get_runtime_invoke_sig (csig));
2224 /* runtime-invoke used by finalizers */
2225 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2227 /* This is used by mono_runtime_capture_context () */
2228 method = mono_get_context_capture_method ();
2230 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2232 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2233 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2236 /* JIT icall wrappers */
2237 /* FIXME: locking */
2238 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2241 add_method (acfg, mono_marshal_get_stelemref ());
2243 #ifdef MONO_ARCH_HAVE_TLS_GET
2244 /* Managed Allocators */
2245 nallocators = mono_gc_get_managed_allocator_types ();
2246 for (i = 0; i < nallocators; ++i) {
2247 m = mono_gc_get_managed_allocator_by_type (i);
2249 add_method (acfg, m);
2252 /* Monitor Enter/Exit */
2253 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2254 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2255 g_assert (orig_method);
2256 mono_method_desc_free (desc);
2257 method = mono_monitor_get_fast_path (orig_method);
2259 add_method (acfg, method);
2261 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2262 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2263 g_assert (orig_method);
2264 mono_method_desc_free (desc);
2265 method = mono_monitor_get_fast_path (orig_method);
2267 add_method (acfg, method);
2272 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2273 * we use the original method instead at runtime.
2274 * Since full-aot doesn't support remoting, this is not a problem.
2277 /* remoting-invoke wrappers */
2278 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2279 MonoMethodSignature *sig;
2281 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2282 method = mono_get_method (acfg->image, token, NULL);
2284 sig = mono_method_signature (method);
2286 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2287 m = mono_marshal_get_remoting_invoke_with_check (method);
2289 add_method (acfg, m);
2294 /* delegate-invoke wrappers */
2295 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2298 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2299 klass = mono_class_get (acfg->image, token);
2301 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2302 method = mono_get_delegate_invoke (klass);
2304 m = mono_marshal_get_delegate_invoke (method, NULL);
2306 add_method (acfg, m);
2308 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2309 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2311 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2312 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2316 /* Synchronized wrappers */
2317 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2318 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2319 method = mono_get_method (acfg->image, token, NULL);
2321 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2322 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2325 /* pinvoke wrappers */
2326 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2328 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2330 method = mono_get_method (acfg->image, token, NULL);
2332 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2333 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2334 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2338 /* native-to-managed wrappers */
2339 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2341 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2342 MonoCustomAttrInfo *cattr;
2345 method = mono_get_method (acfg->image, token, NULL);
2348 * Only generate native-to-managed wrappers for methods which have an
2349 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2350 * name to avoid defining a new assembly to contain it.
2352 cattr = mono_custom_attrs_from_method (method);
2355 for (j = 0; j < cattr->num_attrs; ++j)
2356 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2358 if (j < cattr->num_attrs) {
2359 MonoCustomAttrEntry *e = &cattr->attrs [j];
2360 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2361 const char *p = (const char*)e->data;
2367 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2369 g_assert (sig->param_count == 1);
2370 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2373 * Decode the cattr manually since we can't create objects
2374 * during aot compilation.
2380 /* From load_cattr_value () in reflection.c */
2381 slen = mono_metadata_decode_value (p, &p);
2382 n = g_memdup (p, slen + 1);
2384 t = mono_reflection_type_from_name (n, acfg->image);
2388 klass = mono_class_from_mono_type (t);
2389 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2391 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, NULL));
2395 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2396 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2397 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2401 /* StructureToPtr/PtrToStructure wrappers */
2402 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2405 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2406 klass = mono_class_get (acfg->image, token);
2408 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2409 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2410 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2416 has_type_vars (MonoClass *klass)
2418 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2421 return has_type_vars (klass->element_class);
2422 if (klass->generic_class) {
2423 MonoGenericContext *context = &klass->generic_class->context;
2424 if (context->class_inst) {
2427 for (i = 0; i < context->class_inst->type_argc; ++i)
2428 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2436 method_has_type_vars (MonoMethod *method)
2438 if (has_type_vars (method->klass))
2441 if (method->is_inflated) {
2442 MonoGenericContext *context = mono_method_get_context (method);
2443 if (context->method_inst) {
2446 for (i = 0; i < context->method_inst->type_argc; ++i)
2447 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2455 * add_generic_class:
2457 * Add all methods of a generic class.
2460 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2465 mono_class_init (klass);
2467 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2470 if (has_type_vars (klass))
2473 if (!klass->generic_class && !klass->rank)
2477 while ((method = mono_class_get_methods (klass, &iter))) {
2478 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2482 if (method->is_generic)
2487 * FIXME: Instances which are referenced by these methods are not added,
2488 * for example Array.Resize<int> for List<int>.Add ().
2490 add_extra_method (acfg, method);
2493 if (klass->delegate) {
2494 method = mono_get_delegate_invoke (klass);
2496 method = mono_marshal_get_delegate_invoke (method, NULL);
2498 add_method (acfg, method);
2502 * For ICollection<T>, add instances of the helper methods
2503 * in Array, since a T[] could be cast to ICollection<T>.
2505 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2506 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2507 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2508 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2512 if (!strcmp (klass->name, "IEnumerator`1"))
2513 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2515 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2517 /* Add the T[]/InternalEnumerator class */
2518 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2522 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2523 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2527 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2528 add_generic_class (acfg, nclass);
2532 while ((method = mono_class_get_methods (array_class, &iter))) {
2533 if (strstr (method->name, name_prefix)) {
2534 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2535 add_extra_method (acfg, m);
2539 g_free (name_prefix);
2542 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2543 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2544 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2545 MonoClass *icomparable, *gcomparer;
2546 MonoGenericContext ctx;
2547 MonoType *args [16];
2549 memset (&ctx, 0, sizeof (ctx));
2551 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2552 g_assert (icomparable);
2553 args [0] = &tclass->byval_arg;
2554 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2556 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2557 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2558 g_assert (gcomparer);
2559 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2565 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2568 MonoGenericContext ctx;
2569 MonoType *args [16];
2571 memset (&ctx, 0, sizeof (ctx));
2573 for (i = 0; i < ninsts; ++i) {
2574 args [0] = insts [i];
2575 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2576 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2581 * add_generic_instances:
2583 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2586 add_generic_instances (MonoAotCompile *acfg)
2591 MonoMethodHeader *header;
2592 MonoMethodSignature *sig;
2593 MonoGenericContext *context;
2595 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2596 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2597 method = mono_get_method (acfg->image, token, NULL);
2599 if (method->klass->image != acfg->image)
2602 context = mono_method_get_context (method);
2604 if (context && ((context->class_inst && context->class_inst->is_open)))
2608 * For open methods, create an instantiation which can be passed to the JIT.
2609 * FIXME: Handle class_inst as well.
2611 if (context && context->method_inst && context->method_inst->is_open) {
2612 MonoGenericContext shared_context;
2613 MonoGenericInst *inst;
2614 MonoType **type_argv;
2616 MonoMethod *declaring_method;
2617 gboolean supported = TRUE;
2619 /* Check that the context doesn't contain open constructed types */
2620 if (context->class_inst) {
2621 inst = context->class_inst;
2622 for (i = 0; i < inst->type_argc; ++i) {
2623 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)
2625 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2629 if (context->method_inst) {
2630 inst = context->method_inst;
2631 for (i = 0; i < inst->type_argc; ++i) {
2632 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)
2634 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2642 memset (&shared_context, 0, sizeof (MonoGenericContext));
2644 inst = context->class_inst;
2646 type_argv = g_new0 (MonoType*, inst->type_argc);
2647 for (i = 0; i < inst->type_argc; ++i) {
2648 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)
2649 type_argv [i] = &mono_defaults.object_class->byval_arg;
2651 type_argv [i] = inst->type_argv [i];
2654 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2658 inst = context->method_inst;
2660 type_argv = g_new0 (MonoType*, inst->type_argc);
2661 for (i = 0; i < inst->type_argc; ++i) {
2662 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)
2663 type_argv [i] = &mono_defaults.object_class->byval_arg;
2665 type_argv [i] = inst->type_argv [i];
2668 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2672 if (method->is_generic || method->klass->generic_container)
2673 declaring_method = method;
2675 declaring_method = mono_method_get_declaring_generic_method (method);
2677 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2681 * If the method is fully sharable, it was already added in place of its
2682 * generic definition.
2684 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2688 * FIXME: Partially shared methods are not shared here, so we end up with
2689 * many identical methods.
2691 add_extra_method (acfg, method);
2694 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2697 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2699 klass = mono_class_get (acfg->image, token);
2700 if (!klass || klass->rank)
2703 add_generic_class (acfg, klass);
2706 /* Add types of args/locals */
2707 for (i = 0; i < acfg->methods->len; ++i) {
2710 method = g_ptr_array_index (acfg->methods, i);
2712 sig = mono_method_signature (method);
2715 for (j = 0; j < sig->param_count; ++j)
2716 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2717 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2720 header = mono_method_get_header (method);
2723 for (j = 0; j < header->num_locals; ++j)
2724 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2725 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2729 if (acfg->image == mono_defaults.corlib) {
2731 MonoType *insts [256];
2734 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2735 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2736 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2737 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2738 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2739 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2740 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2741 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2742 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2743 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2744 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2745 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2747 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2748 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2750 add_instances_of (acfg, klass, insts, ninsts);
2751 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2753 add_instances_of (acfg, klass, insts, ninsts);
2755 /* Add instances of the array generic interfaces for primitive types */
2756 /* This will add instances of the InternalArray_ helper methods in Array too */
2757 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2759 add_instances_of (acfg, klass, insts, ninsts);
2760 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2762 add_instances_of (acfg, klass, insts, ninsts);
2763 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2765 add_instances_of (acfg, klass, insts, ninsts);
2768 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2769 * used for all instances of GetGenericValueImpl by the AOT runtime.
2772 MonoGenericContext ctx;
2773 MonoType *args [16];
2774 MonoMethod *get_method;
2775 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2777 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2780 memset (&ctx, 0, sizeof (ctx));
2781 args [0] = &mono_defaults.object_class->byval_arg;
2782 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2783 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2790 * is_direct_callable:
2792 * Return whenever the method identified by JI is directly callable without
2793 * going through the PLT.
2796 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2798 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2799 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2801 gboolean direct_callable = TRUE;
2803 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2804 direct_callable = FALSE;
2805 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2806 // FIXME: Maybe call the wrapper directly ?
2807 direct_callable = FALSE;
2809 if (direct_callable)
2818 * emit_and_reloc_code:
2820 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2821 * is true, calls are made through the GOT too. This is used for emitting trampolines
2822 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2823 * since trampolines are needed to make PTL work.
2826 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2828 int i, pindex, start_index, method_index;
2830 MonoJumpInfo *patch_info;
2831 MonoMethodHeader *header;
2832 gboolean skip, direct_call;
2834 char direct_call_target [128];
2837 header = mono_method_get_header (method);
2839 method_index = get_method_index (acfg, method);
2842 /* Collect and sort relocations */
2843 patches = g_ptr_array_new ();
2844 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2845 g_ptr_array_add (patches, patch_info);
2846 g_ptr_array_sort (patches, compare_patches);
2849 for (i = 0; i < code_len; i++) {
2851 for (pindex = start_index; pindex < patches->len; ++pindex) {
2852 patch_info = g_ptr_array_index (patches, pindex);
2853 if (patch_info->ip.i >= i)
2857 #ifdef MONO_ARCH_AOT_SUPPORTED
2859 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2860 start_index = pindex;
2862 switch (patch_info->type) {
2863 case MONO_PATCH_INFO_NONE:
2865 case MONO_PATCH_INFO_GOT_OFFSET: {
2868 arch_emit_got_offset (acfg, code + i, &code_size);
2871 patch_info->type = MONO_PATCH_INFO_NONE;
2876 * If this patch is a call, try emitting a direct call instead of
2877 * through a PLT entry. This is possible if the called method is in
2878 * the same assembly and requires no initialization.
2880 direct_call = FALSE;
2881 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2882 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2883 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2884 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2886 sprintf (direct_call_target, callee_cfg->asm_symbol);
2887 patch_info->type = MONO_PATCH_INFO_NONE;
2888 acfg->stats.direct_calls ++;
2891 acfg->stats.all_calls ++;
2894 if (!got_only && !direct_call) {
2895 int plt_offset = get_plt_offset (acfg, patch_info);
2896 if (plt_offset != -1) {
2897 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2899 sprintf (direct_call_target, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
2901 /* Nullify the patch */
2902 patch_info->type = MONO_PATCH_INFO_NONE;
2909 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2914 got_slot = get_got_offset (acfg, patch_info);
2916 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2923 #endif /* MONO_ARCH_AOT_SUPPORTED */
2926 /* Find next patch */
2928 for (pindex = start_index; pindex < patches->len; ++pindex) {
2929 patch_info = g_ptr_array_index (patches, pindex);
2930 if (patch_info->ip.i >= i)
2934 /* Try to emit multiple bytes at once */
2935 if (pindex < patches->len && patch_info->ip.i > i) {
2936 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2937 i = patch_info->ip.i - 1;
2939 emit_bytes (acfg, code + i, 1);
2948 * Modify SYMBOL so it only includes characters permissible in symbols.
2951 sanitize_symbol (char *symbol)
2953 int i, len = strlen (symbol);
2955 for (i = 0; i < len; ++i)
2956 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2961 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2963 char *name1, *name2, *cached;
2964 int i, j, len, count;
2966 name1 = mono_method_full_name (method, TRUE);
2967 len = strlen (name1);
2968 name2 = malloc (strlen (prefix) + len + 16);
2969 memcpy (name2, prefix, strlen (prefix));
2970 j = strlen (prefix);
2971 for (i = 0; i < len; ++i) {
2972 if (isalnum (name1 [i])) {
2973 name2 [j ++] = name1 [i];
2974 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2976 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2979 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2988 while (g_hash_table_lookup (cache, name2)) {
2989 sprintf (name2 + j, "_%d", count);
2993 cached = g_strdup (name2);
2994 g_hash_table_insert (cache, cached, cached);
3000 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3005 char *debug_sym = NULL;
3007 int func_alignment = AOT_FUNC_ALIGNMENT;
3008 MonoMethodHeader *header;
3010 method = cfg->orig_method;
3011 code = cfg->native_code;
3012 header = mono_method_get_header (method);
3014 method_index = get_method_index (acfg, method);
3016 /* Make the labels local */
3017 sprintf (symbol, "%s", cfg->asm_symbol);
3019 emit_section_change (acfg, ".text", 0);
3020 emit_alignment (acfg, func_alignment);
3021 emit_label (acfg, symbol);
3023 if (acfg->aot_opts.write_symbols) {
3025 * Write a C style symbol for every method, this has two uses:
3026 * - it works on platforms where the dwarf debugging info is not
3028 * - it allows the setting of breakpoints of aot-ed methods.
3030 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3032 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3033 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3034 emit_label (acfg, debug_sym);
3037 if (cfg->verbose_level > 0)
3038 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3040 acfg->stats.code_size += cfg->code_len;
3042 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3044 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3048 if (acfg->aot_opts.write_symbols) {
3049 emit_symbol_size (acfg, debug_sym, ".");
3053 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3054 emit_label (acfg, symbol);
3060 * Encode PATCH_INFO into its disk representation.
3063 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3067 switch (patch_info->type) {
3068 case MONO_PATCH_INFO_NONE:
3070 case MONO_PATCH_INFO_IMAGE:
3071 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3073 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3075 case MONO_PATCH_INFO_METHOD_REL:
3076 encode_value ((gint)patch_info->data.offset, p, &p);
3078 case MONO_PATCH_INFO_SWITCH: {
3079 gpointer *table = (gpointer *)patch_info->data.table->table;
3082 encode_value (patch_info->data.table->table_size, p, &p);
3083 for (k = 0; k < patch_info->data.table->table_size; k++)
3084 encode_value ((int)(gssize)table [k], p, &p);
3087 case MONO_PATCH_INFO_METHODCONST:
3088 case MONO_PATCH_INFO_METHOD:
3089 case MONO_PATCH_INFO_METHOD_JUMP:
3090 case MONO_PATCH_INFO_ICALL_ADDR:
3091 case MONO_PATCH_INFO_METHOD_RGCTX:
3092 encode_method_ref (acfg, patch_info->data.method, p, &p);
3094 case MONO_PATCH_INFO_INTERNAL_METHOD:
3095 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3096 guint32 len = strlen (patch_info->data.name);
3098 encode_value (len, p, &p);
3100 memcpy (p, patch_info->data.name, len);
3105 case MONO_PATCH_INFO_LDSTR: {
3106 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3107 guint32 token = patch_info->data.token->token;
3108 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3109 encode_value (image_index, p, &p);
3110 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3113 case MONO_PATCH_INFO_RVA:
3114 case MONO_PATCH_INFO_DECLSEC:
3115 case MONO_PATCH_INFO_LDTOKEN:
3116 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3117 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3118 encode_value (patch_info->data.token->token, p, &p);
3119 encode_value (patch_info->data.token->has_context, p, &p);
3120 if (patch_info->data.token->has_context)
3121 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3123 case MONO_PATCH_INFO_EXC_NAME: {
3124 MonoClass *ex_class;
3127 mono_class_from_name (mono_defaults.exception_class->image,
3128 "System", patch_info->data.target);
3129 g_assert (ex_class);
3130 encode_klass_ref (acfg, ex_class, p, &p);
3133 case MONO_PATCH_INFO_R4:
3134 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3136 case MONO_PATCH_INFO_R8:
3137 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3138 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3140 case MONO_PATCH_INFO_VTABLE:
3141 case MONO_PATCH_INFO_CLASS:
3142 case MONO_PATCH_INFO_IID:
3143 case MONO_PATCH_INFO_ADJUSTED_IID:
3144 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3146 case MONO_PATCH_INFO_CLASS_INIT:
3147 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3148 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3150 case MONO_PATCH_INFO_FIELD:
3151 case MONO_PATCH_INFO_SFLDA:
3152 encode_field_info (acfg, patch_info->data.field, p, &p);
3154 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3156 case MONO_PATCH_INFO_RGCTX_FETCH: {
3157 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3159 encode_method_ref (acfg, entry->method, p, &p);
3160 encode_value (entry->in_mrgctx, p, &p);
3161 encode_value (entry->info_type, p, &p);
3162 encode_value (entry->data->type, p, &p);
3163 encode_patch (acfg, entry->data, p, &p);
3166 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3167 case MONO_PATCH_INFO_MONITOR_ENTER:
3168 case MONO_PATCH_INFO_MONITOR_EXIT:
3169 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3171 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3172 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3173 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3176 g_warning ("unable to handle jump info %d", patch_info->type);
3177 g_assert_not_reached ();
3184 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3187 guint32 pindex, offset;
3188 MonoJumpInfo *patch_info;
3190 encode_value (n_patches, p, &p);
3192 for (pindex = 0; pindex < patches->len; ++pindex) {
3193 patch_info = g_ptr_array_index (patches, pindex);
3195 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3199 offset = get_got_offset (acfg, patch_info);
3200 encode_value (offset, p, &p);
3207 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3211 int pindex, buf_size, n_patches;
3214 MonoJumpInfo *patch_info;
3215 MonoMethodHeader *header;
3216 guint32 method_index;
3218 guint32 first_got_offset;
3220 method = cfg->orig_method;
3221 code = cfg->native_code;
3222 header = mono_method_get_header (method);
3224 method_index = get_method_index (acfg, method);
3226 /* Sort relocations */
3227 patches = g_ptr_array_new ();
3228 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3229 g_ptr_array_add (patches, patch_info);
3230 g_ptr_array_sort (patches, compare_patches);
3232 first_got_offset = acfg->cfgs [method_index]->got_offset;
3234 /**********************/
3235 /* Encode method info */
3236 /**********************/
3238 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3239 p = buf = g_malloc (buf_size);
3241 if (mono_class_get_cctor (method->klass))
3242 encode_klass_ref (acfg, method->klass, p, &p);
3244 /* Not needed when loading the method */
3245 encode_value (0, p, &p);
3248 if (cfg->opt & MONO_OPT_SHARED) {
3249 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3250 for (l = cfg->ldstr_list; l; l = l->next) {
3251 encode_value ((long)l->data, p, &p);
3255 /* Used only in shared mode */
3256 g_assert (!cfg->ldstr_list);
3259 for (pindex = 0; pindex < patches->len; ++pindex) {
3260 patch_info = g_ptr_array_index (patches, pindex);
3262 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3263 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3264 patch_info->type = MONO_PATCH_INFO_NONE;
3269 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3270 /* Stored in a GOT slot initialized at module load time */
3271 patch_info->type = MONO_PATCH_INFO_NONE;
3275 if (is_plt_patch (patch_info)) {
3276 /* Calls are made through the PLT */
3277 patch_info->type = MONO_PATCH_INFO_NONE;
3285 g_assert (cfg->has_got_slots);
3287 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3289 acfg->stats.info_size += p - buf;
3291 g_assert (p - buf < buf_size);
3293 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3298 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3300 guint32 cache_index;
3303 /* Reuse the unwind module to canonize and store unwind info entries */
3304 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3306 /* Use +/- 1 to distinguish 0s from missing entries */
3307 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3315 * It would be easier to use assembler symbols, but the caller needs an
3318 offset = acfg->unwind_info_offset;
3319 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3320 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3323 encode_value (encoded_len, p, &p);
3325 acfg->unwind_info_offset += encoded_len + (p - buf);
3331 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3334 int i, k, buf_size, method_index;
3335 guint32 debug_info_size;
3337 MonoMethodHeader *header;
3338 guint8 *p, *buf, *debug_info;
3339 MonoJitInfo *jinfo = cfg->jit_info;
3341 gboolean use_unwind_ops = FALSE;
3342 MonoSeqPointInfo *seq_points;
3344 method = cfg->orig_method;
3345 code = cfg->native_code;
3346 header = mono_method_get_header (method);
3348 method_index = get_method_index (acfg, method);
3350 if (!acfg->aot_opts.nodebug) {
3351 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3354 debug_info_size = 0;
3357 seq_points = cfg->seq_point_info;
3359 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3360 p = buf = g_malloc (buf_size);
3362 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3363 use_unwind_ops = cfg->unwind_ops != NULL;
3366 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);
3368 encode_value (flags, p, &p);
3370 if (use_unwind_ops) {
3371 guint32 encoded_len;
3375 * This is a duplicate of the data in the .debug_frame section, but that
3376 * section cannot be accessed using the dl interface.
3378 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3379 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3382 encode_value (jinfo->used_regs, p, &p);
3385 /*Encode the number of holes before the number of clauses to make decoding easier*/
3386 if (jinfo->has_try_block_holes) {
3387 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3388 encode_value (table->num_holes, p, &p);
3391 /* Exception table */
3392 if (cfg->compile_llvm) {
3393 /* The assembly might be CIL stripped so emit the data ourselves */
3394 if (header->num_clauses)
3395 encode_value (header->num_clauses, p, &p);
3397 for (k = 0; k < header->num_clauses; ++k) {
3398 MonoExceptionClause *clause;
3400 clause = &header->clauses [k];
3402 encode_value (clause->flags, p, &p);
3403 if (clause->data.catch_class) {
3404 encode_value (1, p, &p);
3405 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3407 encode_value (0, p, &p);
3411 if (jinfo->num_clauses)
3412 encode_value (jinfo->num_clauses, p, &p);
3414 for (k = 0; k < jinfo->num_clauses; ++k) {
3415 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3417 encode_value (ei->flags, p, &p);
3418 encode_value (ei->exvar_offset, p, &p);
3420 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3421 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3423 if (ei->data.catch_class) {
3424 encode_value (1, p, &p);
3425 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3427 encode_value (0, p, &p);
3431 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3432 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3433 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3437 if (jinfo->has_generic_jit_info) {
3438 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3440 encode_value (gi->has_this ? 1 : 0, p, &p);
3441 encode_value (gi->this_reg, p, &p);
3442 encode_value (gi->this_offset, p, &p);
3445 * Need to encode jinfo->method too, since it is not equal to 'method'
3446 * when using generic sharing.
3448 encode_method_ref (acfg, jinfo->method, p, &p);
3451 if (jinfo->has_try_block_holes) {
3452 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3453 for (i = 0; i < table->num_holes; ++i) {
3454 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3455 encode_value (hole->clause, p, &p);
3456 encode_value (hole->length, p, &p);
3457 encode_value (hole->offset, p, &p);
3462 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3464 encode_value (seq_points->len, p, &p);
3465 last_il_offset = last_native_offset = 0;
3466 for (i = 0; i < seq_points->len; ++i) {
3467 SeqPoint *sp = &seq_points->seq_points [i];
3468 il_offset = sp->il_offset;
3469 native_offset = sp->native_offset;
3470 encode_value (il_offset - last_il_offset, p, &p);
3471 encode_value (native_offset - last_native_offset, p, &p);
3472 last_il_offset = il_offset;
3473 last_native_offset = native_offset;
3475 encode_value (sp->next_len, p, &p);
3476 for (j = 0; j < sp->next_len; ++j)
3477 encode_value (sp->next [j], p, &p);
3482 g_assert (debug_info_size < buf_size);
3484 encode_value (debug_info_size, p, &p);
3485 if (debug_info_size) {
3486 memcpy (p, debug_info, debug_info_size);
3487 p += debug_info_size;
3488 g_free (debug_info);
3491 acfg->stats.ex_info_size += p - buf;
3493 g_assert (p - buf < buf_size);
3496 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3501 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3503 MonoClass *klass = mono_class_get (acfg->image, token);
3505 int i, buf_size, res;
3506 gboolean no_special_static, cant_encode;
3507 gpointer iter = NULL;
3509 buf_size = 10240 + (klass->vtable_size * 16);
3510 p = buf = g_malloc (buf_size);
3514 mono_class_init (klass);
3516 mono_class_get_nested_types (klass, &iter);
3517 g_assert (klass->nested_classes_inited);
3519 mono_class_setup_vtable (klass);
3522 * Emit all the information which is required for creating vtables so
3523 * the runtime does not need to create the MonoMethod structures which
3524 * take up a lot of space.
3527 no_special_static = !mono_class_has_special_static_fields (klass);
3529 /* Check whenever we have enough info to encode the vtable */
3530 cant_encode = FALSE;
3531 for (i = 0; i < klass->vtable_size; ++i) {
3532 MonoMethod *cm = klass->vtable [i];
3534 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3538 if (klass->generic_container || cant_encode) {
3539 encode_value (-1, p, &p);
3541 encode_value (klass->vtable_size, p, &p);
3542 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);
3543 if (klass->has_cctor)
3544 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3545 if (klass->has_finalize)
3546 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3548 encode_value (klass->instance_size, p, &p);
3549 encode_value (mono_class_data_size (klass), p, &p);
3550 encode_value (klass->packing_size, p, &p);
3551 encode_value (klass->min_align, p, &p);
3553 for (i = 0; i < klass->vtable_size; ++i) {
3554 MonoMethod *cm = klass->vtable [i];
3557 encode_method_ref (acfg, cm, p, &p);
3559 encode_value (0, p, &p);
3563 acfg->stats.class_info_size += p - buf;
3565 g_assert (p - buf < buf_size);
3566 res = add_to_blob (acfg, buf, p - buf);
3573 * Calls made from AOTed code are routed through a table of jumps similar to the
3574 * ELF PLT (Program Linkage Table). The differences are the following:
3575 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3576 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3577 * jumps. This means the jumps need to be patched when the address of the callee is
3578 * known. Initially the PLT entries jump to code which transfers control to the
3579 * AOT runtime through the first PLT entry.
3582 emit_plt (MonoAotCompile *acfg)
3588 cache = g_hash_table_new (g_str_hash, g_str_equal);
3591 sprintf (symbol, "plt");
3593 emit_section_change (acfg, ".text", 0);
3594 emit_global (acfg, symbol, TRUE);
3596 /* This section will be made read-write by the AOT loader */
3597 emit_alignment (acfg, mono_pagesize ());
3599 emit_alignment (acfg, 16);
3601 emit_label (acfg, symbol);
3602 emit_label (acfg, acfg->plt_symbol);
3604 for (i = 0; i < acfg->plt_offset; ++i) {
3606 char *debug_sym = NULL;
3609 sprintf (label, "%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, i);
3613 * If the target is directly callable, alias the plt symbol to point to
3615 * FIXME: Use this to simplify emit_and_reloc_code ().
3616 * FIXME: Avoid the got slot.
3617 * FIXME: Add support to the binary writer.
3619 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3620 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3621 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3622 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3627 emit_label (acfg, label);
3629 if (acfg->aot_opts.write_symbols) {
3630 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3634 case MONO_PATCH_INFO_METHOD:
3635 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3637 case MONO_PATCH_INFO_INTERNAL_METHOD:
3638 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3640 case MONO_PATCH_INFO_CLASS_INIT:
3641 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3642 sanitize_symbol (debug_sym);
3644 case MONO_PATCH_INFO_RGCTX_FETCH:
3645 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3647 case MONO_PATCH_INFO_ICALL_ADDR: {
3648 char *s = get_debug_sym (ji->data.method, "", cache);
3650 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3654 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3655 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3657 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3658 debug_sym = g_strdup_printf ("plt__generic_class_init");
3665 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3666 emit_label (acfg, debug_sym);
3672 * The first plt entry is used to transfer code to the AOT loader.
3674 arch_emit_plt_entry (acfg, i);
3677 emit_symbol_size (acfg, debug_sym, ".");
3682 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3684 sprintf (symbol, "plt_end");
3685 emit_global (acfg, symbol, TRUE);
3686 emit_label (acfg, symbol);
3688 g_hash_table_destroy (cache);
3691 static G_GNUC_UNUSED void
3692 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3693 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3695 char start_symbol [256];
3697 guint32 buf_size, info_offset;
3698 MonoJumpInfo *patch_info;
3704 sprintf (start_symbol, "%s", name);
3706 emit_section_change (acfg, ".text", 0);
3707 emit_global (acfg, start_symbol, TRUE);
3708 emit_alignment (acfg, 16);
3709 emit_label (acfg, start_symbol);
3711 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3712 emit_label (acfg, symbol);
3715 * The code should access everything through the GOT, so we pass
3718 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3720 emit_symbol_size (acfg, start_symbol, ".");
3724 /* Sort relocations */
3725 patches = g_ptr_array_new ();
3726 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3727 if (patch_info->type != MONO_PATCH_INFO_NONE)
3728 g_ptr_array_add (patches, patch_info);
3729 g_ptr_array_sort (patches, compare_patches);
3731 buf_size = patches->len * 128 + 128;
3732 buf = g_malloc (buf_size);
3735 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3736 g_assert (p - buf < buf_size);
3738 sprintf (symbol, "%s_p", name);
3740 info_offset = add_to_blob (acfg, buf, p - buf);
3742 emit_section_change (acfg, ".text", 0);
3743 emit_global (acfg, symbol, FALSE);
3744 emit_label (acfg, symbol);
3746 emit_int32 (acfg, info_offset);
3748 /* Emit debug info */
3752 sprintf (symbol, "%s", name);
3753 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3756 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3761 emit_trampolines (MonoAotCompile *acfg)
3764 int i, tramp_got_offset;
3765 MonoAotTrampoline ntype;
3766 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3774 if (!acfg->aot_opts.full_aot)
3777 g_assert (acfg->image->assembly);
3779 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3780 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3781 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3783 * Emit the generic trampolines.
3785 * We could save some code by treating the generic trampolines as a wrapper
3786 * method, but that approach has its own complexities, so we choose the simpler
3789 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3790 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3792 /* Emit trampoline code */
3794 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3796 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3799 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3800 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3801 #if (defined(TARGET_AMD64) || defined(TARGET_X86)) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3802 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3803 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3804 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3805 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3808 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3809 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3811 /* Emit the exception related code pieces */
3812 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3813 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3814 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3815 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3816 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3817 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3818 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3819 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3820 #ifdef MONO_ARCH_HAVE_THROW_EXCEPTION_BY_NAME
3821 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3822 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3824 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3825 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3827 #if defined(TARGET_AMD64)
3828 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3829 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3832 for (i = 0; i < 128; ++i) {
3835 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3836 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3837 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3838 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3840 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3841 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3842 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3843 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3849 /* delegate_invoke_impl trampolines */
3850 l = mono_arch_get_delegate_invoke_impls ();
3852 MonoAotTrampInfo *info = l->data;
3854 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3859 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3861 /* Emit trampolines which are numerous */
3864 * These include the following:
3865 * - specific trampolines
3866 * - static rgctx invoke trampolines
3868 * These trampolines have the same code, they are parameterized by GOT
3870 * They are defined in this file, in the arch_... routines instead of
3871 * in tramp-<ARCH>.c, since it is easier to do it this way.
3875 * When running in aot-only mode, we can't create specific trampolines at
3876 * runtime, so we create a few, and save them in the AOT file.
3877 * Normal trampolines embed their argument as a literal inside the
3878 * trampoline code, we can't do that here, so instead we embed an offset
3879 * which needs to be added to the trampoline address to get the address of
3880 * the GOT slot which contains the argument value.
3881 * The generated trampolines jump to the generic trampolines using another
3882 * GOT slot, which will be setup by the AOT loader to point to the
3883 * generic trampoline code of the given type.
3887 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3891 emit_section_change (acfg, ".text", 0);
3893 tramp_got_offset = acfg->got_offset;
3895 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3897 case MONO_AOT_TRAMP_SPECIFIC:
3898 sprintf (symbol, "specific_trampolines");
3900 case MONO_AOT_TRAMP_STATIC_RGCTX:
3901 sprintf (symbol, "static_rgctx_trampolines");
3903 case MONO_AOT_TRAMP_IMT_THUNK:
3904 sprintf (symbol, "imt_thunks");
3907 g_assert_not_reached ();
3910 emit_global (acfg, symbol, TRUE);
3911 emit_alignment (acfg, 16);
3912 emit_label (acfg, symbol);
3914 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3916 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3920 case MONO_AOT_TRAMP_SPECIFIC:
3921 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3922 tramp_got_offset += 2;
3924 case MONO_AOT_TRAMP_STATIC_RGCTX:
3925 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3926 tramp_got_offset += 2;
3928 case MONO_AOT_TRAMP_IMT_THUNK:
3929 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3930 tramp_got_offset += 1;
3933 g_assert_not_reached ();
3936 if (!acfg->trampoline_size [ntype]) {
3937 g_assert (tramp_size);
3938 acfg->trampoline_size [ntype] = tramp_size;
3943 /* Reserve some entries at the end of the GOT for our use */
3944 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3947 acfg->got_offset += acfg->num_trampoline_got_entries;
3951 str_begins_with (const char *str1, const char *str2)
3953 int len = strlen (str2);
3954 return strncmp (str1, str2, len) == 0;
3958 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3960 gchar **args, **ptr;
3962 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3963 for (ptr = args; ptr && *ptr; ptr ++) {
3964 const char *arg = *ptr;
3966 if (str_begins_with (arg, "outfile=")) {
3967 opts->outfile = g_strdup (arg + strlen ("outfile="));
3968 } else if (str_begins_with (arg, "save-temps")) {
3969 opts->save_temps = TRUE;
3970 } else if (str_begins_with (arg, "keep-temps")) {
3971 opts->save_temps = TRUE;
3972 } else if (str_begins_with (arg, "write-symbols")) {
3973 opts->write_symbols = TRUE;
3974 } else if (str_begins_with (arg, "metadata-only")) {
3975 opts->metadata_only = TRUE;
3976 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3977 opts->bind_to_runtime_version = TRUE;
3978 } else if (str_begins_with (arg, "full")) {
3979 opts->full_aot = TRUE;
3980 } else if (str_begins_with (arg, "threads=")) {
3981 opts->nthreads = atoi (arg + strlen ("threads="));
3982 } else if (str_begins_with (arg, "static")) {
3983 opts->static_link = TRUE;
3984 opts->no_dlsym = TRUE;
3985 } else if (str_begins_with (arg, "asmonly")) {
3986 opts->asm_only = TRUE;
3987 } else if (str_begins_with (arg, "asmwriter")) {
3988 opts->asm_writer = TRUE;
3989 } else if (str_begins_with (arg, "nodebug")) {
3990 opts->nodebug = TRUE;
3991 } else if (str_begins_with (arg, "ntrampolines=")) {
3992 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3993 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
3994 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
3995 } else if (str_begins_with (arg, "nimt-trampolines=")) {
3996 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
3997 } else if (str_begins_with (arg, "autoreg")) {
3998 opts->autoreg = TRUE;
3999 } else if (str_begins_with (arg, "tool-prefix=")) {
4000 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4001 } else if (str_begins_with (arg, "soft-debug")) {
4002 opts->soft_debug = TRUE;
4003 } else if (str_begins_with (arg, "print-skipped")) {
4004 opts->print_skipped_methods = TRUE;
4005 } else if (str_begins_with (arg, "stats")) {
4008 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4017 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4019 MonoMethod *method = (MonoMethod*)key;
4020 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4021 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4022 MonoAotCompile *acfg = user_data;
4024 new_ji->image = ji->image;
4025 new_ji->token = ji->token;
4026 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4030 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4032 if (klass->type_token)
4034 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4037 return can_encode_class (acfg, klass->element_class);
4042 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4044 switch (patch_info->type) {
4045 case MONO_PATCH_INFO_METHOD:
4046 case MONO_PATCH_INFO_METHODCONST: {
4047 MonoMethod *method = patch_info->data.method;
4049 if (method->wrapper_type) {
4050 switch (method->wrapper_type) {
4051 case MONO_WRAPPER_NONE:
4052 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4053 case MONO_WRAPPER_XDOMAIN_INVOKE:
4054 case MONO_WRAPPER_STFLD:
4055 case MONO_WRAPPER_LDFLD:
4056 case MONO_WRAPPER_LDFLDA:
4057 case MONO_WRAPPER_LDFLD_REMOTE:
4058 case MONO_WRAPPER_STFLD_REMOTE:
4059 case MONO_WRAPPER_STELEMREF:
4060 case MONO_WRAPPER_ISINST:
4061 case MONO_WRAPPER_PROXY_ISINST:
4062 case MONO_WRAPPER_ALLOC:
4063 case MONO_WRAPPER_REMOTING_INVOKE:
4064 case MONO_WRAPPER_UNKNOWN:
4065 case MONO_WRAPPER_WRITE_BARRIER:
4067 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4068 if (!strcmp (method->name, "ElementAddr"))
4073 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4077 if (!method->token) {
4078 /* The method is part of a constructed type like Int[,].Set (). */
4079 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4080 if (method->klass->rank)
4088 case MONO_PATCH_INFO_VTABLE:
4089 case MONO_PATCH_INFO_CLASS_INIT:
4090 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4091 case MONO_PATCH_INFO_CLASS:
4092 case MONO_PATCH_INFO_IID:
4093 case MONO_PATCH_INFO_ADJUSTED_IID:
4094 if (!can_encode_class (acfg, patch_info->data.klass)) {
4095 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4099 case MONO_PATCH_INFO_RGCTX_FETCH: {
4100 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4102 if (!can_encode_patch (acfg, entry->data))
4114 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4119 * AOT compile a given method.
4120 * This function might be called by multiple threads, so it must be thread-safe.
4123 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4126 MonoJumpInfo *patch_info;
4129 MonoMethod *wrapped;
4131 if (acfg->aot_opts.metadata_only)
4134 mono_acfg_lock (acfg);
4135 index = get_method_index (acfg, method);
4136 mono_acfg_unlock (acfg);
4138 /* fixme: maybe we can also precompile wrapper methods */
4139 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4140 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4141 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4142 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4146 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4149 wrapped = mono_marshal_method_from_wrapper (method);
4150 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4151 // FIXME: The wrapper should be generic too, but it is not
4154 InterlockedIncrement (&acfg->stats.mcount);
4157 if (method->is_generic || method->klass->generic_container) {
4158 InterlockedIncrement (&acfg->stats.genericcount);
4163 //acfg->aot_opts.print_skipped_methods = TRUE;
4166 * Since these methods are the only ones which are compiled with
4167 * AOT support, and they are not used by runtime startup/shutdown code,
4168 * the runtime will not see AOT methods during AOT compilation,so it
4169 * does not need to support them by creating a fake GOT etc.
4171 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4172 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4173 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4174 InterlockedIncrement (&acfg->stats.genericcount);
4177 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4178 /* Let the exception happen at runtime */
4182 if (cfg->disable_aot) {
4183 if (acfg->aot_opts.print_skipped_methods)
4184 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4185 InterlockedIncrement (&acfg->stats.ocount);
4186 mono_destroy_compile (cfg);
4190 /* Nullify patches which need no aot processing */
4191 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4192 switch (patch_info->type) {
4193 case MONO_PATCH_INFO_LABEL:
4194 case MONO_PATCH_INFO_BB:
4195 patch_info->type = MONO_PATCH_INFO_NONE;
4202 /* Collect method->token associations from the cfg */
4203 mono_acfg_lock (acfg);
4204 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4205 mono_acfg_unlock (acfg);
4208 * Check for absolute addresses.
4211 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4212 switch (patch_info->type) {
4213 case MONO_PATCH_INFO_ABS:
4214 /* unable to handle this */
4223 if (acfg->aot_opts.print_skipped_methods)
4224 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4225 InterlockedIncrement (&acfg->stats.abscount);
4226 mono_destroy_compile (cfg);
4230 /* Lock for the rest of the code */
4231 mono_acfg_lock (acfg);
4234 * Check for methods/klasses we can't encode.
4237 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4238 if (!can_encode_patch (acfg, patch_info))
4243 if (acfg->aot_opts.print_skipped_methods)
4244 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4245 acfg->stats.ocount++;
4246 mono_destroy_compile (cfg);
4247 mono_acfg_unlock (acfg);
4251 /* Adds generic instances referenced by this method */
4253 * The depth is used to avoid infinite loops when generic virtual recursion is
4256 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4258 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4259 switch (patch_info->type) {
4260 case MONO_PATCH_INFO_METHOD: {
4261 MonoMethod *m = patch_info->data.method;
4262 if (m->is_inflated) {
4263 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4264 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4265 !method_has_type_vars (m)) {
4266 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4267 if (acfg->aot_opts.full_aot)
4268 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4270 add_extra_method_with_depth (acfg, m, depth + 1);
4273 add_generic_class (acfg, m->klass);
4275 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4276 add_extra_method_with_depth (acfg, m, depth + 1);
4279 case MONO_PATCH_INFO_VTABLE: {
4280 MonoClass *klass = patch_info->data.klass;
4282 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4283 add_generic_class (acfg, klass);
4292 /* Determine whenever the method has GOT slots */
4293 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4294 switch (patch_info->type) {
4295 case MONO_PATCH_INFO_GOT_OFFSET:
4296 case MONO_PATCH_INFO_NONE:
4298 case MONO_PATCH_INFO_IMAGE:
4299 /* The assembly is stored in GOT slot 0 */
4300 if (patch_info->data.image != acfg->image)
4301 cfg->has_got_slots = TRUE;
4304 if (!is_plt_patch (patch_info))
4305 cfg->has_got_slots = TRUE;
4310 if (!cfg->has_got_slots)
4311 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4314 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4316 /* Make a copy of the patch info which is in the mempool */
4318 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4320 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4321 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4324 patches = new_patch_info;
4326 patches_end->next = new_patch_info;
4327 patches_end = new_patch_info;
4329 cfg->patch_info = patches;
4331 /* Make a copy of the unwind info */
4333 GSList *l, *unwind_ops;
4337 for (l = cfg->unwind_ops; l; l = l->next) {
4338 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4339 memcpy (op, l->data, sizeof (MonoUnwindOp));
4340 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4342 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4344 /* Make a copy of the argument/local info */
4346 MonoInst **args, **locals;
4347 MonoMethodSignature *sig;
4348 MonoMethodHeader *header;
4351 sig = mono_method_signature (method);
4352 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4353 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4354 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4355 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4359 header = mono_method_get_header (method);
4360 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4361 for (i = 0; i < header->num_locals; ++i) {
4362 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4363 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4365 cfg->locals = locals;
4368 /* Free some fields used by cfg to conserve memory */
4369 mono_mempool_destroy (cfg->mempool);
4370 cfg->mempool = NULL;
4371 g_free (cfg->varinfo);
4372 cfg->varinfo = NULL;
4376 mono_regstate_free (cfg->rs);
4380 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4382 while (index >= acfg->cfgs_size) {
4383 MonoCompile **new_cfgs;
4386 new_size = acfg->cfgs_size * 2;
4387 new_cfgs = g_new0 (MonoCompile*, new_size);
4388 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4389 g_free (acfg->cfgs);
4390 acfg->cfgs = new_cfgs;
4391 acfg->cfgs_size = new_size;
4393 acfg->cfgs [index] = cfg;
4395 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4398 if (cfg->orig_method->wrapper_type)
4399 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4402 mono_acfg_unlock (acfg);
4404 InterlockedIncrement (&acfg->stats.ccount);
4408 compile_thread_main (gpointer *user_data)
4410 MonoDomain *domain = user_data [0];
4411 MonoAotCompile *acfg = user_data [1];
4412 GPtrArray *methods = user_data [2];
4415 mono_thread_attach (domain);
4417 for (i = 0; i < methods->len; ++i)
4418 compile_method (acfg, g_ptr_array_index (methods, i));
4422 load_profile_files (MonoAotCompile *acfg)
4426 int file_index, res, method_index, i;
4433 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4435 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4440 infile = fopen (tmp, "r");
4443 printf ("Using profile data file '%s'\n", tmp);
4448 res = fscanf (infile, "%32s\n", ver);
4449 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4450 printf ("Profile file has wrong version or invalid.\n");
4457 MonoMethodDesc *desc;
4460 if (fgets (name, 1023, infile) == NULL)
4463 /* Kill the newline */
4464 if (strlen (name) > 0)
4465 name [strlen (name) - 1] = '\0';
4467 desc = mono_method_desc_new (name, TRUE);
4469 method = mono_method_desc_search_in_image (desc, acfg->image);
4471 if (method && mono_method_get_token (method)) {
4472 token = mono_method_get_token (method);
4473 method_index = mono_metadata_token_index (token) - 1;
4475 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4476 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4479 //printf ("No method found matching '%s'.\n", name);
4485 /* Add missing methods */
4487 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4488 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4489 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4491 unordered = g_list_reverse (unordered);
4492 if (acfg->method_order)
4493 g_list_last (acfg->method_order)->next = unordered;
4495 acfg->method_order = unordered;
4498 /* Used by the LLVM backend */
4500 mono_aot_get_got_offset (MonoJumpInfo *ji)
4502 return get_got_offset (llvm_acfg, ji);
4506 mono_aot_get_method_name (MonoCompile *cfg)
4508 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4510 return g_strdup_printf ("m_%x", method_index);
4514 mono_aot_get_method_debug_name (MonoCompile *cfg)
4516 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4520 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4522 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4526 ji->data.target = data;
4528 if (!can_encode_patch (llvm_acfg, ji))
4531 offset = get_plt_offset (llvm_acfg, ji);
4533 return g_strdup_printf ("%sp_%d", llvm_acfg->temp_prefix, offset);
4537 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4541 mono_acfg_lock (llvm_acfg);
4542 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4543 mono_acfg_unlock (llvm_acfg);
4553 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4557 emit_llvm_file (MonoAotCompile *acfg)
4559 char *command, *opts;
4561 MonoJumpInfo *patch_info;
4562 char *llc_target_args;
4565 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4569 /* Compute the final size of the got */
4570 for (i = 0; i < acfg->nmethods; ++i) {
4571 if (acfg->cfgs [i]) {
4572 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4573 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4574 if (!is_plt_patch (patch_info))
4575 get_got_offset (acfg, patch_info);
4577 get_plt_offset (acfg, patch_info);
4583 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4585 if (acfg->aot_opts.full_aot) {
4589 * Need to add the got entries used by the trampolines.
4590 * This is only a conservative approximation.
4592 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4593 /* For the generic + rgctx trampolines */
4594 acfg->final_got_size += 200;
4595 /* For the specific trampolines */
4596 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4597 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4602 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4605 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4606 * a lot of time, and doesn't seem to save much space.
4607 * The following optimizations cannot be enabled:
4609 * The opt list below was produced by taking the output of:
4610 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4611 * then removing tailcallelim + the global opts, and adding a second gvn.
4613 opts = g_strdup ("-instcombine -simplifycfg");
4614 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");
4616 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4617 printf ("Executing opt: %s\n", command);
4618 if (system (command) != 0) {
4624 llc_target_args = g_strdup (LLC_TARGET_ARGS);
4626 command = g_strdup_printf ("llc %s -f -relocation-model=pic -unwind-tables -o %s temp.opt.bc", llc_target_args, acfg->tmpfname);
4627 g_free (llc_target_args);
4629 printf ("Executing llc: %s\n", command);
4631 if (system (command) != 0) {
4638 emit_code (MonoAotCompile *acfg)
4642 char end_symbol [256];
4645 #if defined(TARGET_POWERPC64)
4646 sprintf (symbol, ".Lgot_addr");
4647 emit_section_change (acfg, ".text", 0);
4648 emit_alignment (acfg, 8);
4649 emit_label (acfg, symbol);
4650 emit_pointer (acfg, acfg->got_symbol);
4654 * This global symbol is used to compute the address of each method using the
4655 * code_offsets array. It is also used to compute the memory ranges occupied by
4656 * AOT code, so it must be equal to the address of the first emitted method.
4658 sprintf (symbol, "methods");
4659 emit_section_change (acfg, ".text", 0);
4660 emit_global (acfg, symbol, TRUE);
4661 emit_alignment (acfg, 8);
4663 for (i = 0; i < acfg->nmethods; ++i) {
4664 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4665 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4669 if (i == acfg->nmethods)
4670 /* No LLVM compiled methods */
4671 emit_label (acfg, symbol);
4673 emit_label (acfg, symbol);
4677 * Emit some padding so the local symbol for the first method doesn't have the
4678 * same address as 'methods'.
4680 emit_zero_bytes (acfg, 16);
4682 for (l = acfg->method_order; l != NULL; l = l->next) {
4686 i = GPOINTER_TO_UINT (l->data);
4688 cfg = acfg->cfgs [i];
4693 method = cfg->orig_method;
4695 /* Emit unbox trampoline */
4696 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4697 char call_target [256];
4699 if (!method->wrapper_type && !method->is_inflated) {
4700 g_assert (method->token);
4701 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4703 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4706 emit_section_change (acfg, ".text", 0);
4707 emit_global (acfg, symbol, TRUE);
4708 emit_label (acfg, symbol);
4710 sprintf (call_target, "%s", cfg->asm_symbol);
4712 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
4715 if (cfg->compile_llvm)
4716 acfg->stats.llvm_count ++;
4718 emit_method_code (acfg, cfg);
4721 sprintf (symbol, "methods_end");
4722 emit_section_change (acfg, ".text", 0);
4723 emit_global (acfg, symbol, FALSE);
4724 emit_alignment (acfg, 8);
4725 emit_label (acfg, symbol);
4727 sprintf (symbol, "code_offsets");
4728 emit_section_change (acfg, ".text", 1);
4729 emit_global (acfg, symbol, FALSE);
4730 emit_alignment (acfg, 8);
4731 emit_label (acfg, symbol);
4733 acfg->stats.offsets_size += acfg->nmethods * 4;
4735 sprintf (end_symbol, "methods");
4736 for (i = 0; i < acfg->nmethods; ++i) {
4737 if (acfg->cfgs [i]) {
4738 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4740 emit_int32 (acfg, 0xffffffff);
4747 emit_info (MonoAotCompile *acfg)
4754 offsets = g_new0 (gint32, acfg->nmethods);
4756 for (l = acfg->method_order; l != NULL; l = l->next) {
4757 i = GPOINTER_TO_UINT (l->data);
4759 if (acfg->cfgs [i]) {
4760 emit_method_info (acfg, acfg->cfgs [i]);
4761 offsets [i] = acfg->cfgs [i]->method_info_offset;
4767 sprintf (symbol, "method_info_offsets");
4768 emit_section_change (acfg, ".text", 1);
4769 emit_global (acfg, symbol, FALSE);
4770 emit_alignment (acfg, 8);
4771 emit_label (acfg, symbol);
4773 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4778 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4780 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4781 #define mix(a,b,c) { \
4782 a -= c; a ^= rot(c, 4); c += b; \
4783 b -= a; b ^= rot(a, 6); a += c; \
4784 c -= b; c ^= rot(b, 8); b += a; \
4785 a -= c; a ^= rot(c,16); c += b; \
4786 b -= a; b ^= rot(a,19); a += c; \
4787 c -= b; c ^= rot(b, 4); b += a; \
4789 #define final(a,b,c) { \
4790 c ^= b; c -= rot(b,14); \
4791 a ^= c; a -= rot(c,11); \
4792 b ^= a; b -= rot(a,25); \
4793 c ^= b; c -= rot(b,16); \
4794 a ^= c; a -= rot(c,4); \
4795 b ^= a; b -= rot(a,14); \
4796 c ^= b; c -= rot(b,24); \
4800 mono_aot_type_hash (MonoType *t1)
4802 guint hash = t1->type;
4804 hash |= t1->byref << 6; /* do not collide with t1->type values */
4806 case MONO_TYPE_VALUETYPE:
4807 case MONO_TYPE_CLASS:
4808 case MONO_TYPE_SZARRAY:
4809 /* check if the distribution is good enough */
4810 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
4812 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
4813 case MONO_TYPE_ARRAY:
4814 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
4815 case MONO_TYPE_GENERICINST:
4816 return ((hash << 5) - hash) ^ 0;
4822 * mono_aot_method_hash:
4824 * Return a hash code for methods which only depends on metadata.
4827 mono_aot_method_hash (MonoMethod *method)
4829 MonoMethodSignature *sig;
4833 guint32 *hashes_start, *hashes;
4836 /* Similar to the hash in mono_method_get_imt_slot () */
4838 sig = mono_method_signature (method);
4840 hashes_count = sig->param_count + 5;
4841 hashes_start = malloc (hashes_count * sizeof (guint32));
4842 hashes = hashes_start;
4844 /* Some wrappers are assigned to random classes */
4845 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4846 klass = method->klass;
4848 klass = mono_defaults.object_class;
4850 if (!method->wrapper_type) {
4851 char *full_name = mono_type_full_name (&klass->byval_arg);
4853 hashes [0] = mono_metadata_str_hash (full_name);
4857 hashes [0] = mono_metadata_str_hash (klass->name);
4858 hashes [1] = mono_metadata_str_hash (klass->name_space);
4860 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4861 /* The method name includes a stringified pointer */
4864 hashes [2] = mono_metadata_str_hash (method->name);
4865 hashes [3] = method->wrapper_type;
4866 hashes [4] = mono_aot_type_hash (sig->ret);
4867 for (i = 0; i < sig->param_count; i++) {
4868 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4871 /* Setup internal state */
4872 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4874 /* Handle most of the hashes */
4875 while (hashes_count > 3) {
4884 /* Handle the last 3 hashes (all the case statements fall through) */
4885 switch (hashes_count) {
4886 case 3 : c += hashes [2];
4887 case 2 : b += hashes [1];
4888 case 1 : a += hashes [0];
4890 case 0: /* nothing left to add */
4894 free (hashes_start);
4903 * mono_aot_wrapper_name:
4905 * Return a string which uniqely identifies the given wrapper method.
4908 mono_aot_wrapper_name (MonoMethod *method)
4910 char *name, *tmpsig, *klass_desc;
4912 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4914 switch (method->wrapper_type) {
4915 case MONO_WRAPPER_RUNTIME_INVOKE:
4916 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4917 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4919 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4922 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4923 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4924 g_free (klass_desc);
4934 * mono_aot_get_array_helper_from_wrapper;
4936 * Get the helper method in Array called by an array wrapper method.
4939 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4943 MonoGenericContext ctx;
4944 MonoType *args [16];
4945 char *mname, *iname, *s, *s2, *helper_name = NULL;
4947 prefix = "System.Collections.Generic";
4948 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4949 s2 = strstr (s, "`1.");
4955 //printf ("X: %s %s\n", iname, mname);
4957 if (!strcmp (iname, "IList"))
4958 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4960 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4961 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4963 g_free (helper_name);
4966 if (m->is_generic) {
4967 memset (&ctx, 0, sizeof (ctx));
4968 args [0] = &method->klass->element_class->byval_arg;
4969 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4970 m = mono_class_inflate_generic_method (m, &ctx);
4977 * mono_aot_tramp_info_create:
4979 * Create a MonoAotTrampInfo structure from the arguments.
4982 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4984 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4986 info->name = (char*)name;
4988 info->code_size = code_size;
4993 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4995 typedef struct HashEntry {
4996 guint32 key, value, index;
4997 struct HashEntry *next;
5001 * emit_extra_methods:
5003 * Emit methods which are not in the METHOD table, like wrappers.
5006 emit_extra_methods (MonoAotCompile *acfg)
5008 int i, table_size, buf_size;
5011 guint32 *info_offsets;
5014 HashEntry *entry, *new_entry;
5015 int nmethods, max_chain_length;
5018 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5020 /* Emit method info */
5022 for (i = 0; i < acfg->extra_methods->len; ++i) {
5023 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5024 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5031 p = buf = g_malloc (buf_size);
5035 method = cfg->method_to_register;
5038 if (method->wrapper_type) {
5040 * We encode some wrappers using their name, since encoding them
5041 * directly would be difficult. This also avoids creating the wrapper
5042 * methods at runtime, since they are not needed anyway.
5044 switch (method->wrapper_type) {
5045 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5046 case MONO_WRAPPER_SYNCHRONIZED:
5047 /* encode_method_ref () can handle these */
5049 case MONO_WRAPPER_RUNTIME_INVOKE:
5050 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5051 /* Direct wrapper, encode normally */
5055 name = mono_aot_wrapper_name (method);
5061 encode_value (1, p, &p);
5062 encode_value (method->wrapper_type, p, &p);
5063 strcpy ((char*)p, name);
5064 p += strlen (name ) + 1;
5067 encode_value (0, p, &p);
5068 encode_method_ref (acfg, method, p, &p);
5071 g_assert ((p - buf) < buf_size);
5073 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5078 * Construct a chained hash table for mapping indexes in extra_method_info to
5081 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5082 table = g_ptr_array_sized_new (table_size);
5083 for (i = 0; i < table_size; ++i)
5084 g_ptr_array_add (table, NULL);
5085 chain_lengths = g_new0 (int, table_size);
5086 max_chain_length = 0;
5087 for (i = 0; i < acfg->extra_methods->len; ++i) {
5088 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5089 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5095 key = info_offsets [i];
5096 value = get_method_index (acfg, method);
5098 hash = mono_aot_method_hash (method) % table_size;
5100 chain_lengths [hash] ++;
5101 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5103 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5104 new_entry->key = key;
5105 new_entry->value = value;
5107 entry = g_ptr_array_index (table, hash);
5108 if (entry == NULL) {
5109 new_entry->index = hash;
5110 g_ptr_array_index (table, hash) = new_entry;
5113 entry = entry->next;
5115 entry->next = new_entry;
5116 new_entry->index = table->len;
5117 g_ptr_array_add (table, new_entry);
5121 //printf ("MAX: %d\n", max_chain_length);
5123 /* Emit the table */
5124 sprintf (symbol, "extra_method_table");
5125 emit_section_change (acfg, ".text", 0);
5126 emit_global (acfg, symbol, FALSE);
5127 emit_alignment (acfg, 8);
5128 emit_label (acfg, symbol);
5130 emit_int32 (acfg, table_size);
5131 for (i = 0; i < table->len; ++i) {
5132 HashEntry *entry = g_ptr_array_index (table, i);
5134 if (entry == NULL) {
5135 emit_int32 (acfg, 0);
5136 emit_int32 (acfg, 0);
5137 emit_int32 (acfg, 0);
5139 //g_assert (entry->key > 0);
5140 emit_int32 (acfg, entry->key);
5141 emit_int32 (acfg, entry->value);
5143 emit_int32 (acfg, entry->next->index);
5145 emit_int32 (acfg, 0);
5150 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5151 * This is used by mono_aot_find_jit_info ().
5153 sprintf (symbol, "extra_method_info_offsets");
5154 emit_section_change (acfg, ".text", 0);
5155 emit_global (acfg, symbol, FALSE);
5156 emit_alignment (acfg, 8);
5157 emit_label (acfg, symbol);
5159 emit_int32 (acfg, acfg->extra_methods->len);
5160 for (i = 0; i < acfg->extra_methods->len; ++i) {
5161 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5163 emit_int32 (acfg, get_method_index (acfg, method));
5164 emit_int32 (acfg, info_offsets [i]);
5169 emit_exception_info (MonoAotCompile *acfg)
5175 offsets = g_new0 (gint32, acfg->nmethods);
5176 for (i = 0; i < acfg->nmethods; ++i) {
5177 if (acfg->cfgs [i]) {
5178 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5179 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5185 sprintf (symbol, "ex_info_offsets");
5186 emit_section_change (acfg, ".text", 1);
5187 emit_global (acfg, symbol, FALSE);
5188 emit_alignment (acfg, 8);
5189 emit_label (acfg, symbol);
5191 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5196 emit_unwind_info (MonoAotCompile *acfg)
5202 * The unwind info contains a lot of duplicates so we emit each unique
5203 * entry once, and only store the offset from the start of the table in the
5207 sprintf (symbol, "unwind_info");
5208 emit_section_change (acfg, ".text", 1);
5209 emit_alignment (acfg, 8);
5210 emit_label (acfg, symbol);
5211 emit_global (acfg, symbol, FALSE);
5213 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5214 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5215 guint8 *unwind_info;
5216 guint32 unwind_info_len;
5220 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5223 encode_value (unwind_info_len, p, &p);
5224 emit_bytes (acfg, buf, p - buf);
5225 emit_bytes (acfg, unwind_info, unwind_info_len);
5227 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5232 emit_class_info (MonoAotCompile *acfg)
5238 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5239 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5240 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5242 sprintf (symbol, "class_info_offsets");
5243 emit_section_change (acfg, ".text", 1);
5244 emit_global (acfg, symbol, FALSE);
5245 emit_alignment (acfg, 8);
5246 emit_label (acfg, symbol);
5248 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5252 typedef struct ClassNameTableEntry {
5253 guint32 token, index;
5254 struct ClassNameTableEntry *next;
5255 } ClassNameTableEntry;
5258 emit_class_name_table (MonoAotCompile *acfg)
5261 guint32 token, hash;
5266 ClassNameTableEntry *entry, *new_entry;
5269 * Construct a chained hash table for mapping class names to typedef tokens.
5271 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5272 table = g_ptr_array_sized_new (table_size);
5273 for (i = 0; i < table_size; ++i)
5274 g_ptr_array_add (table, NULL);
5275 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5276 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5277 klass = mono_class_get (acfg->image, token);
5278 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5279 hash = mono_metadata_str_hash (full_name) % table_size;
5282 /* FIXME: Allocate from the mempool */
5283 new_entry = g_new0 (ClassNameTableEntry, 1);
5284 new_entry->token = token;
5286 entry = g_ptr_array_index (table, hash);
5287 if (entry == NULL) {
5288 new_entry->index = hash;
5289 g_ptr_array_index (table, hash) = new_entry;
5292 entry = entry->next;
5294 entry->next = new_entry;
5295 new_entry->index = table->len;
5296 g_ptr_array_add (table, new_entry);
5300 /* Emit the table */
5301 sprintf (symbol, "class_name_table");
5302 emit_section_change (acfg, ".text", 0);
5303 emit_global (acfg, symbol, FALSE);
5304 emit_alignment (acfg, 8);
5305 emit_label (acfg, symbol);
5307 /* FIXME: Optimize memory usage */
5308 g_assert (table_size < 65000);
5309 emit_int16 (acfg, table_size);
5310 g_assert (table->len < 65000);
5311 for (i = 0; i < table->len; ++i) {
5312 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5314 if (entry == NULL) {
5315 emit_int16 (acfg, 0);
5316 emit_int16 (acfg, 0);
5318 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5320 emit_int16 (acfg, entry->next->index);
5322 emit_int16 (acfg, 0);
5328 emit_image_table (MonoAotCompile *acfg)
5334 * The image table is small but referenced in a lot of places.
5335 * So we emit it at once, and reference its elements by an index.
5338 sprintf (symbol, "mono_image_table");
5339 emit_section_change (acfg, ".text", 1);
5340 emit_global (acfg, symbol, FALSE);
5341 emit_alignment (acfg, 8);
5342 emit_label (acfg, symbol);
5344 emit_int32 (acfg, acfg->image_table->len);
5345 for (i = 0; i < acfg->image_table->len; i++) {
5346 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5347 MonoAssemblyName *aname = &image->assembly->aname;
5349 /* FIXME: Support multi-module assemblies */
5350 g_assert (image->assembly->image == image);
5352 emit_string (acfg, image->assembly_name);
5353 emit_string (acfg, image->guid);
5354 emit_string (acfg, aname->culture ? aname->culture : "");
5355 emit_string (acfg, (const char*)aname->public_key_token);
5357 emit_alignment (acfg, 8);
5358 emit_int32 (acfg, aname->flags);
5359 emit_int32 (acfg, aname->major);
5360 emit_int32 (acfg, aname->minor);
5361 emit_int32 (acfg, aname->build);
5362 emit_int32 (acfg, aname->revision);
5367 emit_got_info (MonoAotCompile *acfg)
5370 int i, first_plt_got_patch, buf_size;
5372 guint32 *got_info_offsets;
5374 /* Add the patches needed by the PLT to the GOT */
5375 acfg->plt_got_offset_base = acfg->got_offset;
5376 first_plt_got_patch = acfg->got_patches->len;
5377 for (i = 1; i < acfg->plt_offset; ++i) {
5378 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
5380 g_ptr_array_add (acfg->got_patches, patch_info);
5383 acfg->got_offset += acfg->plt_offset;
5387 * - optimize offsets table.
5388 * - reduce number of exported symbols.
5389 * - emit info for a klass only once.
5390 * - determine when a method uses a GOT slot which is guaranteed to be already
5392 * - clean up and document the code.
5393 * - use String.Empty in class libs.
5396 /* Encode info required to decode shared GOT entries */
5397 buf_size = acfg->got_patches->len * 64;
5398 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5399 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5400 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5402 if (acfg->plt_offset)
5403 acfg->plt_got_info_offsets [0] = 0;
5404 for (i = 0; i < acfg->got_patches->len; ++i) {
5405 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5409 encode_value (ji->type, p, &p);
5410 encode_patch (acfg, ji, p, &p);
5412 g_assert (p - buf <= buf_size);
5413 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5415 if (i >= first_plt_got_patch)
5416 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5417 acfg->stats.got_info_size += p - buf;
5420 /* Emit got_info_offsets table */
5421 sprintf (symbol, "got_info_offsets");
5422 emit_section_change (acfg, ".text", 1);
5423 emit_global (acfg, symbol, FALSE);
5424 emit_alignment (acfg, 8);
5425 emit_label (acfg, symbol);
5427 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5428 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5432 emit_got (MonoAotCompile *acfg)
5437 /* Don't make GOT global so accesses to it don't need relocations */
5438 sprintf (symbol, "%s", acfg->got_symbol);
5439 emit_section_change (acfg, ".bss", 0);
5440 emit_alignment (acfg, 8);
5441 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5442 emit_label (acfg, symbol);
5443 if (acfg->got_offset > 0)
5444 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5446 sprintf (symbol, "got_end");
5447 emit_label (acfg, symbol);
5450 sprintf (symbol, "mono_aot_got_addr");
5451 emit_section_change (acfg, ".data", 0);
5452 emit_global (acfg, symbol, FALSE);
5453 emit_alignment (acfg, 8);
5454 emit_label (acfg, symbol);
5455 emit_pointer (acfg, acfg->got_symbol);
5458 typedef struct GlobalsTableEntry {
5459 guint32 value, index;
5460 struct GlobalsTableEntry *next;
5461 } GlobalsTableEntry;
5464 emit_globals_table (MonoAotCompile *acfg)
5470 GlobalsTableEntry *entry, *new_entry;
5473 * Construct a chained hash table for mapping global names to their index in
5474 * the globals table.
5476 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5477 table = g_ptr_array_sized_new (table_size);
5478 for (i = 0; i < table_size; ++i)
5479 g_ptr_array_add (table, NULL);
5480 for (i = 0; i < acfg->globals->len; ++i) {
5481 char *name = g_ptr_array_index (acfg->globals, i);
5483 hash = mono_metadata_str_hash (name) % table_size;
5485 /* FIXME: Allocate from the mempool */
5486 new_entry = g_new0 (GlobalsTableEntry, 1);
5487 new_entry->value = i;
5489 entry = g_ptr_array_index (table, hash);
5490 if (entry == NULL) {
5491 new_entry->index = hash;
5492 g_ptr_array_index (table, hash) = new_entry;
5495 entry = entry->next;
5497 entry->next = new_entry;
5498 new_entry->index = table->len;
5499 g_ptr_array_add (table, new_entry);
5503 /* Emit the table */
5504 sprintf (symbol, ".Lglobals_hash");
5505 emit_section_change (acfg, ".text", 0);
5506 emit_alignment (acfg, 8);
5507 emit_label (acfg, symbol);
5509 /* FIXME: Optimize memory usage */
5510 g_assert (table_size < 65000);
5511 emit_int16 (acfg, table_size);
5512 for (i = 0; i < table->len; ++i) {
5513 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5515 if (entry == NULL) {
5516 emit_int16 (acfg, 0);
5517 emit_int16 (acfg, 0);
5519 emit_int16 (acfg, entry->value + 1);
5521 emit_int16 (acfg, entry->next->index);
5523 emit_int16 (acfg, 0);
5527 /* Emit the names */
5528 for (i = 0; i < acfg->globals->len; ++i) {
5529 char *name = g_ptr_array_index (acfg->globals, i);
5531 sprintf (symbol, "name_%d", i);
5532 emit_section_change (acfg, ".text", 1);
5533 emit_label (acfg, symbol);
5534 emit_string (acfg, name);
5537 /* Emit the globals table */
5538 sprintf (symbol, ".Lglobals");
5539 emit_section_change (acfg, ".data", 0);
5540 /* This is not a global, since it is accessed by the init function */
5541 emit_alignment (acfg, 8);
5542 emit_label (acfg, symbol);
5544 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5545 emit_pointer (acfg, symbol);
5547 for (i = 0; i < acfg->globals->len; ++i) {
5548 char *name = g_ptr_array_index (acfg->globals, i);
5550 sprintf (symbol, "name_%d", i);
5551 emit_pointer (acfg, symbol);
5553 sprintf (symbol, "%s", name);
5554 emit_pointer (acfg, symbol);
5556 /* Null terminate the table */
5557 emit_int32 (acfg, 0);
5558 emit_int32 (acfg, 0);
5562 emit_globals (MonoAotCompile *acfg)
5566 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5568 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5570 if (acfg->aot_opts.bind_to_runtime_version) {
5571 build_info = mono_get_runtime_build_info ();
5572 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5573 g_free (build_info);
5575 emit_string_symbol (acfg, "mono_runtime_version", "");
5579 * When static linking, we emit a global which will point to the symbol table.
5581 if (acfg->aot_opts.static_link) {
5585 /* Emit a string holding the assembly name */
5586 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5588 emit_globals_table (acfg);
5591 * Emit a global symbol which can be passed by an embedding app to
5592 * mono_aot_register_module ().
5594 #if defined(__MACH__)
5595 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5597 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5600 /* Get rid of characters which cannot occur in symbols */
5602 for (p = symbol; *p; ++p) {
5603 if (!(isalnum (*p) || *p == '_'))
5606 acfg->static_linking_symbol = g_strdup (symbol);
5607 emit_global_inner (acfg, symbol, FALSE);
5608 emit_alignment (acfg, 8);
5609 emit_label (acfg, symbol);
5610 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5611 emit_pointer (acfg, symbol);
5616 emit_autoreg (MonoAotCompile *acfg)
5621 * Emit a function into the .ctor section which will be called by the ELF
5622 * loader to register this module with the runtime.
5624 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5627 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5629 arch_emit_autoreg (acfg, symbol);
5635 emit_mem_end (MonoAotCompile *acfg)
5639 sprintf (symbol, "mem_end");
5640 emit_section_change (acfg, ".text", 1);
5641 emit_global (acfg, symbol, FALSE);
5642 emit_alignment (acfg, 8);
5643 emit_label (acfg, symbol);
5647 * Emit a structure containing all the information not stored elsewhere.
5650 emit_file_info (MonoAotCompile *acfg)
5655 sprintf (symbol, "mono_aot_file_info");
5656 emit_section_change (acfg, ".data", 0);
5657 emit_alignment (acfg, 8);
5658 emit_label (acfg, symbol);
5659 emit_global (acfg, symbol, FALSE);
5661 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5662 emit_int32 (acfg, acfg->plt_got_offset_base);
5663 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5664 emit_int32 (acfg, acfg->plt_offset);
5665 emit_int32 (acfg, acfg->nmethods);
5666 emit_int32 (acfg, acfg->flags);
5667 emit_int32 (acfg, acfg->opts);
5669 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5670 emit_int32 (acfg, acfg->num_trampolines [i]);
5671 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5672 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5673 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5674 emit_int32 (acfg, acfg->trampoline_size [i]);
5678 emit_blob (MonoAotCompile *acfg)
5682 sprintf (symbol, "blob");
5683 emit_section_change (acfg, ".text", 1);
5684 emit_global (acfg, symbol, FALSE);
5685 emit_alignment (acfg, 8);
5686 emit_label (acfg, symbol);
5688 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5692 emit_dwarf_info (MonoAotCompile *acfg)
5694 #ifdef EMIT_DWARF_INFO
5696 char symbol [128], symbol2 [128];
5698 /* DIEs for methods */
5699 for (i = 0; i < acfg->nmethods; ++i) {
5700 MonoCompile *cfg = acfg->cfgs [i];
5705 // FIXME: LLVM doesn't define .Lme_...
5706 if (cfg->compile_llvm)
5709 sprintf (symbol, "%s", cfg->asm_symbol);
5710 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5712 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 ()));
5718 collect_methods (MonoAotCompile *acfg)
5721 MonoImage *image = acfg->image;
5723 /* Collect methods */
5724 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5726 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5728 method = mono_get_method (acfg->image, token, NULL);
5731 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5735 /* Load all methods eagerly to skip the slower lazy loading code */
5736 mono_class_setup_methods (method->klass);
5738 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5739 /* Compile the wrapper instead */
5740 /* We do this here instead of add_wrappers () because it is easy to do it here */
5741 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5745 /* FIXME: Some mscorlib methods don't have debug info */
5747 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5748 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5749 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5750 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5751 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5752 if (!mono_debug_lookup_method (method)) {
5753 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5760 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5761 add_method_with_index (acfg, method, i, FALSE);
5762 acfg->method_index ++;
5765 add_generic_instances (acfg);
5767 if (acfg->aot_opts.full_aot)
5768 add_wrappers (acfg);
5772 compile_methods (MonoAotCompile *acfg)
5776 if (acfg->aot_opts.nthreads > 0) {
5781 gpointer *user_data;
5782 MonoMethod **methods;
5784 methods_len = acfg->methods->len;
5786 len = acfg->methods->len / acfg->aot_opts.nthreads;
5789 * Partition the list of methods into fragments, and hand it to threads to
5792 threads = g_ptr_array_new ();
5793 /* Make a copy since acfg->methods is modified by compile_method () */
5794 methods = g_new0 (MonoMethod*, methods_len);
5795 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5796 for (i = 0; i < methods_len; ++i)
5797 methods [i] = g_ptr_array_index (acfg->methods, i);
5799 while (i < methods_len) {
5800 frag = g_ptr_array_new ();
5801 for (j = 0; j < len; ++j) {
5802 if (i < methods_len) {
5803 g_ptr_array_add (frag, methods [i]);
5808 user_data = g_new0 (gpointer, 3);
5809 user_data [0] = mono_domain_get ();
5810 user_data [1] = acfg;
5811 user_data [2] = frag;
5813 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5814 g_ptr_array_add (threads, handle);
5818 for (i = 0; i < threads->len; ++i) {
5819 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5825 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5826 for (i = methods_len; i < acfg->methods->len; ++i) {
5827 /* This can new methods to acfg->methods */
5828 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5833 compile_asm (MonoAotCompile *acfg)
5835 char *command, *objfile;
5836 char *outfile_name, *tmp_outfile_name;
5837 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5839 #if defined(TARGET_AMD64)
5840 #define AS_OPTIONS "--64"
5841 #elif defined(TARGET_POWERPC64)
5842 #define AS_OPTIONS "-a64 -mppc64"
5843 #define LD_OPTIONS "-m elf64ppc"
5844 #elif defined(sparc) && SIZEOF_VOID_P == 8
5845 #define AS_OPTIONS "-xarch=v9"
5847 #define AS_OPTIONS ""
5851 #define LD_OPTIONS ""
5855 #define EH_LD_OPTIONS "--eh-frame-hdr"
5857 #define EH_LD_OPTIONS ""
5860 if (acfg->aot_opts.asm_only) {
5861 printf ("Output file: '%s'.\n", acfg->tmpfname);
5862 if (acfg->aot_opts.static_link)
5863 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5867 if (acfg->aot_opts.static_link) {
5868 if (acfg->aot_opts.outfile)
5869 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5871 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5873 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5875 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5876 printf ("Executing the native assembler: %s\n", command);
5877 if (system (command) != 0) {
5885 if (acfg->aot_opts.static_link) {
5886 printf ("Output file: '%s'.\n", objfile);
5887 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5892 if (acfg->aot_opts.outfile)
5893 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5895 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5897 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5900 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5901 #elif defined(__ppc__) && defined(__MACH__)
5902 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5903 #elif defined(HOST_WIN32)
5904 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5906 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5908 printf ("Executing the native linker: %s\n", command);
5909 if (system (command) != 0) {
5910 g_free (tmp_outfile_name);
5911 g_free (outfile_name);
5919 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5920 printf ("Stripping the binary: %s\n", com);
5924 #if defined(TARGET_ARM) && !defined(__MACH__)
5926 * gas generates 'mapping symbols' each time code and data is mixed, which
5927 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5929 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5930 printf ("Stripping the binary: %s\n", command);
5931 if (system (command) != 0) {
5932 g_free (tmp_outfile_name);
5933 g_free (outfile_name);
5940 rename (tmp_outfile_name, outfile_name);
5942 g_free (tmp_outfile_name);
5943 g_free (outfile_name);
5946 if (acfg->aot_opts.save_temps)
5947 printf ("Retained input file.\n");
5949 unlink (acfg->tmpfname);
5954 static MonoAotCompile*
5955 acfg_create (MonoAssembly *ass, guint32 opts)
5957 MonoImage *image = ass->image;
5958 MonoAotCompile *acfg;
5961 acfg = g_new0 (MonoAotCompile, 1);
5962 acfg->methods = g_ptr_array_new ();
5963 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5964 acfg->method_depth = g_hash_table_new (NULL, NULL);
5965 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5966 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5967 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5968 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5969 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5970 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5971 acfg->got_patches = g_ptr_array_new ();
5972 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5973 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5974 acfg->image_hash = g_hash_table_new (NULL, NULL);
5975 acfg->image_table = g_ptr_array_new ();
5976 acfg->globals = g_ptr_array_new ();
5977 acfg->image = image;
5979 acfg->mempool = mono_mempool_new ();
5980 acfg->extra_methods = g_ptr_array_new ();
5981 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5982 acfg->unwind_ops = g_ptr_array_new ();
5983 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5984 InitializeCriticalSection (&acfg->mutex);
5990 acfg_free (MonoAotCompile *acfg)
5994 img_writer_destroy (acfg->w);
5995 for (i = 0; i < acfg->nmethods; ++i)
5997 g_free (acfg->cfgs [i]);
5998 g_free (acfg->cfgs);
5999 g_free (acfg->static_linking_symbol);
6000 g_free (acfg->got_symbol);
6001 g_free (acfg->plt_symbol);
6002 g_ptr_array_free (acfg->methods, TRUE);
6003 g_ptr_array_free (acfg->got_patches, TRUE);
6004 g_ptr_array_free (acfg->image_table, TRUE);
6005 g_ptr_array_free (acfg->globals, TRUE);
6006 g_ptr_array_free (acfg->unwind_ops, TRUE);
6007 g_hash_table_destroy (acfg->method_indexes);
6008 g_hash_table_destroy (acfg->method_depth);
6009 g_hash_table_destroy (acfg->plt_offset_to_patch);
6010 g_hash_table_destroy (acfg->patch_to_plt_offset);
6011 g_hash_table_destroy (acfg->patch_to_got_offset);
6012 g_hash_table_destroy (acfg->method_to_cfg);
6013 g_hash_table_destroy (acfg->token_info_hash);
6014 g_hash_table_destroy (acfg->image_hash);
6015 g_hash_table_destroy (acfg->unwind_info_offsets);
6016 g_hash_table_destroy (acfg->method_label_hash);
6017 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6018 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6019 g_free (acfg->patch_to_got_offset_by_type);
6020 mono_mempool_destroy (acfg->mempool);
6025 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6027 MonoImage *image = ass->image;
6029 MonoAotCompile *acfg;
6030 char *outfile_name, *tmp_outfile_name, *p;
6034 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6036 acfg = acfg_create (ass, opts);
6038 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6039 acfg->aot_opts.write_symbols = TRUE;
6040 acfg->aot_opts.ntrampolines = 1024;
6041 acfg->aot_opts.nrgctx_trampolines = 1024;
6042 acfg->aot_opts.nimt_trampolines = 128;
6044 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6046 if (acfg->aot_opts.static_link)
6047 acfg->aot_opts.autoreg = TRUE;
6049 //acfg->aot_opts.print_skipped_methods = TRUE;
6051 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6052 if (acfg->aot_opts.full_aot) {
6053 printf ("--aot=full is not supported on this platform.\n");
6058 if (acfg->aot_opts.static_link)
6059 acfg->aot_opts.asm_writer = TRUE;
6061 if (acfg->aot_opts.soft_debug) {
6062 MonoDebugOptions *opt = mini_get_debug_options ();
6064 opt->mdb_optimizations = TRUE;
6065 opt->gen_seq_points = TRUE;
6067 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6068 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6075 acfg->aot_opts.asm_writer = TRUE;
6076 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6079 if (acfg->aot_opts.full_aot)
6080 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6082 load_profile_files (acfg);
6084 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6085 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6086 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6088 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6090 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6091 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6093 /* Get rid of characters which cannot occur in symbols */
6094 for (p = acfg->got_symbol_base; *p; ++p) {
6095 if (!(isalnum (*p) || *p == '_'))
6098 for (p = acfg->plt_symbol; *p; ++p) {
6099 if (!(isalnum (*p) || *p == '_'))
6103 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6105 acfg->method_index = 1;
6107 collect_methods (acfg);
6109 acfg->cfgs_size = acfg->methods->len + 32;
6110 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6112 /* PLT offset 0 is reserved for the PLT trampoline */
6113 acfg->plt_offset = 1;
6117 mono_llvm_create_aot_module (acfg->got_symbol_base);
6120 /* GOT offset 0 is reserved for the address of the current assembly */
6124 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6125 ji->type = MONO_PATCH_INFO_IMAGE;
6126 ji->data.image = acfg->image;
6128 get_got_offset (acfg, ji);
6130 /* Slot 1 is reserved for the mscorlib got addr */
6131 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6132 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6133 get_got_offset (acfg, ji);
6138 compile_methods (acfg);
6142 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6148 if (acfg->aot_opts.asm_only) {
6149 if (acfg->aot_opts.outfile)
6150 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6152 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6154 acfg->tmpfname = g_strdup ("temp.s");
6158 emit_llvm_file (acfg);
6161 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6162 if (acfg->aot_opts.outfile)
6163 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6165 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6168 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6169 * it might be in another file system so the rename () won't work.
6171 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6173 acfg->fp = fopen (tmp_outfile_name, "w");
6175 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6179 acfg->w = img_writer_create (acfg->fp, TRUE);
6180 acfg->use_bin_writer = TRUE;
6183 /* Append to the .s file created by llvm */
6184 /* FIXME: Use multiple files instead */
6185 acfg->fp = fopen (acfg->tmpfname, "a+");
6187 if (acfg->aot_opts.asm_only) {
6188 if (acfg->aot_opts.outfile)
6189 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6191 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6192 acfg->fp = fopen (acfg->tmpfname, "w+");
6194 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6195 acfg->fp = fdopen (i, "w+");
6197 g_assert (acfg->fp);
6199 acfg->w = img_writer_create (acfg->fp, FALSE);
6201 tmp_outfile_name = NULL;
6202 outfile_name = NULL;
6206 * The prefix LLVM likes to put in front of symbol names on darwin.
6207 * The mach-os specs require this for globals, but LLVM puts them in front of all
6208 * symbols. We need to handle this, since we need to refer to LLVM generated
6211 acfg->llvm_label_prefix = "";
6213 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6215 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6217 /* Compute symbols for methods */
6218 for (i = 0; i < acfg->nmethods; ++i) {
6219 if (acfg->cfgs [i]) {
6220 MonoCompile *cfg = acfg->cfgs [i];
6221 int method_index = get_method_index (acfg, cfg->orig_method);
6223 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6227 if (!acfg->aot_opts.nodebug)
6228 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6230 img_writer_emit_start (acfg->w);
6233 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6239 emit_extra_methods (acfg);
6241 emit_trampolines (acfg);
6243 emit_class_name_table (acfg);
6245 emit_got_info (acfg);
6247 emit_exception_info (acfg);
6249 emit_unwind_info (acfg);
6251 emit_class_info (acfg);
6255 emit_image_table (acfg);
6259 emit_file_info (acfg);
6263 emit_globals (acfg);
6265 emit_autoreg (acfg);
6268 emit_dwarf_info (acfg);
6269 mono_dwarf_writer_close (acfg->dwarf);
6272 emit_mem_end (acfg);
6276 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6279 g_assert (acfg->got_offset <= acfg->final_got_size);
6281 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);
6284 res = img_writer_emit_writeout (acfg->w);
6289 if (acfg->use_bin_writer) {
6290 int err = rename (tmp_outfile_name, outfile_name);
6293 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6297 res = compile_asm (acfg);
6304 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6306 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);
6307 if (acfg->stats.genericcount)
6308 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6309 if (acfg->stats.abscount)
6310 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6311 if (acfg->stats.lmfcount)
6312 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6313 if (acfg->stats.ocount)
6314 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6316 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6317 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);
6318 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6320 if (acfg->aot_opts.stats) {
6323 printf ("GOT slot distribution:\n");
6324 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6325 if (acfg->stats.got_slot_types [i])
6326 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6329 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);
6341 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)