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 * - reduce the length of the wrapper names.
13 * - aot IMT tables, so we don't have two kinds of aot code.
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
28 #include <sys/types.h>
38 #ifndef PLATFORM_WIN32
48 #include <mono/metadata/tabledefs.h>
49 #include <mono/metadata/class.h>
50 #include <mono/metadata/object.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/assembly.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/marshal.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/mempool-internals.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/utils/mono-logger.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
65 #include <mono/utils/mono-mmap.h>
68 #include "image-writer.h"
69 #include "dwarfwriter.h"
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
73 #define TV_DECLARE(name) gint64 name
74 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
75 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
78 #define SHARED_EXT ".dll"
79 #elif defined(__ppc__) && defined(__MACH__)
80 #define SHARED_EXT ".dylib"
82 #define SHARED_EXT ".so"
85 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
86 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
87 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
89 typedef struct MonoAotOptions {
92 gboolean write_symbols;
93 gboolean metadata_only;
94 gboolean bind_to_runtime_version;
103 gboolean print_skipped_methods;
106 typedef struct MonoAotStats {
107 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
108 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
109 int methods_without_got_slots, direct_calls, all_calls;
111 int got_slot_types [MONO_PATCH_INFO_NONE];
112 int jit_time, gen_time, link_time;
115 typedef struct MonoAotCompile {
118 GHashTable *method_indexes;
121 GHashTable *patch_to_plt_offset;
122 GHashTable *plt_offset_to_patch;
123 GHashTable *patch_to_shared_got_offset;
124 GPtrArray *shared_patches;
125 GHashTable *image_hash;
126 GHashTable *method_to_cfg;
127 GHashTable *token_info_hash;
128 GPtrArray *extra_methods;
129 GPtrArray *image_table;
132 guint32 *plt_got_info_offsets;
133 guint32 got_offset, plt_offset, plt_got_offset_base;
134 /* Number of GOT entries reserved for trampolines */
135 guint32 num_trampoline_got_entries;
137 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
138 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
139 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
141 MonoAotOptions aot_opts;
144 MonoMemPool *mempool;
147 char *static_linking_symbol;
148 CRITICAL_SECTION mutex;
149 gboolean use_bin_writer;
151 MonoDwarfWriter *dwarf;
155 GHashTable *unwind_info_offsets;
156 GPtrArray *unwind_ops;
157 guint32 unwind_info_offset;
161 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
162 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
164 #ifdef HAVE_ARRAY_ELEM_INIT
165 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
166 #define MSGSTRFIELD1(line) str##line
167 static const struct msgstr_t {
168 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
169 #include "patch-info.h"
172 #define PATCH_INFO(a,b) b,
173 #include "patch-info.h"
176 static const gint16 opidx [] = {
177 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
178 #include "patch-info.h"
182 static G_GNUC_UNUSED const char*
183 get_patch_name (int info)
185 return (const char*)&opstr + opidx [info];
189 #define PATCH_INFO(a,b) b,
190 static const char* const
191 patch_types [MONO_PATCH_INFO_NUM + 1] = {
192 #include "patch-info.h"
197 get_patch_name (int info)
199 return patch_types [info];
204 /* Wrappers around the image writer functions */
207 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
209 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
213 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
215 img_writer_emit_push_section (acfg->w, section_name, subsection);
219 emit_pop_section (MonoAotCompile *acfg)
221 img_writer_emit_pop_section (acfg->w);
225 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
227 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
231 emit_label (MonoAotCompile *acfg, const char *name)
233 img_writer_emit_label (acfg->w, name);
237 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
239 img_writer_emit_bytes (acfg->w, buf, size);
243 emit_string (MonoAotCompile *acfg, const char *value)
245 img_writer_emit_string (acfg->w, value);
249 emit_line (MonoAotCompile *acfg)
251 img_writer_emit_line (acfg->w);
255 emit_alignment (MonoAotCompile *acfg, int size)
257 img_writer_emit_alignment (acfg->w, size);
261 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
263 img_writer_emit_pointer_unaligned (acfg->w, target);
267 emit_pointer (MonoAotCompile *acfg, const char *target)
269 img_writer_emit_pointer (acfg->w, target);
273 emit_int16 (MonoAotCompile *acfg, int value)
275 img_writer_emit_int16 (acfg->w, value);
279 emit_int32 (MonoAotCompile *acfg, int value)
281 img_writer_emit_int32 (acfg->w, value);
285 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
287 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
291 emit_zero_bytes (MonoAotCompile *acfg, int num)
293 img_writer_emit_zero_bytes (acfg->w, num);
297 emit_byte (MonoAotCompile *acfg, guint8 val)
299 img_writer_emit_byte (acfg->w, val);
302 static G_GNUC_UNUSED void
303 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
305 img_writer_emit_global (acfg->w, name, func);
309 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
311 if (acfg->aot_opts.no_dlsym) {
312 g_ptr_array_add (acfg->globals, g_strdup (name));
314 img_writer_emit_global (acfg->w, name, func);
319 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
321 img_writer_emit_section_change (acfg->w, ".text", 1);
322 emit_global (acfg, name, FALSE);
323 img_writer_emit_label (acfg->w, name);
324 img_writer_emit_string (acfg->w, value);
327 static G_GNUC_UNUSED void
328 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
331 guint8 b = value & 0x7f;
333 if (value != 0) /* more bytes to come */
339 static G_GNUC_UNUSED void
340 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
343 gboolean negative = (value < 0);
350 /* the following is unnecessary if the
351 * implementation of >>= uses an arithmetic rather
352 * than logical shift for a signed left operand
356 value |= - ((gint64)1 <<(size - 7));
357 /* sign bit of byte is second high order bit (0x40) */
358 if ((value == 0 && !(byte & 0x40)) ||
359 (value == -1 && (byte & 0x40)))
363 emit_byte (acfg, byte);
367 static G_GNUC_UNUSED void
368 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
373 guint8 b = value & 0x7f;
375 if (value != 0) /* more bytes to come */
383 static G_GNUC_UNUSED void
384 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
387 gboolean negative = (value < 0);
395 /* the following is unnecessary if the
396 * implementation of >>= uses an arithmetic rather
397 * than logical shift for a signed left operand
401 value |= - (1 <<(size - 7));
402 /* sign bit of byte is second high order bit (0x40) */
403 if ((value == 0 && !(byte & 0x40)) ||
404 (value == -1 && (byte & 0x40)))
414 /* ARCHITECTURE SPECIFIC CODE */
416 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
417 #define EMIT_DWARF_INFO 1
421 * arch_emit_direct_call:
423 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
427 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
429 #if defined(TARGET_X86) || defined(TARGET_AMD64)
430 /* Need to make sure this is exactly 5 bytes long */
431 emit_byte (acfg, '\xe8');
432 emit_symbol_diff (acfg, target, ".", -4);
434 #elif defined(TARGET_ARM)
435 if (acfg->use_bin_writer) {
442 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
443 emit_bytes (acfg, buf, 4);
445 img_writer_emit_unset_mode (acfg->w);
446 fprintf (acfg->fp, "bl %s\n", target);
450 g_assert_not_reached ();
454 #ifdef MONO_ARCH_AOT_SUPPORTED
456 * arch_emit_got_offset:
458 * The memory pointed to by CODE should hold native code for computing the GOT
459 * address. Emit this code while patching it with the offset between code and
460 * the GOT. CODE_SIZE is set to the number of bytes emitted.
463 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
465 guint32 offset = mono_arch_get_patch_offset (code);
466 emit_bytes (acfg, code, offset);
467 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
469 *code_size = offset + 4;
473 * arch_emit_got_access:
475 * The memory pointed to by CODE should hold native code for loading a GOT
476 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
477 * CODE_SIZE is set to the number of bytes emitted.
480 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
482 /* Emit beginning of instruction */
483 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
485 /* Emit the offset */
487 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
488 #elif defined(TARGET_X86)
489 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
490 #elif defined(TARGET_ARM)
491 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
493 g_assert_not_reached ();
496 *code_size = mono_arch_get_patch_offset (code) + 4;
502 * arch_emit_plt_entry:
504 * Emit code for the PLT entry with index INDEX.
507 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
509 #if defined(TARGET_X86)
511 /* It is filled up during loading by the AOT loader. */
512 emit_zero_bytes (acfg, 16);
514 /* Need to make sure this is 9 bytes long */
515 emit_byte (acfg, '\xe9');
516 emit_symbol_diff (acfg, "plt", ".", -4);
517 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
519 #elif defined(TARGET_AMD64)
521 * We can't emit jumps because they are 32 bits only so they can't be patched.
522 * So we make indirect calls through GOT entries which are patched by the AOT
523 * loader to point to .Lpd entries.
524 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
526 /* jmpq *<offset>(%rip) */
527 emit_byte (acfg, '\xff');
528 emit_byte (acfg, '\x25');
529 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
530 /* Used by mono_aot_get_plt_info_offset */
531 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
532 #elif defined(TARGET_ARM)
537 * - optimize OP_AOTCONST implementation
538 * - optimize the PLT entries
539 * - optimize SWITCH AOT implementation
540 * - implement IMT support
543 if (acfg->use_bin_writer) {
544 /* We only emit 1 relocation since we implement it ourselves anyway */
545 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
546 /* FIXME: A 2 instruction encoding is sufficient in most cases */
547 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
548 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
549 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
550 emit_bytes (acfg, buf, code - buf);
551 /* FIXME: Get rid of this */
552 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
553 /* Used by mono_aot_get_plt_info_offset */
554 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
556 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
557 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
558 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
559 emit_bytes (acfg, buf, code - buf);
560 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
561 /* Used by mono_aot_get_plt_info_offset */
562 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
565 g_assert_not_reached ();
570 * arch_emit_specific_trampoline:
572 * Emit code for a specific trampoline. OFFSET is the offset of the first of
573 * two GOT slots which contain the generic trampoline address and the trampoline
574 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
577 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
580 * The trampolines created here are variations of the specific
581 * trampolines created in mono_arch_create_specific_trampoline (). The
583 * - the generic trampoline address is taken from a got slot.
584 * - the offset of the got slot where the trampoline argument is stored
585 * is embedded in the instruction stream, and the generic trampoline
586 * can load the argument by loading the offset, adding it to the
587 * address of the trampoline to get the address of the got slot, and
588 * loading the argument from there.
589 * - all the trampolines should be of the same length.
591 #if defined(TARGET_AMD64)
592 /* This should be exactly 16 bytes long */
594 /* call *<offset>(%rip) */
595 emit_byte (acfg, '\x41');
596 emit_byte (acfg, '\xff');
597 emit_byte (acfg, '\x15');
598 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
599 /* This should be relative to the start of the trampoline */
600 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
601 emit_zero_bytes (acfg, 5);
602 #elif defined(TARGET_ARM)
606 /* This should be exactly 28 bytes long */
609 ARM_PUSH (code, 0x5fff);
610 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
611 /* Load the value from the GOT */
612 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
614 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
615 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
617 g_assert (code - buf == 20);
620 emit_bytes (acfg, buf, code - buf);
621 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
622 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
624 g_assert_not_reached ();
629 * arch_emit_unbox_trampoline:
631 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
632 * CALL_TARGET is the symbol pointing to the native code of METHOD.
635 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
637 #if defined(TARGET_AMD64)
642 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
644 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
646 emit_bytes (acfg, buf, code - buf);
648 emit_byte (acfg, '\xe9');
649 emit_symbol_diff (acfg, call_target, ".", -4);
650 #elif defined(TARGET_ARM)
657 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
660 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
662 emit_bytes (acfg, buf, code - buf);
664 if (acfg->use_bin_writer) {
671 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
672 emit_bytes (acfg, buf, 4);
674 fprintf (acfg->fp, "\n\tb %s\n", call_target);
677 g_assert_not_reached ();
682 * arch_emit_static_rgctx_trampoline:
684 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
685 * two GOT slots which contain the rgctx argument, and the method to jump to.
686 * TRAMP_SIZE is set to the size of the emitted trampoline.
687 * These kinds of trampolines cannot be enumerated statically, since there could
688 * be one trampoline per method instantiation, so we emit the same code for all
689 * trampolines, and parameterize them using two GOT slots.
692 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
694 #if defined(TARGET_AMD64)
695 /* This should be exactly 13 bytes long */
698 /* mov <OFFSET>(%rip), %r10 */
699 emit_byte (acfg, '\x4d');
700 emit_byte (acfg, '\x8b');
701 emit_byte (acfg, '\x15');
702 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
704 /* jmp *<offset>(%rip) */
705 emit_byte (acfg, '\xff');
706 emit_byte (acfg, '\x25');
707 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
708 #elif defined(TARGET_ARM)
712 /* This should be exactly 24 bytes long */
715 /* Load rgctx value */
716 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
717 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
718 /* Load branch addr + branch */
719 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
720 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
722 g_assert (code - buf == 16);
725 emit_bytes (acfg, buf, code - buf);
726 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
727 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
729 g_assert_not_reached ();
734 * arch_emit_imt_thunk:
736 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
737 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
738 * key is the IMT key, and ptr holds the address of a memory location holding
739 * the address to branch to if the IMT arg matches the key. The array is
740 * terminated by a pair whose key is NULL, and whose ptr is the address of the
742 * TRAMP_SIZE is set to the size of the emitted trampoline.
745 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
747 #if defined(TARGET_AMD64)
751 code = buf = g_malloc (256);
753 /* FIXME: Optimize this, i.e. use binary search etc. */
754 /* Maybe move the body into a separate function (slower, but much smaller) */
756 /* R10 is a free register */
759 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
761 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
764 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
766 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
769 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
770 amd64_jump_code (code, labels [0]);
773 mono_amd64_patch (labels [2], code);
774 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
775 amd64_jump_membase (code, AMD64_R10, 0);
779 mono_amd64_patch (labels [1], code);
780 x86_breakpoint (code);
782 /* mov <OFFSET>(%rip), %r10 */
783 emit_byte (acfg, '\x4d');
784 emit_byte (acfg, '\x8b');
785 emit_byte (acfg, '\x15');
786 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
788 emit_bytes (acfg, buf, code - buf);
790 *tramp_size = code - buf + 7;
791 #elif defined(TARGET_ARM)
793 guint8 *code, *code2, *labels [16];
797 /* The IMT method is in v5 */
799 /* Only IP is available, but we need at least two free registers */
800 ARM_PUSH1 (code, ARMREG_R1);
802 /* Load the parameter from the GOT */
803 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
804 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
807 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_IP, 0);
808 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
810 ARM_B_COND (code, ARMCOND_EQ, 0);
812 /* End-of-loop check */
813 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
815 ARM_B_COND (code, ARMCOND_EQ, 0);
818 ARM_ADD_REG_IMM8 (code, ARMREG_IP, ARMREG_IP, sizeof (gpointer) * 2);
821 arm_patch (labels [4], labels [1]);
824 arm_patch (labels [2], code);
825 ARM_POP1 (code, ARMREG_R1);
826 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_IP, 4);
827 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
830 arm_patch (labels [3], code);
835 ARM_LDR_IMM (code2, ARMREG_IP, ARMREG_PC, (code - (labels [0] + 8)));
837 emit_bytes (acfg, buf, code - buf);
838 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
840 *tramp_size = code - buf + 4;
842 g_assert_not_reached ();
847 * arch_get_cie_program:
849 * Get the unwind bytecode for the DWARF CIE.
852 arch_get_cie_program (void)
857 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
858 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
866 /* END OF ARCH SPECIFIC CODE */
869 mono_get_field_token (MonoClassField *field)
871 MonoClass *klass = field->parent;
874 for (i = 0; i < klass->field.count; ++i) {
875 if (field == &klass->fields [i])
876 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
879 g_assert_not_reached ();
884 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
888 //printf ("ENCODE: %d 0x%x.\n", value, value);
891 * Same encoding as the one used in the metadata, extended to handle values
892 * greater than 0x1fffffff.
894 if ((value >= 0) && (value <= 127))
896 else if ((value >= 0) && (value <= 16383)) {
897 p [0] = 0x80 | (value >> 8);
898 p [1] = value & 0xff;
900 } else if ((value >= 0) && (value <= 0x1fffffff)) {
901 p [0] = (value >> 24) | 0xc0;
902 p [1] = (value >> 16) & 0xff;
903 p [2] = (value >> 8) & 0xff;
904 p [3] = value & 0xff;
909 p [1] = (value >> 24) & 0xff;
910 p [2] = (value >> 16) & 0xff;
911 p [3] = (value >> 8) & 0xff;
912 p [4] = value & 0xff;
920 get_image_index (MonoAotCompile *cfg, MonoImage *image)
924 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
928 index = g_hash_table_size (cfg->image_hash);
929 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
930 g_ptr_array_add (cfg->image_table, image);
936 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
941 /* FIXME: Search referenced images as well */
942 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
943 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
948 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
949 return MONO_TOKEN_TYPE_SPEC | (i + 1);
955 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
960 * Encode a reference to KLASS. We use our home-grown encoding instead of the
961 * standard metadata encoding.
964 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
968 if (klass->generic_class) {
970 g_assert (klass->type_token);
972 /* Find a typespec for a class if possible */
973 token = find_typespec_for_class (acfg, klass);
975 encode_value (token, p, &p);
976 encode_value (get_image_index (acfg, acfg->image), p, &p);
978 MonoClass *gclass = klass->generic_class->container_class;
979 MonoGenericInst *inst = klass->generic_class->context.class_inst;
982 /* Encode it ourselves */
984 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
985 encode_value (MONO_TYPE_GENERICINST, p, &p);
986 encode_klass_ref (acfg, gclass, p, &p);
987 encode_value (inst->type_argc, p, &p);
988 for (i = 0; i < inst->type_argc; ++i)
989 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
991 } else if (klass->type_token) {
992 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
993 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
994 encode_value (get_image_index (acfg, klass->image), p, &p);
995 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
996 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
997 g_assert (container);
1000 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1001 encode_value (klass->byval_arg.type, p, &p);
1003 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1005 encode_value (container->is_method, p, &p);
1006 if (container->is_method)
1007 encode_method_ref (acfg, container->owner.method, p, &p);
1009 encode_klass_ref (acfg, container->owner.klass, p, &p);
1012 g_assert (klass->rank > 0);
1013 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1014 encode_value (get_image_index (acfg, klass->image), p, &p);
1015 encode_value (klass->rank, p, &p);
1016 encode_klass_ref (acfg, klass->element_class, p, &p);
1022 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1024 guint32 token = mono_get_field_token (field);
1027 encode_klass_ref (cfg, field->parent, p, &p);
1028 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1029 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1034 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1038 MonoGenericInst *inst;
1040 /* Encode the context */
1041 inst = context->class_inst;
1042 encode_value (inst ? 1 : 0, p, &p);
1044 encode_value (inst->type_argc, p, &p);
1045 for (i = 0; i < inst->type_argc; ++i)
1046 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1048 inst = context->method_inst;
1049 encode_value (inst ? 1 : 0, p, &p);
1051 encode_value (inst->type_argc, p, &p);
1052 for (i = 0; i < inst->type_argc; ++i)
1053 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1059 #define MAX_IMAGE_INDEX 250
1062 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1064 guint32 image_index = get_image_index (acfg, method->klass->image);
1065 guint32 token = method->token;
1066 MonoJumpInfoToken *ji;
1071 * The encoding for most methods is as follows:
1072 * - image index encoded as a leb128
1073 * - token index encoded as a leb128
1074 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1075 * types of method encodings.
1078 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1080 /* Mark methods which can't use aot trampolines because they need the further
1081 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1083 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1084 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1085 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1088 * Some wrapper methods are shared using their signature, encode their
1089 * stringified signature instead.
1090 * FIXME: Optimize disk usage
1093 if (method->wrapper_type) {
1094 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1095 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1096 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1098 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1099 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1100 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1102 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1103 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1104 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1106 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1107 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1108 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1114 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1115 strcpy ((char*)p, name);
1116 p += strlen (name) + 1;
1118 } else if (method->wrapper_type) {
1119 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1121 encode_value (method->wrapper_type, p, &p);
1123 switch (method->wrapper_type) {
1124 case MONO_WRAPPER_REMOTING_INVOKE:
1125 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1126 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1129 m = mono_marshal_method_from_wrapper (method);
1131 encode_method_ref (acfg, m, p, &p);
1134 case MONO_WRAPPER_PROXY_ISINST:
1135 case MONO_WRAPPER_LDFLD:
1136 case MONO_WRAPPER_LDFLDA:
1137 case MONO_WRAPPER_STFLD:
1138 case MONO_WRAPPER_ISINST: {
1139 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1140 encode_klass_ref (acfg, proxy_class, p, &p);
1143 case MONO_WRAPPER_LDFLD_REMOTE:
1144 case MONO_WRAPPER_STFLD_REMOTE:
1146 case MONO_WRAPPER_ALLOC: {
1147 int alloc_type = mono_gc_get_managed_allocator_type (method);
1148 g_assert (alloc_type != -1);
1149 encode_value (alloc_type, p, &p);
1152 case MONO_WRAPPER_STELEMREF:
1154 case MONO_WRAPPER_UNKNOWN:
1155 if (strcmp (method->name, "FastMonitorEnter") == 0)
1156 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1157 else if (strcmp (method->name, "FastMonitorExit") == 0)
1158 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1160 g_assert_not_reached ();
1162 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
1163 case MONO_WRAPPER_SYNCHRONIZED:
1164 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
1167 m = mono_marshal_method_from_wrapper (method);
1169 g_assert (m != method);
1170 encode_method_ref (acfg, m, p, &p);
1174 g_assert_not_reached ();
1176 } else if (mono_method_signature (method)->is_inflated) {
1178 * This is a generic method, find the original token which referenced it and
1180 * Obtain the token from information recorded by the JIT.
1182 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1184 image_index = get_image_index (acfg, ji->image);
1185 g_assert (image_index < MAX_IMAGE_INDEX);
1188 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1189 encode_value (image_index, p, &p);
1190 encode_value (token, p, &p);
1192 MonoMethod *declaring;
1193 MonoGenericContext *context = mono_method_get_context (method);
1195 g_assert (method->is_inflated);
1196 declaring = ((MonoMethodInflated*)method)->declaring;
1199 * This might be a non-generic method of a generic instance, which
1200 * doesn't have a token since the reference is generated by the JIT
1201 * like Nullable:Box/Unbox, or by generic sharing.
1204 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1205 /* Encode the klass */
1206 encode_klass_ref (acfg, method->klass, p, &p);
1207 /* Encode the method */
1208 image_index = get_image_index (acfg, method->klass->image);
1209 g_assert (image_index < MAX_IMAGE_INDEX);
1210 g_assert (declaring->token);
1211 token = declaring->token;
1212 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1213 encode_value (image_index, p, &p);
1214 encode_value (token, p, &p);
1215 encode_generic_context (acfg, context, p, &p);
1217 } else if (token == 0) {
1218 /* This might be a method of a constructed type like int[,].Set */
1219 /* Obtain the token from information recorded by the JIT */
1220 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1222 image_index = get_image_index (acfg, ji->image);
1223 g_assert (image_index < MAX_IMAGE_INDEX);
1226 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1227 encode_value (image_index, p, &p);
1228 encode_value (token, p, &p);
1231 g_assert (method->klass->rank);
1233 /* Encode directly */
1234 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1235 encode_klass_ref (acfg, method->klass, p, &p);
1236 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1237 encode_value (0, p, &p);
1238 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1239 encode_value (1, p, &p);
1240 else if (!strcmp (method->name, "Get"))
1241 encode_value (2, p, &p);
1242 else if (!strcmp (method->name, "Address"))
1243 encode_value (3, p, &p);
1244 else if (!strcmp (method->name, "Set"))
1245 encode_value (4, p, &p);
1247 g_assert_not_reached ();
1250 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1251 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1257 compare_patches (gconstpointer a, gconstpointer b)
1261 i = (*(MonoJumpInfo**)a)->ip.i;
1262 j = (*(MonoJumpInfo**)b)->ip.i;
1276 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1279 static inline gboolean
1280 is_plt_patch (MonoJumpInfo *patch_info)
1282 switch (patch_info->type) {
1283 case MONO_PATCH_INFO_METHOD:
1284 case MONO_PATCH_INFO_INTERNAL_METHOD:
1285 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1286 case MONO_PATCH_INFO_ICALL_ADDR:
1287 case MONO_PATCH_INFO_CLASS_INIT:
1288 case MONO_PATCH_INFO_RGCTX_FETCH:
1289 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1290 case MONO_PATCH_INFO_MONITOR_ENTER:
1291 case MONO_PATCH_INFO_MONITOR_EXIT:
1299 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1303 if (is_plt_patch (patch_info)) {
1304 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1306 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1308 * Allocate a separate PLT slot for each such patch, since some plt
1309 * entries will refer to the method itself, and some will refer to
1318 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1320 res = acfg->plt_offset;
1321 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1322 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1323 acfg->plt_offset ++;
1333 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1334 * JI could be found if it exists, otherwise allocates a new one.
1337 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1341 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1343 return got_offset - 1;
1345 got_offset = acfg->got_offset;
1346 acfg->got_offset ++;
1348 acfg->stats.got_slots ++;
1349 acfg->stats.got_slot_types [ji->type] ++;
1355 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1360 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1361 got_offset = get_got_offset (acfg, ji);
1362 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1363 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1364 g_ptr_array_add (acfg->shared_patches, copy);
1367 return get_got_offset (acfg, ji);
1370 /* Add a method to the list of methods which need to be emitted */
1372 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1375 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1376 g_ptr_array_add (acfg->methods, method);
1377 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1378 acfg->nmethods = acfg->methods->len + 1;
1383 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1385 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1393 add_method (MonoAotCompile *acfg, MonoMethod *method)
1397 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1401 index = acfg->method_index;
1402 add_method_with_index (acfg, method, index);
1404 /* FIXME: Fix quadratic behavior */
1405 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1407 acfg->method_index ++;
1413 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1417 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1420 add_method (acfg, method);
1421 g_ptr_array_add (acfg->extra_methods, method);
1425 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1427 MonoAotCompile *acfg = user_data;
1428 MonoJitICallInfo *callinfo = value;
1429 MonoMethod *wrapper;
1435 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1436 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1439 add_method (acfg, wrapper);
1443 get_runtime_invoke_sig (MonoMethodSignature *sig)
1445 MonoMethodBuilder *mb;
1448 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1449 m = mono_mb_create_method (mb, sig, 16);
1450 return mono_marshal_get_runtime_invoke (m, FALSE);
1454 add_wrappers (MonoAotCompile *acfg)
1456 MonoMethod *method, *m;
1457 int i, j, nallocators;
1458 MonoMethodSignature *sig, *csig;
1462 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1463 * so there is only one wrapper of a given type, or inlining their contents into their
1468 * FIXME: This depends on the fact that different wrappers have different
1472 /* FIXME: Collect these automatically */
1474 /* Runtime invoke wrappers */
1476 /* void runtime-invoke () [.cctor] */
1477 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1478 csig->ret = &mono_defaults.void_class->byval_arg;
1479 add_method (acfg, get_runtime_invoke_sig (csig));
1481 /* void runtime-invoke () [Finalize] */
1482 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1484 csig->ret = &mono_defaults.void_class->byval_arg;
1485 add_method (acfg, get_runtime_invoke_sig (csig));
1487 /* void runtime-invoke (string) [exception ctor] */
1488 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1490 csig->ret = &mono_defaults.void_class->byval_arg;
1491 csig->params [0] = &mono_defaults.string_class->byval_arg;
1492 add_method (acfg, get_runtime_invoke_sig (csig));
1494 /* void runtime-invoke (string, string) [exception ctor] */
1495 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1497 csig->ret = &mono_defaults.void_class->byval_arg;
1498 csig->params [0] = &mono_defaults.string_class->byval_arg;
1499 csig->params [1] = &mono_defaults.string_class->byval_arg;
1500 add_method (acfg, get_runtime_invoke_sig (csig));
1502 /* string runtime-invoke () [Exception.ToString ()] */
1503 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1505 csig->ret = &mono_defaults.string_class->byval_arg;
1506 add_method (acfg, get_runtime_invoke_sig (csig));
1508 /* void runtime-invoke (string, Exception) [exception ctor] */
1509 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1511 csig->ret = &mono_defaults.void_class->byval_arg;
1512 csig->params [0] = &mono_defaults.string_class->byval_arg;
1513 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1514 add_method (acfg, get_runtime_invoke_sig (csig));
1516 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1517 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1519 csig->ret = &(mono_class_from_name (
1520 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1521 csig->params [0] = &mono_defaults.string_class->byval_arg;
1522 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1523 add_method (acfg, get_runtime_invoke_sig (csig));
1525 /* runtime-invoke used by finalizers */
1526 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1528 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1530 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1531 gboolean skip = FALSE;
1533 method = mono_get_method (acfg->image, token, NULL);
1535 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1536 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1537 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1540 if (method->is_generic || method->klass->generic_container)
1543 /* Skip methods which can not be handled by get_runtime_invoke () */
1544 sig = mono_method_signature (method);
1545 if ((sig->ret->type == MONO_TYPE_PTR) ||
1546 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1549 for (j = 0; j < sig->param_count; j++) {
1550 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1555 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1558 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1559 MonoMethodDesc *desc;
1560 MonoMethod *orig_method;
1562 /* JIT icall wrappers */
1563 /* FIXME: locking */
1564 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1566 /* Managed Allocators */
1567 nallocators = mono_gc_get_managed_allocator_types ();
1568 for (i = 0; i < nallocators; ++i) {
1569 m = mono_gc_get_managed_allocator_by_type (i);
1571 add_method (acfg, m);
1575 add_method (acfg, mono_marshal_get_stelemref ());
1577 /* Monitor Enter/Exit */
1578 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1579 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1580 g_assert (orig_method);
1581 mono_method_desc_free (desc);
1582 method = mono_monitor_get_fast_path (orig_method);
1584 add_method (acfg, method);
1586 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1587 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1588 g_assert (orig_method);
1589 mono_method_desc_free (desc);
1590 method = mono_monitor_get_fast_path (orig_method);
1592 add_method (acfg, method);
1595 /* remoting-invoke wrappers */
1596 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1597 MonoMethodSignature *sig;
1599 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1600 method = mono_get_method (acfg->image, token, NULL);
1602 sig = mono_method_signature (method);
1604 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1605 m = mono_marshal_get_remoting_invoke_with_check (method);
1607 add_method (acfg, m);
1611 /* delegate-invoke wrappers */
1612 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1615 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1616 klass = mono_class_get (acfg->image, token);
1618 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1619 method = mono_get_delegate_invoke (klass);
1621 m = mono_marshal_get_delegate_invoke (method, NULL);
1623 add_method (acfg, m);
1625 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1626 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1628 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1629 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1633 /* Synchronized wrappers */
1634 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1635 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1636 method = mono_get_method (acfg->image, token, NULL);
1638 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1639 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1642 /* pinvoke wrappers */
1643 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1645 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1647 method = mono_get_method (acfg->image, token, NULL);
1649 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1650 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1651 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1657 has_type_vars (MonoClass *klass)
1659 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1662 return has_type_vars (klass->element_class);
1663 if (klass->generic_class) {
1664 MonoGenericContext *context = &klass->generic_class->context;
1665 if (context->class_inst) {
1668 for (i = 0; i < context->class_inst->type_argc; ++i)
1669 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1677 method_has_type_vars (MonoMethod *method)
1679 if (has_type_vars (method->klass))
1682 if (method->is_inflated) {
1683 MonoGenericContext *context = mono_method_get_context (method);
1684 if (context->method_inst) {
1687 for (i = 0; i < context->method_inst->type_argc; ++i)
1688 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1696 * add_generic_class:
1698 * Add all methods of a generic class.
1701 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1706 mono_class_init (klass);
1708 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1711 if (has_type_vars (klass))
1714 if (!klass->generic_class && !klass->rank)
1718 * Add rgctx wrappers for cctors since those are called by the runtime, so
1719 * there is no methodspec for them. This is needed even for shared classes,
1720 * since rgctx wrappers belong to inflated methods.
1722 method = mono_class_get_cctor (klass);
1723 if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
1724 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1727 while ((method = mono_class_get_methods (klass, &iter))) {
1728 if (mono_method_is_generic_sharable_impl (method, FALSE))
1732 if (method->is_generic)
1737 * FIXME: Instances which are referenced by these methods are not added,
1738 * for example Array.Resize<int> for List<int>.Add ().
1740 add_extra_method (acfg, method);
1744 * For ICollection<T>, where T is a vtype, add instances of the helper methods
1745 * in Array, since a T[] could be cast to ICollection<T>.
1747 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
1748 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
1749 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
1750 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
1751 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
1755 if (!strcmp (klass->name, "IEnumerator`1"))
1756 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
1758 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
1760 /* Add the T[]/InternalEnumerator class */
1761 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
1765 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
1766 if (!strcmp (nclass->name, "InternalEnumerator`1"))
1770 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
1771 add_generic_class (acfg, nclass);
1775 while ((method = mono_class_get_methods (array_class, &iter))) {
1776 if (strstr (method->name, name_prefix))
1777 add_extra_method (acfg, method);
1780 g_free (name_prefix);
1785 * add_generic_instances:
1787 * Add instances referenced by the METHODSPEC/TYPESPEC table.
1790 add_generic_instances (MonoAotCompile *acfg)
1795 MonoMethodHeader *header;
1796 MonoMethodSignature *sig;
1797 MonoGenericContext *context;
1799 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1800 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1801 method = mono_get_method (acfg->image, token, NULL);
1803 context = mono_method_get_context (method);
1804 if (context && ((context->class_inst && context->class_inst->is_open) ||
1805 (context->method_inst && context->method_inst->is_open)))
1808 if (method->klass->image != acfg->image)
1811 if (mono_method_is_generic_sharable_impl (method, FALSE))
1815 add_extra_method (acfg, method);
1818 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1821 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1823 klass = mono_class_get (acfg->image, token);
1827 add_generic_class (acfg, klass);
1830 /* Add types of args/locals */
1831 for (i = 0; i < acfg->methods->len; ++i) {
1834 method = g_ptr_array_index (acfg->methods, i);
1836 sig = mono_method_signature (method);
1839 for (j = 0; j < sig->param_count; ++j)
1840 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
1841 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
1844 header = mono_method_get_header (method);
1847 for (j = 0; j < header->num_locals; ++j)
1848 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
1849 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
1855 * emit_and_reloc_code:
1857 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1858 * is true, calls are made through the GOT too. This is used for emitting trampolines
1859 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1860 * since trampolines are needed to make PTL work.
1863 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1865 int i, pindex, start_index, method_index;
1867 MonoJumpInfo *patch_info;
1868 MonoMethodHeader *header;
1869 gboolean skip, direct_call;
1871 char direct_call_target [128];
1874 header = mono_method_get_header (method);
1876 method_index = get_method_index (acfg, method);
1879 /* Collect and sort relocations */
1880 patches = g_ptr_array_new ();
1881 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1882 g_ptr_array_add (patches, patch_info);
1883 g_ptr_array_sort (patches, compare_patches);
1886 for (i = 0; i < code_len; i++) {
1888 for (pindex = start_index; pindex < patches->len; ++pindex) {
1889 patch_info = g_ptr_array_index (patches, pindex);
1890 if (patch_info->ip.i >= i)
1894 #ifdef MONO_ARCH_AOT_SUPPORTED
1896 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1897 start_index = pindex;
1899 switch (patch_info->type) {
1900 case MONO_PATCH_INFO_NONE:
1902 case MONO_PATCH_INFO_GOT_OFFSET: {
1905 arch_emit_got_offset (acfg, code + i, &code_size);
1912 * If this patch is a call, try emitting a direct call instead of
1913 * through a PLT entry. This is possible if the called method is in
1914 * the same assembly and requires no initialization.
1916 direct_call = FALSE;
1917 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1918 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1920 gboolean direct_callable = TRUE;
1922 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1923 direct_callable = FALSE;
1924 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1925 // FIXME: Maybe call the wrapper directly ?
1926 direct_callable = FALSE;
1927 if (direct_callable) {
1928 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1930 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1931 patch_info->type = MONO_PATCH_INFO_NONE;
1932 acfg->stats.direct_calls ++;
1936 acfg->stats.all_calls ++;
1939 if (!got_only && !direct_call) {
1940 int plt_offset = get_plt_offset (acfg, patch_info);
1941 if (plt_offset != -1) {
1942 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1944 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1946 /* Nullify the patch */
1947 patch_info->type = MONO_PATCH_INFO_NONE;
1954 arch_emit_direct_call (acfg, direct_call_target, &call_size);
1959 got_slot = get_got_offset (acfg, patch_info);
1961 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1968 #endif /* MONO_ARCH_AOT_SUPPORTED */
1971 /* Find next patch */
1973 for (pindex = start_index; pindex < patches->len; ++pindex) {
1974 patch_info = g_ptr_array_index (patches, pindex);
1975 if (patch_info->ip.i >= i)
1979 /* Try to emit multiple bytes at once */
1980 if (pindex < patches->len && patch_info->ip.i > i) {
1981 emit_bytes (acfg, code + i, patch_info->ip.i - i);
1982 i = patch_info->ip.i - 1;
1984 emit_bytes (acfg, code + i, 1);
1991 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1997 int func_alignment = 16;
1998 MonoMethodHeader *header;
2000 method = cfg->orig_method;
2001 code = cfg->native_code;
2002 header = mono_method_get_header (method);
2004 method_index = get_method_index (acfg, method);
2006 /* Make the labels local */
2007 sprintf (symbol, ".Lm_%x", method_index);
2009 emit_alignment (acfg, func_alignment);
2010 emit_label (acfg, symbol);
2012 if (acfg->aot_opts.write_symbols && !acfg->aot_opts.nodebug) {
2013 char *name1, *name2;
2016 name1 = mono_method_full_name (method, TRUE);
2017 len = strlen (name1);
2018 name2 = malloc (len + 1);
2020 for (i = 0; i < len; ++i) {
2021 if (isalnum (name1 [i])) {
2022 name2 [j ++] = name1 [i];
2023 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2025 } else if (name1 [i] == '(' || name1 [i] == ')') {
2030 sprintf (symbol, ".Lme_%x", method_index);
2031 emit_local_symbol (acfg, name2, symbol, TRUE);
2032 emit_label (acfg, name2);
2037 if (cfg->verbose_level > 0)
2038 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2040 acfg->stats.code_size += cfg->code_len;
2042 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2044 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2048 sprintf (symbol, ".Lme_%x", method_index);
2049 emit_label (acfg, symbol);
2055 * Encode PATCH_INFO into its disk representation.
2058 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2062 switch (patch_info->type) {
2063 case MONO_PATCH_INFO_NONE:
2065 case MONO_PATCH_INFO_IMAGE:
2066 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2068 case MONO_PATCH_INFO_METHOD_REL:
2069 encode_value ((gint)patch_info->data.offset, p, &p);
2071 case MONO_PATCH_INFO_SWITCH: {
2072 gpointer *table = (gpointer *)patch_info->data.table->table;
2075 encode_value (patch_info->data.table->table_size, p, &p);
2076 for (k = 0; k < patch_info->data.table->table_size; k++)
2077 encode_value ((int)(gssize)table [k], p, &p);
2080 case MONO_PATCH_INFO_METHODCONST:
2081 case MONO_PATCH_INFO_METHOD:
2082 case MONO_PATCH_INFO_METHOD_JUMP:
2083 case MONO_PATCH_INFO_ICALL_ADDR:
2084 case MONO_PATCH_INFO_METHOD_RGCTX:
2085 encode_method_ref (acfg, patch_info->data.method, p, &p);
2087 case MONO_PATCH_INFO_INTERNAL_METHOD:
2088 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2089 guint32 len = strlen (patch_info->data.name);
2091 encode_value (len, p, &p);
2093 memcpy (p, patch_info->data.name, len);
2098 case MONO_PATCH_INFO_LDSTR: {
2099 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2100 guint32 token = patch_info->data.token->token;
2101 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2102 encode_value (image_index, p, &p);
2103 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2106 case MONO_PATCH_INFO_RVA:
2107 case MONO_PATCH_INFO_DECLSEC:
2108 case MONO_PATCH_INFO_LDTOKEN:
2109 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2110 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2111 encode_value (patch_info->data.token->token, p, &p);
2112 encode_value (patch_info->data.token->has_context, p, &p);
2113 if (patch_info->data.token->has_context)
2114 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2116 case MONO_PATCH_INFO_EXC_NAME: {
2117 MonoClass *ex_class;
2120 mono_class_from_name (mono_defaults.exception_class->image,
2121 "System", patch_info->data.target);
2122 g_assert (ex_class);
2123 encode_klass_ref (acfg, ex_class, p, &p);
2126 case MONO_PATCH_INFO_R4:
2127 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2129 case MONO_PATCH_INFO_R8:
2130 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2131 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2133 case MONO_PATCH_INFO_VTABLE:
2134 case MONO_PATCH_INFO_CLASS:
2135 case MONO_PATCH_INFO_IID:
2136 case MONO_PATCH_INFO_ADJUSTED_IID:
2137 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2139 case MONO_PATCH_INFO_CLASS_INIT:
2140 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2141 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2143 case MONO_PATCH_INFO_FIELD:
2144 case MONO_PATCH_INFO_SFLDA:
2145 encode_field_info (acfg, patch_info->data.field, p, &p);
2147 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2149 case MONO_PATCH_INFO_RGCTX_FETCH: {
2150 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2152 encode_method_ref (acfg, entry->method, p, &p);
2153 encode_value (entry->in_mrgctx, p, &p);
2154 encode_value (entry->info_type, p, &p);
2155 encode_value (entry->data->type, p, &p);
2156 encode_patch (acfg, entry->data, p, &p);
2159 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2160 case MONO_PATCH_INFO_MONITOR_ENTER:
2161 case MONO_PATCH_INFO_MONITOR_EXIT:
2164 g_warning ("unable to handle jump info %d", patch_info->type);
2165 g_assert_not_reached ();
2172 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2176 MonoJumpInfo *patch_info;
2178 encode_value (n_patches, p, &p);
2181 encode_value (first_got_offset, p, &p);
2183 for (pindex = 0; pindex < patches->len; ++pindex) {
2184 patch_info = g_ptr_array_index (patches, pindex);
2186 if (patch_info->type == MONO_PATCH_INFO_NONE)
2190 encode_value (patch_info->type, p, &p);
2191 if (mono_aot_is_shared_got_patch (patch_info)) {
2192 guint32 offset = get_got_offset (acfg, patch_info);
2193 encode_value (offset, p, &p);
2195 encode_patch (acfg, patch_info, p, &p);
2203 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2207 int pindex, buf_size, n_patches;
2211 MonoJumpInfo *patch_info;
2212 MonoMethodHeader *header;
2213 guint32 method_index;
2215 guint32 first_got_offset;
2217 method = cfg->orig_method;
2218 code = cfg->native_code;
2219 header = mono_method_get_header (method);
2221 method_index = get_method_index (acfg, method);
2223 /* Make the labels local */
2224 sprintf (symbol, ".Lm_%x_p", method_index);
2226 /* Sort relocations */
2227 patches = g_ptr_array_new ();
2228 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2229 g_ptr_array_add (patches, patch_info);
2230 g_ptr_array_sort (patches, compare_patches);
2232 first_got_offset = acfg->cfgs [method_index]->got_offset;
2234 /**********************/
2235 /* Encode method info */
2236 /**********************/
2238 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2239 p = buf = g_malloc (buf_size);
2241 if (mono_class_get_cctor (method->klass))
2242 encode_klass_ref (acfg, method->klass, p, &p);
2244 /* Not needed when loading the method */
2245 encode_value (0, p, &p);
2248 if (cfg->opt & MONO_OPT_SHARED) {
2249 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2250 for (l = cfg->ldstr_list; l; l = l->next) {
2251 encode_value ((long)l->data, p, &p);
2255 /* Used only in shared mode */
2256 g_assert (!cfg->ldstr_list);
2259 for (pindex = 0; pindex < patches->len; ++pindex) {
2260 patch_info = g_ptr_array_index (patches, pindex);
2262 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2263 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2264 patch_info->type = MONO_PATCH_INFO_NONE;
2269 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2270 /* Stored in a GOT slot initialized at module load time */
2271 patch_info->type = MONO_PATCH_INFO_NONE;
2275 if (is_plt_patch (patch_info)) {
2276 /* Calls are made through the PLT */
2277 patch_info->type = MONO_PATCH_INFO_NONE;
2285 g_assert (cfg->has_got_slots);
2287 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2289 acfg->stats.info_size += p - buf;
2291 /* Emit method info */
2293 emit_label (acfg, symbol);
2295 g_assert (p - buf < buf_size);
2296 emit_bytes (acfg, buf, p - buf);
2301 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2303 guint32 cache_index;
2306 /* Reuse the unwind module to canonize and store unwind info entries */
2307 cache_index = mono_cache_unwind_info (encoded, encoded_len);
2309 /* Use +/- 1 to distinguish 0s from missing entries */
2310 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2318 * It would be easier to use assembler symbols, but the caller needs an
2321 offset = acfg->unwind_info_offset;
2322 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2323 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2326 encode_value (encoded_len, p, &p);
2328 acfg->unwind_info_offset += encoded_len + (p - buf);
2334 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2337 int k, buf_size, method_index;
2338 guint32 debug_info_size;
2341 MonoMethodHeader *header;
2342 guint8 *p, *buf, *debug_info;
2343 MonoJitInfo *jinfo = cfg->jit_info;
2345 gboolean use_unwind_ops = FALSE;
2347 method = cfg->orig_method;
2348 code = cfg->native_code;
2349 header = mono_method_get_header (method);
2351 method_index = get_method_index (acfg, method);
2353 /* Make the labels local */
2354 sprintf (symbol, ".Le_%x_p", method_index);
2356 if (!acfg->aot_opts.nodebug) {
2357 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2360 debug_info_size = 0;
2363 buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2364 p = buf = g_malloc (buf_size);
2366 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2367 use_unwind_ops = cfg->unwind_ops != NULL;
2370 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2372 encode_value (jinfo->code_size, p, &p);
2373 encode_value (flags, p, &p);
2375 if (use_unwind_ops) {
2376 guint32 encoded_len;
2380 * This is a duplicate of the data in the .debug_frame section, but that
2381 * section cannot be accessed using the dl interface.
2383 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2384 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2387 encode_value (jinfo->used_regs, p, &p);
2390 /* Exception table */
2391 if (header->num_clauses) {
2392 for (k = 0; k < header->num_clauses; ++k) {
2393 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2395 encode_value (ei->exvar_offset, p, &p);
2397 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2398 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2400 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2401 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2402 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2406 if (jinfo->has_generic_jit_info) {
2407 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2409 encode_value (gi->has_this ? 1 : 0, p, &p);
2410 encode_value (gi->this_reg, p, &p);
2411 encode_value (gi->this_offset, p, &p);
2414 * Need to encode jinfo->method too, since it is not equal to 'method'
2415 * when using generic sharing.
2417 encode_method_ref (acfg, jinfo->method, p, &p);
2420 g_assert (debug_info_size < buf_size);
2422 encode_value (debug_info_size, p, &p);
2423 if (debug_info_size) {
2424 memcpy (p, debug_info, debug_info_size);
2425 p += debug_info_size;
2426 g_free (debug_info);
2429 acfg->stats.ex_info_size += p - buf;
2433 emit_label (acfg, symbol);
2435 g_assert (p - buf < buf_size);
2436 emit_bytes (acfg, buf, p - buf);
2441 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2443 MonoClass *klass = mono_class_get (acfg->image, token);
2447 gboolean no_special_static, cant_encode;
2448 gpointer iter = NULL;
2450 buf_size = 10240 + (klass->vtable_size * 16);
2451 p = buf = g_malloc (buf_size);
2455 mono_class_init (klass);
2457 mono_class_get_nested_types (klass, &iter);
2458 g_assert (klass->nested_classes_inited);
2460 mono_class_setup_vtable (klass);
2463 * Emit all the information which is required for creating vtables so
2464 * the runtime does not need to create the MonoMethod structures which
2465 * take up a lot of space.
2468 no_special_static = !mono_class_has_special_static_fields (klass);
2470 /* Check whenever we have enough info to encode the vtable */
2471 cant_encode = FALSE;
2472 for (i = 0; i < klass->vtable_size; ++i) {
2473 MonoMethod *cm = klass->vtable [i];
2475 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2479 if (klass->generic_container || cant_encode) {
2480 encode_value (-1, p, &p);
2482 encode_value (klass->vtable_size, p, &p);
2483 encode_value ((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);
2484 if (klass->has_cctor)
2485 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2486 if (klass->has_finalize)
2487 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2489 encode_value (klass->instance_size, p, &p);
2490 encode_value (mono_class_data_size (klass), p, &p);
2491 encode_value (klass->packing_size, p, &p);
2492 encode_value (klass->min_align, p, &p);
2494 for (i = 0; i < klass->vtable_size; ++i) {
2495 MonoMethod *cm = klass->vtable [i];
2498 encode_method_ref (acfg, cm, p, &p);
2500 encode_value (0, p, &p);
2504 acfg->stats.class_info_size += p - buf;
2507 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2508 emit_label (acfg, symbol);
2510 g_assert (p - buf < buf_size);
2511 emit_bytes (acfg, buf, p - buf);
2516 * Calls made from AOTed code are routed through a table of jumps similar to the
2517 * ELF PLT (Program Linkage Table). The differences are the following:
2518 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2519 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2520 * jumps. This means the jumps need to be patched when the address of the callee is
2521 * known. Initially the PLT entries jump to code which transfers control to the
2522 * AOT runtime through the first PLT entry.
2525 emit_plt (MonoAotCompile *acfg)
2531 sprintf (symbol, "plt");
2533 emit_section_change (acfg, ".text", 0);
2534 emit_global (acfg, symbol, TRUE);
2536 /* This section will be made read-write by the AOT loader */
2537 emit_alignment (acfg, mono_pagesize ());
2539 emit_alignment (acfg, 16);
2541 emit_label (acfg, symbol);
2543 for (i = 0; i < acfg->plt_offset; ++i) {
2546 sprintf (label, ".Lp_%d", i);
2547 emit_label (acfg, label);
2550 * The first plt entry is used to transfer code to the AOT loader.
2552 arch_emit_plt_entry (acfg, i);
2555 sprintf (symbol, "plt_end");
2556 emit_global (acfg, symbol, TRUE);
2557 emit_label (acfg, symbol);
2560 static G_GNUC_UNUSED void
2561 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
2562 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2566 MonoJumpInfo *patch_info;
2572 sprintf (symbol, "%s", name);
2574 emit_section_change (acfg, ".text", 0);
2575 emit_global (acfg, symbol, TRUE);
2576 emit_alignment (acfg, 16);
2577 emit_label (acfg, symbol);
2579 sprintf (symbol, ".Lnamed_%s", name);
2580 emit_label (acfg, symbol);
2583 * The code should access everything through the GOT, so we pass
2586 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2590 /* Sort relocations */
2591 patches = g_ptr_array_new ();
2592 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2593 g_ptr_array_add (patches, patch_info);
2594 g_ptr_array_sort (patches, compare_patches);
2596 buf_size = patches->len * 128 + 128;
2597 buf = g_malloc (buf_size);
2600 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2601 g_assert (p - buf < buf_size);
2603 sprintf (symbol, "%s_p", name);
2605 emit_section_change (acfg, ".text", 0);
2606 emit_global (acfg, symbol, FALSE);
2607 emit_label (acfg, symbol);
2609 emit_bytes (acfg, buf, p - buf);
2611 /* Emit debug info */
2615 sprintf (symbol, "%s", name);
2616 sprintf (symbol2, ".Lnamed_%s", name);
2619 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2624 emit_trampolines (MonoAotCompile *acfg)
2627 int i, tramp_got_offset;
2628 MonoAotTrampoline ntype;
2629 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2637 if (!acfg->aot_opts.full_aot)
2640 g_assert (acfg->image->assembly);
2642 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2643 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2644 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2646 * Emit the generic trampolines.
2648 * We could save some code by treating the generic trampolines as a wrapper
2649 * method, but that approach has its own complexities, so we choose the simpler
2652 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2653 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2655 /* Emit trampoline code */
2657 sprintf (symbol, "generic_trampoline_%d", tramp_type);
2659 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2662 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2663 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2664 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2665 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2666 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2667 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2668 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2671 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2672 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2674 /* Emit the exception related code pieces */
2675 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2676 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2677 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2678 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2679 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2680 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2681 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2682 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2683 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2684 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2685 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2686 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2688 #if defined(TARGET_AMD64)
2689 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2690 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2693 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2694 for (i = 0; i < 128; ++i) {
2697 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2698 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2699 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2700 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2702 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2703 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2704 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2705 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2709 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2713 /* delegate_invoke_impl trampolines */
2714 l = mono_arch_get_delegate_invoke_impls ();
2716 MonoAotTrampInfo *info = l->data;
2718 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
2724 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
2726 /* Emit trampolines which are numerous */
2729 * These include the following:
2730 * - specific trampolines
2731 * - static rgctx invoke trampolines
2733 * These trampolines have the same code, they are parameterized by GOT
2735 * They are defined in this file, in the arch_... routines instead of
2736 * in tramp-<ARCH>.c, since it is easier to do it this way.
2740 * When running in aot-only mode, we can't create specific trampolines at
2741 * runtime, so we create a few, and save them in the AOT file.
2742 * Normal trampolines embed their argument as a literal inside the
2743 * trampoline code, we can't do that here, so instead we embed an offset
2744 * which needs to be added to the trampoline address to get the address of
2745 * the GOT slot which contains the argument value.
2746 * The generated trampolines jump to the generic trampolines using another
2747 * GOT slot, which will be setup by the AOT loader to point to the
2748 * generic trampoline code of the given type.
2752 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2756 emit_section_change (acfg, ".text", 0);
2758 tramp_got_offset = acfg->got_offset;
2760 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
2762 case MONO_AOT_TRAMP_SPECIFIC:
2763 sprintf (symbol, "specific_trampolines");
2765 case MONO_AOT_TRAMP_STATIC_RGCTX:
2766 sprintf (symbol, "static_rgctx_trampolines");
2768 case MONO_AOT_TRAMP_IMT_THUNK:
2769 sprintf (symbol, "imt_thunks");
2772 g_assert_not_reached ();
2775 emit_global (acfg, symbol, TRUE);
2776 emit_alignment (acfg, 16);
2777 emit_label (acfg, symbol);
2779 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
2781 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
2785 case MONO_AOT_TRAMP_SPECIFIC:
2786 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
2787 tramp_got_offset += 2;
2789 case MONO_AOT_TRAMP_STATIC_RGCTX:
2790 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
2791 tramp_got_offset += 2;
2793 case MONO_AOT_TRAMP_IMT_THUNK:
2794 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
2795 tramp_got_offset += 1;
2798 g_assert_not_reached ();
2801 if (!acfg->trampoline_size [ntype]) {
2802 g_assert (tramp_size);
2803 acfg->trampoline_size [ntype] = tramp_size;
2808 /* Reserve some entries at the end of the GOT for our use */
2809 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
2812 /* Unbox trampolines */
2813 for (i = 0; i < acfg->methods->len; ++i) {
2814 MonoMethod *method = g_ptr_array_index (acfg->methods, i);
2816 char call_target [256];
2818 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2819 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2822 if (!method->wrapper_type && !method->is_inflated) {
2823 g_assert (method->token);
2824 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2826 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2829 emit_section_change (acfg, ".text", 0);
2830 emit_global (acfg, symbol, TRUE);
2831 emit_label (acfg, symbol);
2833 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2835 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2838 acfg->got_offset += acfg->num_trampoline_got_entries;
2842 str_begins_with (const char *str1, const char *str2)
2844 int len = strlen (str2);
2845 return strncmp (str1, str2, len) == 0;
2849 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2851 gchar **args, **ptr;
2853 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2854 for (ptr = args; ptr && *ptr; ptr ++) {
2855 const char *arg = *ptr;
2857 if (str_begins_with (arg, "outfile=")) {
2858 opts->outfile = g_strdup (arg + strlen ("outfile="));
2859 } else if (str_begins_with (arg, "save-temps")) {
2860 opts->save_temps = TRUE;
2861 } else if (str_begins_with (arg, "keep-temps")) {
2862 opts->save_temps = TRUE;
2863 } else if (str_begins_with (arg, "write-symbols")) {
2864 opts->write_symbols = TRUE;
2865 } else if (str_begins_with (arg, "metadata-only")) {
2866 opts->metadata_only = TRUE;
2867 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2868 opts->bind_to_runtime_version = TRUE;
2869 } else if (str_begins_with (arg, "full")) {
2870 opts->full_aot = TRUE;
2871 } else if (str_begins_with (arg, "threads=")) {
2872 opts->nthreads = atoi (arg + strlen ("threads="));
2873 } else if (str_begins_with (arg, "static")) {
2874 opts->static_link = TRUE;
2875 opts->no_dlsym = TRUE;
2876 } else if (str_begins_with (arg, "asmonly")) {
2877 opts->asm_only = TRUE;
2878 } else if (str_begins_with (arg, "asmwriter")) {
2879 opts->asm_writer = TRUE;
2880 } else if (str_begins_with (arg, "nodebug")) {
2881 opts->nodebug = TRUE;
2882 } else if (str_begins_with (arg, "ntrampolines=")) {
2883 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
2885 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2894 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2896 MonoMethod *method = (MonoMethod*)key;
2897 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2898 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2899 MonoAotCompile *acfg = user_data;
2901 new_ji->image = ji->image;
2902 new_ji->token = ji->token;
2903 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2907 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2909 if (klass->type_token)
2911 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2914 return can_encode_class (acfg, klass->element_class);
2919 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2921 switch (patch_info->type) {
2922 case MONO_PATCH_INFO_METHOD:
2923 case MONO_PATCH_INFO_METHODCONST: {
2924 MonoMethod *method = patch_info->data.method;
2926 if (method->wrapper_type) {
2927 switch (method->wrapper_type) {
2928 case MONO_WRAPPER_NONE:
2929 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2930 case MONO_WRAPPER_XDOMAIN_INVOKE:
2931 case MONO_WRAPPER_STFLD:
2932 case MONO_WRAPPER_LDFLD:
2933 case MONO_WRAPPER_LDFLDA:
2934 case MONO_WRAPPER_LDFLD_REMOTE:
2935 case MONO_WRAPPER_STFLD_REMOTE:
2936 case MONO_WRAPPER_STELEMREF:
2937 case MONO_WRAPPER_ISINST:
2938 case MONO_WRAPPER_PROXY_ISINST:
2939 case MONO_WRAPPER_ALLOC:
2940 case MONO_WRAPPER_REMOTING_INVOKE:
2941 case MONO_WRAPPER_UNKNOWN:
2943 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
2944 g_assert (!acfg->aot_opts.full_aot);
2947 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2951 if (!method->token) {
2952 /* The method is part of a constructed type like Int[,].Set (). */
2953 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2954 if (method->klass->rank)
2962 case MONO_PATCH_INFO_VTABLE:
2963 case MONO_PATCH_INFO_CLASS_INIT:
2964 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2965 case MONO_PATCH_INFO_CLASS:
2966 case MONO_PATCH_INFO_IID:
2967 case MONO_PATCH_INFO_ADJUSTED_IID:
2968 if (!can_encode_class (acfg, patch_info->data.klass)) {
2969 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
2973 case MONO_PATCH_INFO_RGCTX_FETCH: {
2974 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2976 if (!can_encode_patch (acfg, entry->data))
2988 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
2993 * AOT compile a given method.
2994 * This function might be called by multiple threads, so it must be thread-safe.
2997 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3000 MonoJumpInfo *patch_info;
3003 MonoMethod *wrapped;
3005 if (acfg->aot_opts.metadata_only)
3008 mono_acfg_lock (acfg);
3009 index = get_method_index (acfg, method);
3010 mono_acfg_unlock (acfg);
3012 /* fixme: maybe we can also precompile wrapper methods */
3013 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3014 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3015 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3016 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3020 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3023 wrapped = mono_marshal_method_from_wrapper (method);
3024 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3025 // FIXME: The wrapper should be generic too, but it is not
3028 InterlockedIncrement (&acfg->stats.mcount);
3031 if (method->is_generic || method->klass->generic_container) {
3032 InterlockedIncrement (&acfg->stats.genericcount);
3037 //acfg->aot_opts.print_skipped_methods = TRUE;
3040 * Since these methods are the only ones which are compiled with
3041 * AOT support, and they are not used by runtime startup/shutdown code,
3042 * the runtime will not see AOT methods during AOT compilation,so it
3043 * does not need to support them by creating a fake GOT etc.
3045 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3046 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3047 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3048 InterlockedIncrement (&acfg->stats.genericcount);
3051 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3052 /* Let the exception happen at runtime */
3056 if (cfg->disable_aot) {
3057 if (acfg->aot_opts.print_skipped_methods)
3058 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3059 InterlockedIncrement (&acfg->stats.ocount);
3060 mono_destroy_compile (cfg);
3064 /* Nullify patches which need no aot processing */
3065 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3066 switch (patch_info->type) {
3067 case MONO_PATCH_INFO_LABEL:
3068 case MONO_PATCH_INFO_BB:
3069 patch_info->type = MONO_PATCH_INFO_NONE;
3076 /* Collect method->token associations from the cfg */
3077 mono_acfg_lock (acfg);
3078 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3079 mono_acfg_unlock (acfg);
3082 * Check for absolute addresses.
3085 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3086 switch (patch_info->type) {
3087 case MONO_PATCH_INFO_ABS:
3088 /* unable to handle this */
3097 if (acfg->aot_opts.print_skipped_methods)
3098 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3099 InterlockedIncrement (&acfg->stats.abscount);
3100 mono_destroy_compile (cfg);
3104 /* Lock for the rest of the code */
3105 mono_acfg_lock (acfg);
3108 * Check for methods/klasses we can't encode.
3111 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3112 if (!can_encode_patch (acfg, patch_info))
3117 if (acfg->aot_opts.print_skipped_methods)
3118 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3119 acfg->stats.ocount++;
3120 mono_destroy_compile (cfg);
3121 mono_acfg_unlock (acfg);
3125 /* Adds generic instances referenced by this method */
3126 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3127 switch (patch_info->type) {
3128 case MONO_PATCH_INFO_METHOD: {
3129 MonoMethod *m = patch_info->data.method;
3130 if (m->is_inflated) {
3131 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3132 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3133 !method_has_type_vars (m)) {
3134 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3135 if (acfg->aot_opts.full_aot)
3136 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3138 add_extra_method (acfg, m);
3141 add_generic_class (acfg, m->klass);
3150 /* Determine whenever the method has GOT slots */
3151 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3152 switch (patch_info->type) {
3153 case MONO_PATCH_INFO_GOT_OFFSET:
3154 case MONO_PATCH_INFO_NONE:
3156 case MONO_PATCH_INFO_IMAGE:
3157 /* The assembly is stored in GOT slot 0 */
3158 if (patch_info->data.image != acfg->image)
3159 cfg->has_got_slots = TRUE;
3162 if (!is_plt_patch (patch_info))
3163 cfg->has_got_slots = TRUE;
3168 if (!cfg->has_got_slots)
3169 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3171 /* Make a copy of the patch info which is in the mempool */
3173 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3175 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3176 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3179 patches = new_patch_info;
3181 patches_end->next = new_patch_info;
3182 patches_end = new_patch_info;
3184 cfg->patch_info = patches;
3186 /* Make a copy of the unwind info */
3188 GSList *l, *unwind_ops;
3192 for (l = cfg->unwind_ops; l; l = l->next) {
3193 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3194 memcpy (op, l->data, sizeof (MonoUnwindOp));
3195 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3197 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3199 /* Make a copy of the argument/local info */
3201 MonoInst **args, **locals;
3202 MonoMethodSignature *sig;
3203 MonoMethodHeader *header;
3206 sig = mono_method_signature (method);
3207 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3208 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3209 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3210 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3214 header = mono_method_get_header (method);
3215 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3216 for (i = 0; i < header->num_locals; ++i) {
3217 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3218 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3220 cfg->locals = locals;
3223 /* Free some fields used by cfg to conserve memory */
3224 mono_mempool_destroy (cfg->mempool);
3225 cfg->mempool = NULL;
3226 g_free (cfg->varinfo);
3227 cfg->varinfo = NULL;
3231 mono_regstate_free (cfg->rs);
3235 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3237 while (index >= acfg->cfgs_size) {
3238 MonoCompile **new_cfgs;
3241 new_size = acfg->cfgs_size * 2;
3242 new_cfgs = g_new0 (MonoCompile*, new_size);
3243 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3244 g_free (acfg->cfgs);
3245 acfg->cfgs = new_cfgs;
3246 acfg->cfgs_size = new_size;
3248 acfg->cfgs [index] = cfg;
3250 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3252 if (cfg->orig_method->wrapper_type)
3253 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3255 mono_acfg_unlock (acfg);
3257 InterlockedIncrement (&acfg->stats.ccount);
3261 compile_thread_main (gpointer *user_data)
3263 MonoDomain *domain = user_data [0];
3264 MonoAotCompile *acfg = user_data [1];
3265 GPtrArray *methods = user_data [2];
3268 mono_thread_attach (domain);
3270 for (i = 0; i < methods->len; ++i)
3271 compile_method (acfg, g_ptr_array_index (methods, i));
3275 load_profile_files (MonoAotCompile *acfg)
3279 int file_index, res, method_index, i;
3286 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
3288 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3293 infile = fopen (tmp, "r");
3296 printf ("Using profile data file '%s'\n", tmp);
3301 res = fscanf (infile, "%32s\n", ver);
3302 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3303 printf ("Profile file has wrong version or invalid.\n");
3309 res = fscanf (infile, "%d\n", &token);
3313 method_index = mono_metadata_token_index (token) - 1;
3315 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3316 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3321 /* Add missing methods */
3323 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3324 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3325 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3327 unordered = g_list_reverse (unordered);
3328 if (acfg->method_order)
3329 g_list_last (acfg->method_order)->next = unordered;
3331 acfg->method_order = unordered;
3337 * Collect all patches which have shared GOT entries and alloc entries for them. The
3338 * rest will get entries allocated during emit_code ().
3341 alloc_got_slots (MonoAotCompile *acfg)
3347 /* Slot 0 is reserved for the address of the current assembly */
3348 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3349 ji->type = MONO_PATCH_INFO_IMAGE;
3350 ji->data.image = acfg->image;
3352 get_shared_got_offset (acfg, ji);
3354 for (l = acfg->method_order; l != NULL; l = l->next) {
3355 i = GPOINTER_TO_UINT (l->data);
3357 if (acfg->cfgs [i]) {
3358 MonoCompile *cfg = acfg->cfgs [i];
3360 for (ji = cfg->patch_info; ji; ji = ji->next) {
3361 if (mono_aot_is_shared_got_patch (ji))
3362 get_shared_got_offset (acfg, ji);
3369 emit_code (MonoAotCompile *acfg)
3375 sprintf (symbol, "methods");
3376 emit_section_change (acfg, ".text", 0);
3377 emit_global (acfg, symbol, TRUE);
3378 emit_alignment (acfg, 8);
3379 emit_label (acfg, symbol);
3382 * Emit some padding so the local symbol for the first method doesn't have the
3383 * same address as 'methods'.
3385 emit_zero_bytes (acfg, 16);
3387 for (l = acfg->method_order; l != NULL; l = l->next) {
3388 i = GPOINTER_TO_UINT (l->data);
3391 emit_method_code (acfg, acfg->cfgs [i]);
3394 sprintf (symbol, "methods_end");
3395 emit_section_change (acfg, ".text", 0);
3396 emit_global (acfg, symbol, FALSE);
3397 emit_alignment (acfg, 8);
3398 emit_label (acfg, symbol);
3400 sprintf (symbol, "method_offsets");
3401 emit_section_change (acfg, ".text", 1);
3402 emit_global (acfg, symbol, FALSE);
3403 emit_alignment (acfg, 8);
3404 emit_label (acfg, symbol);
3406 for (i = 0; i < acfg->nmethods; ++i) {
3407 if (acfg->cfgs [i]) {
3408 sprintf (symbol, ".Lm_%x", i);
3409 emit_symbol_diff (acfg, symbol, "methods", 0);
3411 emit_int32 (acfg, 0xffffffff);
3418 emit_info (MonoAotCompile *acfg)
3424 /* Emit method info */
3425 sprintf (symbol, "method_info");
3426 emit_section_change (acfg, ".text", 1);
3427 emit_global (acfg, symbol, FALSE);
3428 emit_alignment (acfg, 8);
3429 emit_label (acfg, symbol);
3431 /* To reduce size of generated assembly code */
3432 sprintf (symbol, "mi");
3433 emit_label (acfg, symbol);
3435 for (l = acfg->method_order; l != NULL; l = l->next) {
3436 i = GPOINTER_TO_UINT (l->data);
3439 emit_method_info (acfg, acfg->cfgs [i]);
3442 sprintf (symbol, "method_info_offsets");
3443 emit_section_change (acfg, ".text", 1);
3444 emit_global (acfg, symbol, FALSE);
3445 emit_alignment (acfg, 8);
3446 emit_label (acfg, symbol);
3448 for (i = 0; i < acfg->nmethods; ++i) {
3449 if (acfg->cfgs [i]) {
3450 sprintf (symbol, ".Lm_%x_p", i);
3451 emit_symbol_diff (acfg, symbol, "mi", 0);
3453 emit_int32 (acfg, 0);
3459 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
3462 * mono_aot_str_hash:
3464 * Hash function for strings which we use to hash strings for things which are
3465 * saved in the AOT image, since g_str_hash () can change.
3468 mono_aot_str_hash (gconstpointer v1)
3470 /* Same as g_str_hash () in glib */
3471 char *p = (char *) v1;
3476 hash = (hash << 5) - hash + *p;
3482 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
3483 #define mix(a,b,c) { \
3484 a -= c; a ^= rot(c, 4); c += b; \
3485 b -= a; b ^= rot(a, 6); a += c; \
3486 c -= b; c ^= rot(b, 8); b += a; \
3487 a -= c; a ^= rot(c,16); c += b; \
3488 b -= a; b ^= rot(a,19); a += c; \
3489 c -= b; c ^= rot(b, 4); b += a; \
3491 #define final(a,b,c) { \
3492 c ^= b; c -= rot(b,14); \
3493 a ^= c; a -= rot(c,11); \
3494 b ^= a; b -= rot(a,25); \
3495 c ^= b; c -= rot(b,16); \
3496 a ^= c; a -= rot(c,4); \
3497 b ^= a; b -= rot(a,14); \
3498 c ^= b; c -= rot(b,24); \
3502 mono_aot_type_hash (MonoType *t1)
3504 guint hash = t1->type;
3506 hash |= t1->byref << 6; /* do not collide with t1->type values */
3508 case MONO_TYPE_VALUETYPE:
3509 case MONO_TYPE_CLASS:
3510 case MONO_TYPE_SZARRAY:
3511 /* check if the distribution is good enough */
3512 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
3514 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
3515 case MONO_TYPE_ARRAY:
3516 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
3517 case MONO_TYPE_GENERICINST:
3518 return ((hash << 5) - hash) ^ 0;
3524 * mono_aot_method_hash:
3526 * Return a hash code for methods which only depends on metadata.
3529 mono_aot_method_hash (MonoMethod *method)
3531 MonoMethodSignature *sig;
3535 guint32 *hashes_start, *hashes;
3538 /* Similar to the hash in mono_method_get_imt_slot () */
3540 sig = mono_method_signature (method);
3542 hashes_count = sig->param_count + 5;
3543 hashes_start = malloc (hashes_count * sizeof (guint32));
3544 hashes = hashes_start;
3546 /* Some wrappers are assigned to random classes */
3547 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3548 klass = method->klass;
3550 klass = mono_defaults.object_class;
3552 if (!method->wrapper_type) {
3553 char *full_name = mono_type_full_name (&klass->byval_arg);
3555 hashes [0] = mono_aot_str_hash (full_name);
3559 hashes [0] = mono_aot_str_hash (klass->name);
3560 hashes [1] = mono_aot_str_hash (klass->name_space);
3562 hashes [2] = mono_aot_str_hash (method->name);
3563 hashes [3] = method->wrapper_type;
3564 hashes [4] = mono_aot_type_hash (sig->ret);
3565 for (i = 0; i < sig->param_count; i++) {
3566 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
3569 /* Setup internal state */
3570 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
3572 /* Handle most of the hashes */
3573 while (hashes_count > 3) {
3582 /* Handle the last 3 hashes (all the case statements fall through) */
3583 switch (hashes_count) {
3584 case 3 : c += hashes [2];
3585 case 2 : b += hashes [1];
3586 case 1 : a += hashes [0];
3588 case 0: /* nothing left to add */
3592 free (hashes_start);
3601 * mono_aot_wrapper_name:
3603 * Return a string which uniqely identifies the given wrapper method.
3606 mono_aot_wrapper_name (MonoMethod *method)
3608 char *name, *tmpsig, *klass_desc;
3610 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3612 switch (method->wrapper_type) {
3613 case MONO_WRAPPER_RUNTIME_INVOKE:
3614 case MONO_WRAPPER_DELEGATE_INVOKE:
3615 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3616 case MONO_WRAPPER_DELEGATE_END_INVOKE:
3617 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
3618 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
3621 klass_desc = mono_type_full_name (&method->klass->byval_arg);
3623 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
3633 * mono_aot_tramp_info_create:
3635 * Create a MonoAotTrampInfo structure from the arguments.
3638 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
3640 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
3642 info->name = (char*)name;
3644 info->code_size = code_size;
3650 * mono_is_shared_got_patch:
3652 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
3656 mono_aot_is_shared_got_patch (MonoJumpInfo *patch_info)
3658 switch (patch_info->type) {
3659 case MONO_PATCH_INFO_VTABLE:
3660 case MONO_PATCH_INFO_CLASS:
3661 case MONO_PATCH_INFO_IID:
3662 case MONO_PATCH_INFO_ADJUSTED_IID:
3663 case MONO_PATCH_INFO_FIELD:
3664 case MONO_PATCH_INFO_SFLDA:
3665 case MONO_PATCH_INFO_DECLSEC:
3666 case MONO_PATCH_INFO_LDTOKEN:
3667 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3668 case MONO_PATCH_INFO_RVA:
3669 case MONO_PATCH_INFO_METHODCONST:
3670 case MONO_PATCH_INFO_IMAGE:
3677 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
3679 typedef struct HashEntry {
3680 guint32 key, value, index;
3681 struct HashEntry *next;
3685 * emit_extra_methods:
3687 * Emit methods which are not in the METHOD table, like wrappers.
3690 emit_extra_methods (MonoAotCompile *acfg)
3692 int i, table_size, buf_size;
3695 guint32 *info_offsets;
3698 HashEntry *entry, *new_entry;
3699 int nmethods, max_chain_length;
3702 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3704 buf_size = acfg->extra_methods->len * 256 + 256;
3705 p = buf = g_malloc (buf_size);
3707 /* Encode method info */
3709 /* So offsets are > 0 */
3712 for (i = 0; i < acfg->extra_methods->len; ++i) {
3713 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3714 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3721 info_offsets [i] = p - buf;
3724 if (method->wrapper_type) {
3726 * We encode some wrappers using their name, since encoding them
3727 * directly would be difficult. This also avoids creating the wrapper
3728 * methods at runtime, since they are not needed anyway.
3730 switch (method->wrapper_type) {
3731 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3732 case MONO_WRAPPER_SYNCHRONIZED:
3733 /* encode_method_ref () can handle these */
3736 name = mono_aot_wrapper_name (method);
3742 encode_value (1, p, &p);
3743 encode_value (method->wrapper_type, p, &p);
3744 strcpy ((char*)p, name);
3745 p += strlen (name ) + 1;
3748 encode_value (0, p, &p);
3749 encode_method_ref (acfg, method, p, &p);
3752 g_assert ((p - buf) < buf_size);
3755 g_assert ((p - buf) < buf_size);
3757 /* Emit method info */
3758 sprintf (symbol, "extra_method_info");
3759 emit_section_change (acfg, ".text", 1);
3760 emit_global (acfg, symbol, FALSE);
3761 emit_alignment (acfg, 8);
3762 emit_label (acfg, symbol);
3764 emit_bytes (acfg, buf, p - buf);
3769 * Construct a chained hash table for mapping indexes in extra_method_info to
3772 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3773 table = g_ptr_array_sized_new (table_size);
3774 for (i = 0; i < table_size; ++i)
3775 g_ptr_array_add (table, NULL);
3776 chain_lengths = g_new0 (int, table_size);
3777 max_chain_length = 0;
3778 for (i = 0; i < acfg->extra_methods->len; ++i) {
3779 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3780 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3786 key = info_offsets [i];
3787 value = get_method_index (acfg, method);
3789 hash = mono_aot_method_hash (method) % table_size;
3791 chain_lengths [hash] ++;
3792 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3794 /* FIXME: Allocate from the mempool */
3795 new_entry = g_new0 (HashEntry, 1);
3796 new_entry->key = key;
3797 new_entry->value = value;
3799 entry = g_ptr_array_index (table, hash);
3800 if (entry == NULL) {
3801 new_entry->index = hash;
3802 g_ptr_array_index (table, hash) = new_entry;
3805 entry = entry->next;
3807 entry->next = new_entry;
3808 new_entry->index = table->len;
3809 g_ptr_array_add (table, new_entry);
3813 //printf ("MAX: %d\n", max_chain_length);
3815 /* Emit the table */
3816 sprintf (symbol, "extra_method_table");
3817 emit_section_change (acfg, ".text", 0);
3818 emit_global (acfg, symbol, FALSE);
3819 emit_alignment (acfg, 8);
3820 emit_label (acfg, symbol);
3822 g_assert (table_size < 65000);
3823 emit_int32 (acfg, table_size);
3824 g_assert (table->len < 65000);
3825 for (i = 0; i < table->len; ++i) {
3826 HashEntry *entry = g_ptr_array_index (table, i);
3828 if (entry == NULL) {
3829 emit_int32 (acfg, 0);
3830 emit_int32 (acfg, 0);
3831 emit_int32 (acfg, 0);
3833 g_assert (entry->key > 0);
3834 emit_int32 (acfg, entry->key);
3835 emit_int32 (acfg, entry->value);
3837 emit_int32 (acfg, entry->next->index);
3839 emit_int32 (acfg, 0);
3844 * Emit a table reverse mapping method indexes to their index in extra_method_info.
3845 * This is used by mono_aot_find_jit_info ().
3847 sprintf (symbol, "extra_method_info_offsets");
3848 emit_section_change (acfg, ".text", 0);
3849 emit_global (acfg, symbol, FALSE);
3850 emit_alignment (acfg, 8);
3851 emit_label (acfg, symbol);
3853 emit_int32 (acfg, acfg->extra_methods->len);
3854 for (i = 0; i < acfg->extra_methods->len; ++i) {
3855 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3857 emit_int32 (acfg, get_method_index (acfg, method));
3858 emit_int32 (acfg, info_offsets [i]);
3863 emit_method_order (MonoAotCompile *acfg)
3869 sprintf (symbol, "method_order");
3870 emit_section_change (acfg, ".text", 1);
3871 emit_global (acfg, symbol, FALSE);
3872 emit_alignment (acfg, 8);
3873 emit_label (acfg, symbol);
3875 /* First emit an index table */
3878 for (l = acfg->method_order; l != NULL; l = l->next) {
3879 i = GPOINTER_TO_UINT (l->data);
3881 if (acfg->cfgs [i]) {
3882 if ((index % 1024) == 0) {
3883 emit_int32 (acfg, i);
3891 emit_int32 (acfg, 0xffffff);
3893 /* Then emit the whole method order */
3894 for (l = acfg->method_order; l != NULL; l = l->next) {
3895 i = GPOINTER_TO_UINT (l->data);
3897 if (acfg->cfgs [i]) {
3898 emit_int32 (acfg, i);
3903 sprintf (symbol, "method_order_end");
3904 emit_section_change (acfg, ".text", 1);
3905 emit_global (acfg, symbol, FALSE);
3906 emit_label (acfg, symbol);
3910 emit_exception_info (MonoAotCompile *acfg)
3915 sprintf (symbol, "ex_info");
3916 emit_section_change (acfg, ".text", 1);
3917 emit_global (acfg, symbol, FALSE);
3918 emit_alignment (acfg, 8);
3919 emit_label (acfg, symbol);
3921 /* To reduce size of generated assembly */
3922 sprintf (symbol, "ex");
3923 emit_label (acfg, symbol);
3925 for (i = 0; i < acfg->nmethods; ++i) {
3927 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3930 sprintf (symbol, "ex_info_offsets");
3931 emit_section_change (acfg, ".text", 1);
3932 emit_global (acfg, symbol, FALSE);
3933 emit_alignment (acfg, 8);
3934 emit_label (acfg, symbol);
3936 for (i = 0; i < acfg->nmethods; ++i) {
3937 if (acfg->cfgs [i]) {
3938 sprintf (symbol, ".Le_%x_p", i);
3939 emit_symbol_diff (acfg, symbol, "ex", 0);
3941 emit_int32 (acfg, 0);
3948 emit_unwind_info (MonoAotCompile *acfg)
3954 * The unwind info contains a lot of duplicates so we emit each unique
3955 * entry once, and only store the offset from the start of the table in the
3959 sprintf (symbol, "unwind_info");
3960 emit_section_change (acfg, ".text", 1);
3961 emit_alignment (acfg, 8);
3962 emit_label (acfg, symbol);
3963 emit_global (acfg, symbol, FALSE);
3965 for (i = 0; i < acfg->unwind_ops->len; ++i) {
3966 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
3967 guint8 *unwind_info;
3968 guint32 unwind_info_len;
3972 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
3975 encode_value (unwind_info_len, p, &p);
3976 emit_bytes (acfg, buf, p - buf);
3977 emit_bytes (acfg, unwind_info, unwind_info_len);
3979 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
3984 emit_class_info (MonoAotCompile *acfg)
3989 sprintf (symbol, "class_info");
3990 emit_section_change (acfg, ".text", 1);
3991 emit_global (acfg, symbol, FALSE);
3992 emit_alignment (acfg, 8);
3993 emit_label (acfg, symbol);
3995 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3996 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3998 sprintf (symbol, "class_info_offsets");
3999 emit_section_change (acfg, ".text", 1);
4000 emit_global (acfg, symbol, FALSE);
4001 emit_alignment (acfg, 8);
4002 emit_label (acfg, symbol);
4004 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4005 sprintf (symbol, ".LK_I_%x", i);
4006 emit_symbol_diff (acfg, symbol, "class_info", 0);
4011 typedef struct ClassNameTableEntry {
4012 guint32 token, index;
4013 struct ClassNameTableEntry *next;
4014 } ClassNameTableEntry;
4017 emit_class_name_table (MonoAotCompile *acfg)
4020 guint32 token, hash;
4025 ClassNameTableEntry *entry, *new_entry;
4028 * Construct a chained hash table for mapping class names to typedef tokens.
4030 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4031 table = g_ptr_array_sized_new (table_size);
4032 for (i = 0; i < table_size; ++i)
4033 g_ptr_array_add (table, NULL);
4034 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4035 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4036 klass = mono_class_get (acfg->image, token);
4037 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4038 hash = mono_aot_str_hash (full_name) % table_size;
4041 /* FIXME: Allocate from the mempool */
4042 new_entry = g_new0 (ClassNameTableEntry, 1);
4043 new_entry->token = token;
4045 entry = g_ptr_array_index (table, hash);
4046 if (entry == NULL) {
4047 new_entry->index = hash;
4048 g_ptr_array_index (table, hash) = new_entry;
4051 entry = entry->next;
4053 entry->next = new_entry;
4054 new_entry->index = table->len;
4055 g_ptr_array_add (table, new_entry);
4059 /* Emit the table */
4060 sprintf (symbol, "class_name_table");
4061 emit_section_change (acfg, ".text", 0);
4062 emit_global (acfg, symbol, FALSE);
4063 emit_alignment (acfg, 8);
4064 emit_label (acfg, symbol);
4066 /* FIXME: Optimize memory usage */
4067 g_assert (table_size < 65000);
4068 emit_int16 (acfg, table_size);
4069 g_assert (table->len < 65000);
4070 for (i = 0; i < table->len; ++i) {
4071 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4073 if (entry == NULL) {
4074 emit_int16 (acfg, 0);
4075 emit_int16 (acfg, 0);
4077 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4079 emit_int16 (acfg, entry->next->index);
4081 emit_int16 (acfg, 0);
4087 emit_image_table (MonoAotCompile *acfg)
4093 * The image table is small but referenced in a lot of places.
4094 * So we emit it at once, and reference its elements by an index.
4097 sprintf (symbol, "mono_image_table");
4098 emit_section_change (acfg, ".text", 1);
4099 emit_global (acfg, symbol, FALSE);
4100 emit_alignment (acfg, 8);
4101 emit_label (acfg, symbol);
4103 emit_int32 (acfg, acfg->image_table->len);
4104 for (i = 0; i < acfg->image_table->len; i++) {
4105 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4106 MonoAssemblyName *aname = &image->assembly->aname;
4108 /* FIXME: Support multi-module assemblies */
4109 g_assert (image->assembly->image == image);
4111 emit_string (acfg, image->assembly_name);
4112 emit_string (acfg, image->guid);
4113 emit_string (acfg, aname->culture ? aname->culture : "");
4114 emit_string (acfg, (const char*)aname->public_key_token);
4116 emit_alignment (acfg, 8);
4117 emit_int32 (acfg, aname->flags);
4118 emit_int32 (acfg, aname->major);
4119 emit_int32 (acfg, aname->minor);
4120 emit_int32 (acfg, aname->build);
4121 emit_int32 (acfg, aname->revision);
4126 emit_got_info (MonoAotCompile *acfg)
4129 int i, first_plt_got_patch, buf_size;
4131 guint32 *got_info_offsets;
4133 /* Add the patches needed by the PLT to the GOT */
4134 acfg->plt_got_offset_base = acfg->got_offset;
4135 first_plt_got_patch = acfg->shared_patches->len;
4136 for (i = 1; i < acfg->plt_offset; ++i) {
4137 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4139 g_ptr_array_add (acfg->shared_patches, patch_info);
4142 acfg->got_offset += acfg->plt_offset;
4146 * - optimize offsets table.
4147 * - reduce number of exported symbols.
4148 * - emit info for a klass only once.
4149 * - determine when a method uses a GOT slot which is guaranteed to be already
4151 * - clean up and document the code.
4152 * - use String.Empty in class libs.
4155 /* Encode info required to decode shared GOT entries */
4156 buf_size = acfg->shared_patches->len * 64;
4157 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4158 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4159 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4160 for (i = 0; i < acfg->shared_patches->len; ++i) {
4161 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4163 got_info_offsets [i] = p - buf;
4164 /* No need to encode the patch type for non-PLT patches */
4165 if (i >= first_plt_got_patch) {
4166 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4167 encode_value (ji->type, p, &p);
4169 encode_patch (acfg, ji, p, &p);
4172 g_assert (p - buf <= buf_size);
4174 acfg->stats.got_info_size = p - buf;
4176 /* Emit got_info table */
4177 sprintf (symbol, "got_info");
4178 emit_section_change (acfg, ".text", 1);
4179 emit_global (acfg, symbol, FALSE);
4180 emit_alignment (acfg, 8);
4181 emit_label (acfg, symbol);
4183 emit_bytes (acfg, buf, p - buf);
4185 /* Emit got_info_offsets table */
4186 sprintf (symbol, "got_info_offsets");
4187 emit_section_change (acfg, ".text", 1);
4188 emit_global (acfg, symbol, FALSE);
4189 emit_alignment (acfg, 8);
4190 emit_label (acfg, symbol);
4192 for (i = 0; i < acfg->shared_patches->len; ++i)
4193 emit_int32 (acfg, got_info_offsets [i]);
4195 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4199 emit_got (MonoAotCompile *acfg)
4203 /* Don't make GOT global so accesses to it don't need relocations */
4204 sprintf (symbol, acfg->got_symbol);
4205 emit_section_change (acfg, ".bss", 0);
4206 emit_alignment (acfg, 8);
4207 emit_local_symbol (acfg, symbol, "got_end", FALSE);
4208 emit_label (acfg, symbol);
4209 if (acfg->got_offset > 0)
4210 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4212 sprintf (symbol, "got_end");
4213 emit_label (acfg, symbol);
4215 sprintf (symbol, "mono_aot_got_addr");
4216 emit_section_change (acfg, ".data", 0);
4217 emit_global (acfg, symbol, FALSE);
4218 emit_alignment (acfg, 8);
4219 emit_label (acfg, symbol);
4220 emit_pointer (acfg, acfg->got_symbol);
4224 emit_globals (MonoAotCompile *acfg)
4229 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4231 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4233 opts_str = g_strdup_printf ("%d", acfg->opts);
4234 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4237 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4239 if (acfg->aot_opts.bind_to_runtime_version) {
4240 build_info = mono_get_runtime_build_info ();
4241 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4242 g_free (build_info);
4244 emit_string_symbol (acfg, "mono_runtime_version", "");
4248 * When static linking, we emit a global which will point to the symbol table.
4250 if (acfg->aot_opts.static_link) {
4255 /* Emit a string holding the assembly name */
4256 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4258 /* Emit the names */
4259 for (i = 0; i < acfg->globals->len; ++i) {
4260 char *name = g_ptr_array_index (acfg->globals, i);
4262 sprintf (symbol, "name_%d", i);
4263 emit_section_change (acfg, ".text", 1);
4264 emit_label (acfg, symbol);
4265 emit_string (acfg, name);
4268 /* Emit the globals table */
4269 sprintf (symbol, "globals");
4270 emit_section_change (acfg, ".data", 0);
4271 /* This is not a global, since it is accessed by the init function */
4272 emit_alignment (acfg, 8);
4273 emit_label (acfg, symbol);
4275 for (i = 0; i < acfg->globals->len; ++i) {
4276 char *name = g_ptr_array_index (acfg->globals, i);
4278 sprintf (symbol, "name_%d", i);
4279 emit_pointer (acfg, symbol);
4281 sprintf (symbol, "%s", name);
4282 emit_pointer (acfg, symbol);
4284 /* Null terminate the table */
4285 emit_int32 (acfg, 0);
4286 emit_int32 (acfg, 0);
4289 * Emit a global symbol which can be passed by an embedding app to
4290 * mono_aot_register_module ().
4292 #if defined(__MACH__)
4293 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4295 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4298 /* Get rid of characters which cannot occur in symbols */
4300 for (p = symbol; *p; ++p) {
4301 if (!(isalnum (*p) || *p == '_'))
4304 acfg->static_linking_symbol = g_strdup (symbol);
4305 emit_global_inner (acfg, symbol, FALSE);
4306 emit_alignment (acfg, 8);
4307 emit_label (acfg, symbol);
4308 emit_pointer (acfg, "globals");
4313 emit_mem_end (MonoAotCompile *acfg)
4317 sprintf (symbol, "mem_end");
4318 emit_section_change (acfg, ".text", 1);
4319 emit_global (acfg, symbol, FALSE);
4320 emit_alignment (acfg, 8);
4321 emit_label (acfg, symbol);
4325 * Emit a structure containing all the information not stored elsewhere.
4328 emit_file_info (MonoAotCompile *acfg)
4333 sprintf (symbol, "mono_aot_file_info");
4334 emit_section_change (acfg, ".data", 0);
4335 emit_alignment (acfg, 8);
4336 emit_label (acfg, symbol);
4337 emit_global (acfg, symbol, FALSE);
4339 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4340 emit_int32 (acfg, acfg->plt_got_offset_base);
4341 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4342 emit_int32 (acfg, acfg->plt_offset);
4344 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4345 emit_int32 (acfg, acfg->num_trampolines [i]);
4346 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4347 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4348 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4349 emit_int32 (acfg, acfg->trampoline_size [i]);
4353 emit_dwarf_info (MonoAotCompile *acfg)
4355 #ifdef EMIT_DWARF_INFO
4357 char symbol [128], symbol2 [128];
4359 /* DIEs for methods */
4360 for (i = 0; i < acfg->nmethods; ++i) {
4361 MonoCompile *cfg = acfg->cfgs [i];
4366 sprintf (symbol, ".Lm_%x", i);
4367 sprintf (symbol2, ".Lme_%x", i);
4369 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
4375 collect_methods (MonoAotCompile *acfg)
4378 MonoImage *image = acfg->image;
4380 /* Collect methods */
4381 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4383 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4385 method = mono_get_method (acfg->image, token, NULL);
4388 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4392 /* Load all methods eagerly to skip the slower lazy loading code */
4393 mono_class_setup_methods (method->klass);
4395 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4396 /* Compile the wrapper instead */
4397 /* We do this here instead of add_wrappers () because it is easy to do it here */
4398 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4402 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4403 add_method_with_index (acfg, method, i);
4404 acfg->method_index ++;
4407 add_generic_instances (acfg);
4409 if (acfg->aot_opts.full_aot)
4410 add_wrappers (acfg);
4414 compile_methods (MonoAotCompile *acfg)
4418 if (acfg->aot_opts.nthreads > 0) {
4423 gpointer *user_data;
4424 MonoMethod **methods;
4426 methods_len = acfg->methods->len;
4428 len = acfg->methods->len / acfg->aot_opts.nthreads;
4431 * Partition the list of methods into fragments, and hand it to threads to
4434 threads = g_ptr_array_new ();
4435 /* Make a copy since acfg->methods is modified by compile_method () */
4436 methods = g_new0 (MonoMethod*, methods_len);
4437 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4438 for (i = 0; i < methods_len; ++i)
4439 methods [i] = g_ptr_array_index (acfg->methods, i);
4441 while (i < methods_len) {
4442 frag = g_ptr_array_new ();
4443 for (j = 0; j < len; ++j) {
4444 if (i < methods_len) {
4445 g_ptr_array_add (frag, methods [i]);
4450 user_data = g_new0 (gpointer, 3);
4451 user_data [0] = mono_domain_get ();
4452 user_data [1] = acfg;
4453 user_data [2] = frag;
4455 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4456 g_ptr_array_add (threads, handle);
4460 for (i = 0; i < threads->len; ++i) {
4461 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4467 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4468 for (i = methods_len; i < acfg->methods->len; ++i) {
4469 /* This can new methods to acfg->methods */
4470 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4475 compile_asm (MonoAotCompile *acfg)
4477 char *command, *objfile;
4478 char *outfile_name, *tmp_outfile_name;
4480 #if defined(TARGET_AMD64)
4481 #define AS_OPTIONS "--64"
4482 #elif defined(sparc) && SIZEOF_VOID_P == 8
4483 #define AS_OPTIONS "-xarch=v9"
4485 #define AS_OPTIONS ""
4488 if (acfg->aot_opts.asm_only) {
4489 printf ("Output file: '%s'.\n", acfg->tmpfname);
4490 if (acfg->aot_opts.static_link)
4491 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4495 if (acfg->aot_opts.static_link) {
4496 if (acfg->aot_opts.outfile)
4497 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4499 objfile = g_strdup_printf ("%s.o", acfg->image->name);
4501 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
4503 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
4504 printf ("Executing the native assembler: %s\n", command);
4505 if (system (command) != 0) {
4513 if (acfg->aot_opts.static_link) {
4514 printf ("Output file: '%s'.\n", objfile);
4515 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4520 if (acfg->aot_opts.outfile)
4521 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4523 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4525 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4528 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4529 #elif defined(__ppc__) && defined(__MACH__)
4530 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4531 #elif defined(PLATFORM_WIN32)
4532 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4534 command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4536 printf ("Executing the native linker: %s\n", command);
4537 if (system (command) != 0) {
4538 g_free (tmp_outfile_name);
4539 g_free (outfile_name);
4547 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
4548 printf ("Stripping the binary: %s\n", com);
4552 #if defined(TARGET_ARM) && !defined(__MACH__)
4554 * gas generates 'mapping symbols' each time code and data is mixed, which
4555 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
4557 command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
4558 printf ("Stripping the binary: %s\n", command);
4559 if (system (command) != 0) {
4560 g_free (tmp_outfile_name);
4561 g_free (outfile_name);
4568 rename (tmp_outfile_name, outfile_name);
4570 g_free (tmp_outfile_name);
4571 g_free (outfile_name);
4574 if (acfg->aot_opts.save_temps)
4575 printf ("Retained input file.\n");
4577 unlink (acfg->tmpfname);
4582 static MonoAotCompile*
4583 acfg_create (MonoAssembly *ass, guint32 opts)
4585 MonoImage *image = ass->image;
4586 MonoAotCompile *acfg;
4588 acfg = g_new0 (MonoAotCompile, 1);
4589 acfg->methods = g_ptr_array_new ();
4590 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4591 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4592 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4593 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4594 acfg->shared_patches = g_ptr_array_new ();
4595 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4596 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4597 acfg->image_hash = g_hash_table_new (NULL, NULL);
4598 acfg->image_table = g_ptr_array_new ();
4599 acfg->globals = g_ptr_array_new ();
4600 acfg->image = image;
4602 acfg->mempool = mono_mempool_new ();
4603 acfg->extra_methods = g_ptr_array_new ();
4604 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
4605 acfg->unwind_ops = g_ptr_array_new ();
4606 InitializeCriticalSection (&acfg->mutex);
4612 acfg_free (MonoAotCompile *acfg)
4616 img_writer_destroy (acfg->w);
4617 for (i = 0; i < acfg->nmethods; ++i)
4619 g_free (acfg->cfgs [i]);
4620 g_free (acfg->cfgs);
4621 g_free (acfg->static_linking_symbol);
4622 g_ptr_array_free (acfg->methods, TRUE);
4623 g_ptr_array_free (acfg->shared_patches, TRUE);
4624 g_ptr_array_free (acfg->image_table, TRUE);
4625 g_ptr_array_free (acfg->globals, TRUE);
4626 g_ptr_array_free (acfg->unwind_ops, TRUE);
4627 g_hash_table_destroy (acfg->method_indexes);
4628 g_hash_table_destroy (acfg->plt_offset_to_patch);
4629 g_hash_table_destroy (acfg->patch_to_plt_offset);
4630 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4631 g_hash_table_destroy (acfg->method_to_cfg);
4632 g_hash_table_destroy (acfg->token_info_hash);
4633 g_hash_table_destroy (acfg->image_hash);
4634 g_hash_table_destroy (acfg->unwind_info_offsets);
4635 mono_mempool_destroy (acfg->mempool);
4640 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4642 MonoImage *image = ass->image;
4644 MonoAotCompile *acfg;
4645 char *outfile_name, *tmp_outfile_name, *p;
4649 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4651 acfg = acfg_create (ass, opts);
4653 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4654 acfg->aot_opts.write_symbols = TRUE;
4655 acfg->aot_opts.ntrampolines = 10240;
4657 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4659 //acfg->aot_opts.print_skipped_methods = TRUE;
4661 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4662 if (acfg->aot_opts.full_aot) {
4663 printf ("--aot=full is not supported on this platform.\n");
4668 if (acfg->aot_opts.static_link)
4669 acfg->aot_opts.asm_writer = TRUE;
4671 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4672 if (acfg->aot_opts.outfile)
4673 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4675 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4677 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4679 acfg->fp = fopen (tmp_outfile_name, "w");
4680 g_assert (acfg->fp);
4682 acfg->w = img_writer_create (acfg->fp, TRUE);
4683 acfg->use_bin_writer = TRUE;
4685 if (acfg->aot_opts.asm_only) {
4686 if (acfg->aot_opts.outfile)
4687 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4689 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4690 acfg->fp = fopen (acfg->tmpfname, "w+");
4692 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4693 acfg->fp = fdopen (i, "w+");
4695 g_assert (acfg->fp);
4697 acfg->w = img_writer_create (acfg->fp, FALSE);
4699 tmp_outfile_name = NULL;
4700 outfile_name = NULL;
4703 load_profile_files (acfg);
4705 if (!acfg->aot_opts.nodebug)
4706 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4708 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
4709 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
4710 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
4712 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
4714 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
4716 /* Get rid of characters which cannot occur in symbols */
4717 p = acfg->got_symbol;
4718 for (p = acfg->got_symbol; *p; ++p) {
4719 if (!(isalnum (*p) || *p == '_'))
4723 acfg->method_index = 1;
4725 collect_methods (acfg);
4727 acfg->cfgs_size = acfg->methods->len + 32;
4728 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4730 /* PLT offset 0 is reserved for the PLT trampoline */
4731 acfg->plt_offset = 1;
4735 compile_methods (acfg);
4739 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4743 alloc_got_slots (acfg);
4745 img_writer_emit_start (acfg->w);
4748 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4754 emit_extra_methods (acfg);
4756 emit_method_order (acfg);
4758 emit_trampolines (acfg);
4760 emit_class_name_table (acfg);
4762 emit_got_info (acfg);
4764 emit_exception_info (acfg);
4766 emit_unwind_info (acfg);
4768 emit_class_info (acfg);
4772 emit_image_table (acfg);
4776 emit_file_info (acfg);
4778 emit_globals (acfg);
4781 emit_dwarf_info (acfg);
4783 emit_mem_end (acfg);
4787 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4789 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %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, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
4792 res = img_writer_emit_writeout (acfg->w);
4797 if (acfg->use_bin_writer) {
4798 rename (tmp_outfile_name, outfile_name);
4800 res = compile_asm (acfg);
4807 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4809 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);
4810 if (acfg->stats.genericcount)
4811 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4812 if (acfg->stats.abscount)
4813 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4814 if (acfg->stats.lmfcount)
4815 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4816 if (acfg->stats.ocount)
4817 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4818 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);
4819 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4822 printf ("GOT slot distribution:\n");
4823 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4824 if (acfg->stats.got_slot_types [i])
4825 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4828 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);
4836 * Support for emitting debug info for JITted code.
4838 * This works as follows:
4839 * - the runtime writes out an xdb.s file containing DWARF debug info.
4840 * - the user calls a gdb macro
4841 * - the macro compiles and loads this shared library using add-symbol-file.
4843 * This is based on the xdebug functionality in the Kaffe Java VM.
4845 * We emit assembly code instead of using the ELF writer, so we can emit debug info
4846 * incrementally as each method is JITted, and the debugger doesn't have to call
4847 * into the runtime to emit the shared library, which would cause all kinds of
4848 * complications, like threading issues, and the fact that the ELF writer's
4849 * emit_writeout () function cannot be called more than once.
4852 /* The recommended gdb macro is: */
4855 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4856 add-symbol-file xdb.so 0
4860 static MonoDwarfWriter *xdebug_writer;
4861 static FILE *xdebug_fp;
4864 mono_xdebug_init (void)
4870 xdebug_fp = fopen ("xdb.s", "w");
4872 w = img_writer_create (xdebug_fp, FALSE);
4874 img_writer_emit_start (w);
4876 /* This file will contain the IL code for methods which don't have debug info */
4877 il_file = fopen ("xdb.il", "w");
4879 xdebug_writer = mono_dwarf_writer_create (w, il_file);
4881 /* Emit something so the file has a text segment */
4882 img_writer_emit_section_change (w, ".text", 0);
4883 img_writer_emit_string (w, "");
4885 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4889 * mono_save_xdebug_info:
4891 * Emit debugging info for METHOD into an assembly file which can be assembled
4892 * and loaded into gdb to provide debugging info for JITted code.
4893 * LOCKING: Acquires the loader lock.
4896 mono_save_xdebug_info (MonoCompile *cfg)
4901 mono_loader_lock ();
4902 mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, 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 ()));
4904 mono_loader_unlock ();
4908 * mono_save_trampoline_xdebug_info:
4910 * Same as mono_save_xdebug_info, but for trampolines.
4911 * LOCKING: Acquires the loader lock.
4914 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4919 mono_loader_lock ();
4920 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4922 mono_loader_unlock ();
4930 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4936 mono_xdebug_init (void)
4941 mono_save_xdebug_info (MonoCompile *cfg)
4946 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)