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;
159 GHashTable *method_label_hash;
162 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
163 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
165 #ifdef HAVE_ARRAY_ELEM_INIT
166 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
167 #define MSGSTRFIELD1(line) str##line
168 static const struct msgstr_t {
169 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
170 #include "patch-info.h"
173 #define PATCH_INFO(a,b) b,
174 #include "patch-info.h"
177 static const gint16 opidx [] = {
178 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
179 #include "patch-info.h"
183 static G_GNUC_UNUSED const char*
184 get_patch_name (int info)
186 return (const char*)&opstr + opidx [info];
190 #define PATCH_INFO(a,b) b,
191 static const char* const
192 patch_types [MONO_PATCH_INFO_NUM + 1] = {
193 #include "patch-info.h"
198 get_patch_name (int info)
200 return patch_types [info];
205 /* Wrappers around the image writer functions */
208 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
210 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
214 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
216 img_writer_emit_push_section (acfg->w, section_name, subsection);
220 emit_pop_section (MonoAotCompile *acfg)
222 img_writer_emit_pop_section (acfg->w);
226 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
228 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
232 emit_label (MonoAotCompile *acfg, const char *name)
234 img_writer_emit_label (acfg->w, name);
238 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
240 img_writer_emit_bytes (acfg->w, buf, size);
244 emit_string (MonoAotCompile *acfg, const char *value)
246 img_writer_emit_string (acfg->w, value);
250 emit_line (MonoAotCompile *acfg)
252 img_writer_emit_line (acfg->w);
256 emit_alignment (MonoAotCompile *acfg, int size)
258 img_writer_emit_alignment (acfg->w, size);
262 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
264 img_writer_emit_pointer_unaligned (acfg->w, target);
268 emit_pointer (MonoAotCompile *acfg, const char *target)
270 img_writer_emit_pointer (acfg->w, target);
274 emit_int16 (MonoAotCompile *acfg, int value)
276 img_writer_emit_int16 (acfg->w, value);
280 emit_int32 (MonoAotCompile *acfg, int value)
282 img_writer_emit_int32 (acfg->w, value);
286 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
288 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
292 emit_zero_bytes (MonoAotCompile *acfg, int num)
294 img_writer_emit_zero_bytes (acfg->w, num);
298 emit_byte (MonoAotCompile *acfg, guint8 val)
300 img_writer_emit_byte (acfg->w, val);
303 static G_GNUC_UNUSED void
304 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
306 img_writer_emit_global (acfg->w, name, func);
310 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
312 if (acfg->aot_opts.no_dlsym) {
313 g_ptr_array_add (acfg->globals, g_strdup (name));
315 img_writer_emit_global (acfg->w, name, func);
320 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
322 img_writer_emit_section_change (acfg->w, ".text", 1);
323 emit_global (acfg, name, FALSE);
324 img_writer_emit_label (acfg->w, name);
325 img_writer_emit_string (acfg->w, value);
328 static G_GNUC_UNUSED void
329 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
332 guint8 b = value & 0x7f;
334 if (value != 0) /* more bytes to come */
340 static G_GNUC_UNUSED void
341 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
344 gboolean negative = (value < 0);
351 /* the following is unnecessary if the
352 * implementation of >>= uses an arithmetic rather
353 * than logical shift for a signed left operand
357 value |= - ((gint64)1 <<(size - 7));
358 /* sign bit of byte is second high order bit (0x40) */
359 if ((value == 0 && !(byte & 0x40)) ||
360 (value == -1 && (byte & 0x40)))
364 emit_byte (acfg, byte);
368 static G_GNUC_UNUSED void
369 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
374 guint8 b = value & 0x7f;
376 if (value != 0) /* more bytes to come */
384 static G_GNUC_UNUSED void
385 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
388 gboolean negative = (value < 0);
396 /* the following is unnecessary if the
397 * implementation of >>= uses an arithmetic rather
398 * than logical shift for a signed left operand
402 value |= - (1 <<(size - 7));
403 /* sign bit of byte is second high order bit (0x40) */
404 if ((value == 0 && !(byte & 0x40)) ||
405 (value == -1 && (byte & 0x40)))
415 /* ARCHITECTURE SPECIFIC CODE */
417 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
418 #define EMIT_DWARF_INFO 1
422 * arch_emit_direct_call:
424 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
428 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
430 #if defined(TARGET_X86) || defined(TARGET_AMD64)
431 /* Need to make sure this is exactly 5 bytes long */
432 emit_byte (acfg, '\xe8');
433 emit_symbol_diff (acfg, target, ".", -4);
435 #elif defined(TARGET_ARM)
436 if (acfg->use_bin_writer) {
443 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
444 emit_bytes (acfg, buf, 4);
446 img_writer_emit_unset_mode (acfg->w);
447 fprintf (acfg->fp, "bl %s\n", target);
451 g_assert_not_reached ();
455 #ifdef MONO_ARCH_AOT_SUPPORTED
457 * arch_emit_got_offset:
459 * The memory pointed to by CODE should hold native code for computing the GOT
460 * address. Emit this code while patching it with the offset between code and
461 * the GOT. CODE_SIZE is set to the number of bytes emitted.
464 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
466 guint32 offset = mono_arch_get_patch_offset (code);
467 emit_bytes (acfg, code, offset);
468 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
470 *code_size = offset + 4;
474 * arch_emit_got_access:
476 * The memory pointed to by CODE should hold native code for loading a GOT
477 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
478 * CODE_SIZE is set to the number of bytes emitted.
481 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
483 /* Emit beginning of instruction */
484 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
486 /* Emit the offset */
488 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
489 #elif defined(TARGET_X86)
490 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
491 #elif defined(TARGET_ARM)
492 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
494 g_assert_not_reached ();
497 *code_size = mono_arch_get_patch_offset (code) + 4;
503 * arch_emit_plt_entry:
505 * Emit code for the PLT entry with index INDEX.
508 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
510 #if defined(TARGET_X86)
512 /* It is filled up during loading by the AOT loader. */
513 emit_zero_bytes (acfg, 16);
515 /* Need to make sure this is 9 bytes long */
516 emit_byte (acfg, '\xe9');
517 emit_symbol_diff (acfg, "plt", ".", -4);
518 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
520 #elif defined(TARGET_AMD64)
522 * We can't emit jumps because they are 32 bits only so they can't be patched.
523 * So we make indirect calls through GOT entries which are patched by the AOT
524 * loader to point to .Lpd entries.
525 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
527 /* jmpq *<offset>(%rip) */
528 emit_byte (acfg, '\xff');
529 emit_byte (acfg, '\x25');
530 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
531 /* Used by mono_aot_get_plt_info_offset */
532 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
533 #elif defined(TARGET_ARM)
538 * - optimize OP_AOTCONST implementation
539 * - optimize the PLT entries
540 * - optimize SWITCH AOT implementation
541 * - implement IMT support
544 if (acfg->use_bin_writer) {
545 /* We only emit 1 relocation since we implement it ourselves anyway */
546 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
547 /* FIXME: A 2 instruction encoding is sufficient in most cases */
548 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
549 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
550 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
551 emit_bytes (acfg, buf, code - buf);
552 /* FIXME: Get rid of this */
553 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
554 /* Used by mono_aot_get_plt_info_offset */
555 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
557 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
558 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
559 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
560 emit_bytes (acfg, buf, code - buf);
561 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
562 /* Used by mono_aot_get_plt_info_offset */
563 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
566 g_assert_not_reached ();
571 * arch_emit_specific_trampoline:
573 * Emit code for a specific trampoline. OFFSET is the offset of the first of
574 * two GOT slots which contain the generic trampoline address and the trampoline
575 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
578 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
581 * The trampolines created here are variations of the specific
582 * trampolines created in mono_arch_create_specific_trampoline (). The
584 * - the generic trampoline address is taken from a got slot.
585 * - the offset of the got slot where the trampoline argument is stored
586 * is embedded in the instruction stream, and the generic trampoline
587 * can load the argument by loading the offset, adding it to the
588 * address of the trampoline to get the address of the got slot, and
589 * loading the argument from there.
590 * - all the trampolines should be of the same length.
592 #if defined(TARGET_AMD64)
593 /* This should be exactly 16 bytes long */
595 /* call *<offset>(%rip) */
596 emit_byte (acfg, '\x41');
597 emit_byte (acfg, '\xff');
598 emit_byte (acfg, '\x15');
599 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
600 /* This should be relative to the start of the trampoline */
601 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
602 emit_zero_bytes (acfg, 5);
603 #elif defined(TARGET_ARM)
607 /* This should be exactly 28 bytes long */
610 ARM_PUSH (code, 0x5fff);
611 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
612 /* Load the value from the GOT */
613 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
615 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
616 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
618 g_assert (code - buf == 20);
621 emit_bytes (acfg, buf, code - buf);
622 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
623 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
625 g_assert_not_reached ();
630 * arch_emit_unbox_trampoline:
632 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
633 * CALL_TARGET is the symbol pointing to the native code of METHOD.
636 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
638 #if defined(TARGET_AMD64)
643 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
645 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
647 emit_bytes (acfg, buf, code - buf);
649 emit_byte (acfg, '\xe9');
650 emit_symbol_diff (acfg, call_target, ".", -4);
651 #elif defined(TARGET_ARM)
658 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
661 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
663 emit_bytes (acfg, buf, code - buf);
665 if (acfg->use_bin_writer) {
672 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
673 emit_bytes (acfg, buf, 4);
675 fprintf (acfg->fp, "\n\tb %s\n", call_target);
678 g_assert_not_reached ();
683 * arch_emit_static_rgctx_trampoline:
685 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
686 * two GOT slots which contain the rgctx argument, and the method to jump to.
687 * TRAMP_SIZE is set to the size of the emitted trampoline.
688 * These kinds of trampolines cannot be enumerated statically, since there could
689 * be one trampoline per method instantiation, so we emit the same code for all
690 * trampolines, and parameterize them using two GOT slots.
693 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
695 #if defined(TARGET_AMD64)
696 /* This should be exactly 13 bytes long */
699 /* mov <OFFSET>(%rip), %r10 */
700 emit_byte (acfg, '\x4d');
701 emit_byte (acfg, '\x8b');
702 emit_byte (acfg, '\x15');
703 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
705 /* jmp *<offset>(%rip) */
706 emit_byte (acfg, '\xff');
707 emit_byte (acfg, '\x25');
708 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
709 #elif defined(TARGET_ARM)
713 /* This should be exactly 24 bytes long */
716 /* Load rgctx value */
717 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
718 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
719 /* Load branch addr + branch */
720 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
721 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
723 g_assert (code - buf == 16);
726 emit_bytes (acfg, buf, code - buf);
727 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
728 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
730 g_assert_not_reached ();
735 * arch_emit_imt_thunk:
737 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
738 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
739 * key is the IMT key, and ptr holds the address of a memory location holding
740 * the address to branch to if the IMT arg matches the key. The array is
741 * terminated by a pair whose key is NULL, and whose ptr is the address of the
743 * TRAMP_SIZE is set to the size of the emitted trampoline.
746 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
748 #if defined(TARGET_AMD64)
752 code = buf = g_malloc (256);
754 /* FIXME: Optimize this, i.e. use binary search etc. */
755 /* Maybe move the body into a separate function (slower, but much smaller) */
757 /* R10 is a free register */
760 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
762 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
765 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
767 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
770 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
771 amd64_jump_code (code, labels [0]);
774 mono_amd64_patch (labels [2], code);
775 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
776 amd64_jump_membase (code, AMD64_R10, 0);
780 mono_amd64_patch (labels [1], code);
781 x86_breakpoint (code);
783 /* mov <OFFSET>(%rip), %r10 */
784 emit_byte (acfg, '\x4d');
785 emit_byte (acfg, '\x8b');
786 emit_byte (acfg, '\x15');
787 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
789 emit_bytes (acfg, buf, code - buf);
791 *tramp_size = code - buf + 7;
792 #elif defined(TARGET_ARM)
794 guint8 *code, *code2, *labels [16];
798 /* The IMT method is in v5 */
800 /* Only IP is available, but we need at least two free registers */
801 ARM_PUSH1 (code, ARMREG_R1);
803 /* Load the parameter from the GOT */
804 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
805 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
808 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_IP, 0);
809 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
811 ARM_B_COND (code, ARMCOND_EQ, 0);
813 /* End-of-loop check */
814 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
816 ARM_B_COND (code, ARMCOND_EQ, 0);
819 ARM_ADD_REG_IMM8 (code, ARMREG_IP, ARMREG_IP, sizeof (gpointer) * 2);
822 arm_patch (labels [4], labels [1]);
825 arm_patch (labels [2], code);
826 ARM_POP1 (code, ARMREG_R1);
827 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_IP, 4);
828 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
831 arm_patch (labels [3], code);
836 ARM_LDR_IMM (code2, ARMREG_IP, ARMREG_PC, (code - (labels [0] + 8)));
838 emit_bytes (acfg, buf, code - buf);
839 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
841 *tramp_size = code - buf + 4;
843 g_assert_not_reached ();
848 * arch_get_cie_program:
850 * Get the unwind bytecode for the DWARF CIE.
853 arch_get_cie_program (void)
858 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
859 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
867 /* END OF ARCH SPECIFIC CODE */
870 mono_get_field_token (MonoClassField *field)
872 MonoClass *klass = field->parent;
875 for (i = 0; i < klass->field.count; ++i) {
876 if (field == &klass->fields [i])
877 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
880 g_assert_not_reached ();
885 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
889 //printf ("ENCODE: %d 0x%x.\n", value, value);
892 * Same encoding as the one used in the metadata, extended to handle values
893 * greater than 0x1fffffff.
895 if ((value >= 0) && (value <= 127))
897 else if ((value >= 0) && (value <= 16383)) {
898 p [0] = 0x80 | (value >> 8);
899 p [1] = value & 0xff;
901 } else if ((value >= 0) && (value <= 0x1fffffff)) {
902 p [0] = (value >> 24) | 0xc0;
903 p [1] = (value >> 16) & 0xff;
904 p [2] = (value >> 8) & 0xff;
905 p [3] = value & 0xff;
910 p [1] = (value >> 24) & 0xff;
911 p [2] = (value >> 16) & 0xff;
912 p [3] = (value >> 8) & 0xff;
913 p [4] = value & 0xff;
921 get_image_index (MonoAotCompile *cfg, MonoImage *image)
925 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
929 index = g_hash_table_size (cfg->image_hash);
930 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
931 g_ptr_array_add (cfg->image_table, image);
937 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
942 /* FIXME: Search referenced images as well */
943 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
944 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
949 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
950 return MONO_TOKEN_TYPE_SPEC | (i + 1);
956 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
961 * Encode a reference to KLASS. We use our home-grown encoding instead of the
962 * standard metadata encoding.
965 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
969 if (klass->generic_class) {
971 g_assert (klass->type_token);
973 /* Find a typespec for a class if possible */
974 token = find_typespec_for_class (acfg, klass);
976 encode_value (token, p, &p);
977 encode_value (get_image_index (acfg, acfg->image), p, &p);
979 MonoClass *gclass = klass->generic_class->container_class;
980 MonoGenericInst *inst = klass->generic_class->context.class_inst;
983 /* Encode it ourselves */
985 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
986 encode_value (MONO_TYPE_GENERICINST, p, &p);
987 encode_klass_ref (acfg, gclass, p, &p);
988 encode_value (inst->type_argc, p, &p);
989 for (i = 0; i < inst->type_argc; ++i)
990 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
992 } else if (klass->type_token) {
993 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
994 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
995 encode_value (get_image_index (acfg, klass->image), p, &p);
996 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
997 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
998 g_assert (container);
1001 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1002 encode_value (klass->byval_arg.type, p, &p);
1004 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1006 encode_value (container->is_method, p, &p);
1007 if (container->is_method)
1008 encode_method_ref (acfg, container->owner.method, p, &p);
1010 encode_klass_ref (acfg, container->owner.klass, p, &p);
1013 g_assert (klass->rank > 0);
1014 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1015 encode_value (get_image_index (acfg, klass->image), p, &p);
1016 encode_value (klass->rank, p, &p);
1017 encode_klass_ref (acfg, klass->element_class, p, &p);
1023 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1025 guint32 token = mono_get_field_token (field);
1028 encode_klass_ref (cfg, field->parent, p, &p);
1029 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1030 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1035 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1039 MonoGenericInst *inst;
1041 /* Encode the context */
1042 inst = context->class_inst;
1043 encode_value (inst ? 1 : 0, p, &p);
1045 encode_value (inst->type_argc, p, &p);
1046 for (i = 0; i < inst->type_argc; ++i)
1047 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1049 inst = context->method_inst;
1050 encode_value (inst ? 1 : 0, p, &p);
1052 encode_value (inst->type_argc, p, &p);
1053 for (i = 0; i < inst->type_argc; ++i)
1054 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1060 #define MAX_IMAGE_INDEX 250
1063 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1065 guint32 image_index = get_image_index (acfg, method->klass->image);
1066 guint32 token = method->token;
1067 MonoJumpInfoToken *ji;
1072 * The encoding for most methods is as follows:
1073 * - image index encoded as a leb128
1074 * - token index encoded as a leb128
1075 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1076 * types of method encodings.
1079 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1081 /* Mark methods which can't use aot trampolines because they need the further
1082 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1084 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1085 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1086 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1089 * Some wrapper methods are shared using their signature, encode their
1090 * stringified signature instead.
1091 * FIXME: Optimize disk usage
1094 if (method->wrapper_type) {
1095 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1096 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1097 if (mono_marshal_method_from_wrapper (method) != method) {
1098 /* Direct wrapper, encode it normally */
1100 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1103 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1104 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1105 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1107 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1108 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1109 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1111 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1112 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1113 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1119 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1120 strcpy ((char*)p, name);
1121 p += strlen (name) + 1;
1123 } else if (method->wrapper_type) {
1124 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1126 encode_value (method->wrapper_type, p, &p);
1128 switch (method->wrapper_type) {
1129 case MONO_WRAPPER_REMOTING_INVOKE:
1130 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1131 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1134 m = mono_marshal_method_from_wrapper (method);
1136 encode_method_ref (acfg, m, p, &p);
1139 case MONO_WRAPPER_PROXY_ISINST:
1140 case MONO_WRAPPER_LDFLD:
1141 case MONO_WRAPPER_LDFLDA:
1142 case MONO_WRAPPER_STFLD:
1143 case MONO_WRAPPER_ISINST: {
1144 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1145 encode_klass_ref (acfg, proxy_class, p, &p);
1148 case MONO_WRAPPER_LDFLD_REMOTE:
1149 case MONO_WRAPPER_STFLD_REMOTE:
1151 case MONO_WRAPPER_ALLOC: {
1152 int alloc_type = mono_gc_get_managed_allocator_type (method);
1153 g_assert (alloc_type != -1);
1154 encode_value (alloc_type, p, &p);
1157 case MONO_WRAPPER_STELEMREF:
1159 case MONO_WRAPPER_UNKNOWN:
1160 if (strcmp (method->name, "FastMonitorEnter") == 0)
1161 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1162 else if (strcmp (method->name, "FastMonitorExit") == 0)
1163 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1165 g_assert_not_reached ();
1167 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
1168 case MONO_WRAPPER_SYNCHRONIZED:
1169 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1170 case MONO_WRAPPER_RUNTIME_INVOKE: {
1173 m = mono_marshal_method_from_wrapper (method);
1175 g_assert (m != method);
1176 encode_method_ref (acfg, m, p, &p);
1180 g_assert_not_reached ();
1182 } else if (mono_method_signature (method)->is_inflated) {
1184 * This is a generic method, find the original token which referenced it and
1186 * Obtain the token from information recorded by the JIT.
1188 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1190 image_index = get_image_index (acfg, ji->image);
1191 g_assert (image_index < MAX_IMAGE_INDEX);
1194 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1195 encode_value (image_index, p, &p);
1196 encode_value (token, p, &p);
1198 MonoMethod *declaring;
1199 MonoGenericContext *context = mono_method_get_context (method);
1201 g_assert (method->is_inflated);
1202 declaring = ((MonoMethodInflated*)method)->declaring;
1205 * This might be a non-generic method of a generic instance, which
1206 * doesn't have a token since the reference is generated by the JIT
1207 * like Nullable:Box/Unbox, or by generic sharing.
1210 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1211 /* Encode the klass */
1212 encode_klass_ref (acfg, method->klass, p, &p);
1213 /* Encode the method */
1214 image_index = get_image_index (acfg, method->klass->image);
1215 g_assert (image_index < MAX_IMAGE_INDEX);
1216 g_assert (declaring->token);
1217 token = declaring->token;
1218 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1219 encode_value (image_index, p, &p);
1220 encode_value (token, p, &p);
1221 encode_generic_context (acfg, context, p, &p);
1223 } else if (token == 0) {
1224 /* This might be a method of a constructed type like int[,].Set */
1225 /* Obtain the token from information recorded by the JIT */
1226 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1228 image_index = get_image_index (acfg, ji->image);
1229 g_assert (image_index < MAX_IMAGE_INDEX);
1232 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1233 encode_value (image_index, p, &p);
1234 encode_value (token, p, &p);
1237 g_assert (method->klass->rank);
1239 /* Encode directly */
1240 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1241 encode_klass_ref (acfg, method->klass, p, &p);
1242 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1243 encode_value (0, p, &p);
1244 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1245 encode_value (1, p, &p);
1246 else if (!strcmp (method->name, "Get"))
1247 encode_value (2, p, &p);
1248 else if (!strcmp (method->name, "Address"))
1249 encode_value (3, p, &p);
1250 else if (!strcmp (method->name, "Set"))
1251 encode_value (4, p, &p);
1253 g_assert_not_reached ();
1256 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1257 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1263 compare_patches (gconstpointer a, gconstpointer b)
1267 i = (*(MonoJumpInfo**)a)->ip.i;
1268 j = (*(MonoJumpInfo**)b)->ip.i;
1282 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1285 static inline gboolean
1286 is_plt_patch (MonoJumpInfo *patch_info)
1288 switch (patch_info->type) {
1289 case MONO_PATCH_INFO_METHOD:
1290 case MONO_PATCH_INFO_INTERNAL_METHOD:
1291 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1292 case MONO_PATCH_INFO_ICALL_ADDR:
1293 case MONO_PATCH_INFO_CLASS_INIT:
1294 case MONO_PATCH_INFO_RGCTX_FETCH:
1295 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1296 case MONO_PATCH_INFO_MONITOR_ENTER:
1297 case MONO_PATCH_INFO_MONITOR_EXIT:
1305 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1309 if (is_plt_patch (patch_info)) {
1310 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1312 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1314 * Allocate a separate PLT slot for each such patch, since some plt
1315 * entries will refer to the method itself, and some will refer to
1324 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1326 res = acfg->plt_offset;
1327 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1328 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1329 acfg->plt_offset ++;
1339 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1340 * JI could be found if it exists, otherwise allocates a new one.
1343 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1347 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1349 return got_offset - 1;
1351 got_offset = acfg->got_offset;
1352 acfg->got_offset ++;
1354 acfg->stats.got_slots ++;
1355 acfg->stats.got_slot_types [ji->type] ++;
1361 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1366 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1367 got_offset = get_got_offset (acfg, ji);
1368 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1369 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1370 g_ptr_array_add (acfg->shared_patches, copy);
1373 return get_got_offset (acfg, ji);
1376 /* Add a method to the list of methods which need to be emitted */
1378 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1381 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1382 g_ptr_array_add (acfg->methods, method);
1383 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1384 acfg->nmethods = acfg->methods->len + 1;
1387 if (method->wrapper_type || extra)
1388 g_ptr_array_add (acfg->extra_methods, method);
1392 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1394 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1402 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra)
1406 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1410 index = acfg->method_index;
1411 add_method_with_index (acfg, method, index, extra);
1413 /* FIXME: Fix quadratic behavior */
1414 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1416 acfg->method_index ++;
1422 add_method (MonoAotCompile *acfg, MonoMethod *method)
1424 return add_method_full (acfg, method, FALSE);
1428 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1430 add_method_full (acfg, method, TRUE);
1434 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1436 MonoAotCompile *acfg = user_data;
1437 MonoJitICallInfo *callinfo = value;
1438 MonoMethod *wrapper;
1444 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1445 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1448 add_method (acfg, wrapper);
1452 get_runtime_invoke_sig (MonoMethodSignature *sig)
1454 MonoMethodBuilder *mb;
1457 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1458 m = mono_mb_create_method (mb, sig, 16);
1459 return mono_marshal_get_runtime_invoke (m, FALSE);
1463 add_wrappers (MonoAotCompile *acfg)
1465 MonoMethod *method, *m;
1466 int i, j, nallocators;
1467 MonoMethodSignature *sig, *csig;
1471 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1472 * so there is only one wrapper of a given type, or inlining their contents into their
1477 * FIXME: This depends on the fact that different wrappers have different
1481 /* FIXME: Collect these automatically */
1483 /* Runtime invoke wrappers */
1485 /* void runtime-invoke () [.cctor] */
1486 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1487 csig->ret = &mono_defaults.void_class->byval_arg;
1488 add_method (acfg, get_runtime_invoke_sig (csig));
1490 /* void runtime-invoke () [Finalize] */
1491 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1493 csig->ret = &mono_defaults.void_class->byval_arg;
1494 add_method (acfg, get_runtime_invoke_sig (csig));
1496 /* void runtime-invoke (string) [exception ctor] */
1497 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1499 csig->ret = &mono_defaults.void_class->byval_arg;
1500 csig->params [0] = &mono_defaults.string_class->byval_arg;
1501 add_method (acfg, get_runtime_invoke_sig (csig));
1503 /* void runtime-invoke (string, string) [exception ctor] */
1504 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1506 csig->ret = &mono_defaults.void_class->byval_arg;
1507 csig->params [0] = &mono_defaults.string_class->byval_arg;
1508 csig->params [1] = &mono_defaults.string_class->byval_arg;
1509 add_method (acfg, get_runtime_invoke_sig (csig));
1511 /* string runtime-invoke () [Exception.ToString ()] */
1512 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1514 csig->ret = &mono_defaults.string_class->byval_arg;
1515 add_method (acfg, get_runtime_invoke_sig (csig));
1517 /* void runtime-invoke (string, Exception) [exception ctor] */
1518 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1520 csig->ret = &mono_defaults.void_class->byval_arg;
1521 csig->params [0] = &mono_defaults.string_class->byval_arg;
1522 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1523 add_method (acfg, get_runtime_invoke_sig (csig));
1525 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1526 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1528 csig->ret = &(mono_class_from_name (
1529 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1530 csig->params [0] = &mono_defaults.string_class->byval_arg;
1531 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1532 add_method (acfg, get_runtime_invoke_sig (csig));
1534 /* runtime-invoke used by finalizers */
1535 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1537 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1539 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1540 gboolean skip = FALSE;
1542 method = mono_get_method (acfg->image, token, NULL);
1544 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1545 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1546 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1549 if (method->is_generic || method->klass->generic_container)
1552 /* Skip methods which can not be handled by get_runtime_invoke () */
1553 sig = mono_method_signature (method);
1554 if ((sig->ret->type == MONO_TYPE_PTR) ||
1555 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1558 for (j = 0; j < sig->param_count; j++) {
1559 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1564 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1567 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1568 MonoMethodDesc *desc;
1569 MonoMethod *orig_method;
1571 /* JIT icall wrappers */
1572 /* FIXME: locking */
1573 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1575 /* Managed Allocators */
1576 nallocators = mono_gc_get_managed_allocator_types ();
1577 for (i = 0; i < nallocators; ++i) {
1578 m = mono_gc_get_managed_allocator_by_type (i);
1580 add_method (acfg, m);
1584 add_method (acfg, mono_marshal_get_stelemref ());
1586 /* Monitor Enter/Exit */
1587 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1588 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1589 g_assert (orig_method);
1590 mono_method_desc_free (desc);
1591 method = mono_monitor_get_fast_path (orig_method);
1593 add_method (acfg, method);
1595 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1596 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1597 g_assert (orig_method);
1598 mono_method_desc_free (desc);
1599 method = mono_monitor_get_fast_path (orig_method);
1601 add_method (acfg, method);
1604 /* remoting-invoke wrappers */
1605 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1606 MonoMethodSignature *sig;
1608 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1609 method = mono_get_method (acfg->image, token, NULL);
1611 sig = mono_method_signature (method);
1613 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1614 m = mono_marshal_get_remoting_invoke_with_check (method);
1616 add_method (acfg, m);
1620 /* delegate-invoke wrappers */
1621 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1624 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1625 klass = mono_class_get (acfg->image, token);
1627 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1628 method = mono_get_delegate_invoke (klass);
1630 m = mono_marshal_get_delegate_invoke (method, NULL);
1632 add_method (acfg, m);
1634 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1635 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1637 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1638 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1642 /* Synchronized wrappers */
1643 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1644 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1645 method = mono_get_method (acfg->image, token, NULL);
1647 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1648 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1651 /* pinvoke wrappers */
1652 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1654 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1656 method = mono_get_method (acfg->image, token, NULL);
1658 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1659 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1660 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1664 /* StructureToPtr/PtrToStructure wrappers */
1665 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1668 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1669 klass = mono_class_get (acfg->image, token);
1671 if (klass->valuetype && !klass->generic_container && ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)) {
1672 MonoMarshalType *info;
1673 gboolean can_marshal = TRUE;
1676 info = mono_marshal_load_type_info (klass);
1678 /* Only allow a few field types to avoid asserts in the marshalling code */
1679 for (j = 0; j < info->num_fields; j++) {
1680 switch (info->fields [j].field->type->type) {
1685 case MONO_TYPE_BOOLEAN:
1688 case MONO_TYPE_CHAR:
1696 can_marshal = FALSE;
1702 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
1703 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
1710 has_type_vars (MonoClass *klass)
1712 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1715 return has_type_vars (klass->element_class);
1716 if (klass->generic_class) {
1717 MonoGenericContext *context = &klass->generic_class->context;
1718 if (context->class_inst) {
1721 for (i = 0; i < context->class_inst->type_argc; ++i)
1722 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1730 method_has_type_vars (MonoMethod *method)
1732 if (has_type_vars (method->klass))
1735 if (method->is_inflated) {
1736 MonoGenericContext *context = mono_method_get_context (method);
1737 if (context->method_inst) {
1740 for (i = 0; i < context->method_inst->type_argc; ++i)
1741 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1749 * add_generic_class:
1751 * Add all methods of a generic class.
1754 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1759 mono_class_init (klass);
1761 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1764 if (has_type_vars (klass))
1767 if (!klass->generic_class && !klass->rank)
1771 * Add rgctx wrappers for cctors since those are called by the runtime, so
1772 * there is no methodspec for them. This is needed even for shared classes,
1773 * since rgctx wrappers belong to inflated methods.
1775 method = mono_class_get_cctor (klass);
1776 if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
1777 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1780 while ((method = mono_class_get_methods (klass, &iter))) {
1781 if (mono_method_is_generic_sharable_impl (method, FALSE))
1785 if (method->is_generic)
1790 * FIXME: Instances which are referenced by these methods are not added,
1791 * for example Array.Resize<int> for List<int>.Add ().
1793 add_extra_method (acfg, method);
1797 * For ICollection<T>, where T is a vtype, add instances of the helper methods
1798 * in Array, since a T[] could be cast to ICollection<T>.
1800 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
1801 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
1802 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
1803 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
1804 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
1808 if (!strcmp (klass->name, "IEnumerator`1"))
1809 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
1811 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
1813 /* Add the T[]/InternalEnumerator class */
1814 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
1818 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
1819 if (!strcmp (nclass->name, "InternalEnumerator`1"))
1823 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
1824 add_generic_class (acfg, nclass);
1828 while ((method = mono_class_get_methods (array_class, &iter))) {
1829 if (strstr (method->name, name_prefix))
1830 add_extra_method (acfg, method);
1833 g_free (name_prefix);
1838 * add_generic_instances:
1840 * Add instances referenced by the METHODSPEC/TYPESPEC table.
1843 add_generic_instances (MonoAotCompile *acfg)
1848 MonoMethodHeader *header;
1849 MonoMethodSignature *sig;
1850 MonoGenericContext *context;
1852 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1853 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1854 method = mono_get_method (acfg->image, token, NULL);
1856 context = mono_method_get_context (method);
1857 if (context && ((context->class_inst && context->class_inst->is_open) ||
1858 (context->method_inst && context->method_inst->is_open)))
1861 if (method->klass->image != acfg->image)
1864 if (mono_method_is_generic_sharable_impl (method, FALSE))
1868 add_extra_method (acfg, method);
1871 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1874 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1876 klass = mono_class_get (acfg->image, token);
1877 if (!klass || klass->rank)
1880 add_generic_class (acfg, klass);
1883 /* Add types of args/locals */
1884 for (i = 0; i < acfg->methods->len; ++i) {
1887 method = g_ptr_array_index (acfg->methods, i);
1889 sig = mono_method_signature (method);
1892 for (j = 0; j < sig->param_count; ++j)
1893 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
1894 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
1897 header = mono_method_get_header (method);
1900 for (j = 0; j < header->num_locals; ++j)
1901 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
1902 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
1908 * emit_and_reloc_code:
1910 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1911 * is true, calls are made through the GOT too. This is used for emitting trampolines
1912 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1913 * since trampolines are needed to make PTL work.
1916 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1918 int i, pindex, start_index, method_index;
1920 MonoJumpInfo *patch_info;
1921 MonoMethodHeader *header;
1922 gboolean skip, direct_call;
1924 char direct_call_target [128];
1927 header = mono_method_get_header (method);
1929 method_index = get_method_index (acfg, method);
1932 /* Collect and sort relocations */
1933 patches = g_ptr_array_new ();
1934 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1935 g_ptr_array_add (patches, patch_info);
1936 g_ptr_array_sort (patches, compare_patches);
1939 for (i = 0; i < code_len; i++) {
1941 for (pindex = start_index; pindex < patches->len; ++pindex) {
1942 patch_info = g_ptr_array_index (patches, pindex);
1943 if (patch_info->ip.i >= i)
1947 #ifdef MONO_ARCH_AOT_SUPPORTED
1949 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1950 start_index = pindex;
1952 switch (patch_info->type) {
1953 case MONO_PATCH_INFO_NONE:
1955 case MONO_PATCH_INFO_GOT_OFFSET: {
1958 arch_emit_got_offset (acfg, code + i, &code_size);
1965 * If this patch is a call, try emitting a direct call instead of
1966 * through a PLT entry. This is possible if the called method is in
1967 * the same assembly and requires no initialization.
1969 direct_call = FALSE;
1970 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1971 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1973 gboolean direct_callable = TRUE;
1975 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1976 direct_callable = FALSE;
1977 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1978 // FIXME: Maybe call the wrapper directly ?
1979 direct_callable = FALSE;
1980 if (direct_callable) {
1981 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1983 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1984 patch_info->type = MONO_PATCH_INFO_NONE;
1985 acfg->stats.direct_calls ++;
1989 acfg->stats.all_calls ++;
1992 if (!got_only && !direct_call) {
1993 int plt_offset = get_plt_offset (acfg, patch_info);
1994 if (plt_offset != -1) {
1995 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1997 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1999 /* Nullify the patch */
2000 patch_info->type = MONO_PATCH_INFO_NONE;
2007 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2012 got_slot = get_got_offset (acfg, patch_info);
2014 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2021 #endif /* MONO_ARCH_AOT_SUPPORTED */
2024 /* Find next patch */
2026 for (pindex = start_index; pindex < patches->len; ++pindex) {
2027 patch_info = g_ptr_array_index (patches, pindex);
2028 if (patch_info->ip.i >= i)
2032 /* Try to emit multiple bytes at once */
2033 if (pindex < patches->len && patch_info->ip.i > i) {
2034 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2035 i = patch_info->ip.i - 1;
2037 emit_bytes (acfg, code + i, 1);
2044 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2050 int func_alignment = 16;
2051 MonoMethodHeader *header;
2053 method = cfg->orig_method;
2054 code = cfg->native_code;
2055 header = mono_method_get_header (method);
2057 method_index = get_method_index (acfg, method);
2059 /* Make the labels local */
2060 sprintf (symbol, ".Lm_%x", method_index);
2062 emit_alignment (acfg, func_alignment);
2063 emit_label (acfg, symbol);
2065 if (acfg->aot_opts.write_symbols && !acfg->aot_opts.nodebug) {
2066 char *name1, *name2, *cached;
2067 int i, j, len, count;
2069 name1 = mono_method_full_name (method, TRUE);
2070 len = strlen (name1);
2071 name2 = malloc (len + 1);
2073 for (i = 0; i < len; ++i) {
2074 if (isalnum (name1 [i])) {
2075 name2 [j ++] = name1 [i];
2076 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2078 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2081 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2088 while (g_hash_table_lookup (acfg->method_label_hash, name2)) {
2089 sprintf (name2 + j, "_%d", count);
2093 cached = g_strdup (name2);
2094 g_hash_table_insert (acfg->method_label_hash, cached, cached);
2096 sprintf (symbol, ".Lme_%x", method_index);
2097 emit_local_symbol (acfg, name2, symbol, TRUE);
2098 emit_label (acfg, name2);
2103 if (cfg->verbose_level > 0)
2104 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2106 acfg->stats.code_size += cfg->code_len;
2108 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2110 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2114 sprintf (symbol, ".Lme_%x", method_index);
2115 emit_label (acfg, symbol);
2121 * Encode PATCH_INFO into its disk representation.
2124 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2128 switch (patch_info->type) {
2129 case MONO_PATCH_INFO_NONE:
2131 case MONO_PATCH_INFO_IMAGE:
2132 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2134 case MONO_PATCH_INFO_METHOD_REL:
2135 encode_value ((gint)patch_info->data.offset, p, &p);
2137 case MONO_PATCH_INFO_SWITCH: {
2138 gpointer *table = (gpointer *)patch_info->data.table->table;
2141 encode_value (patch_info->data.table->table_size, p, &p);
2142 for (k = 0; k < patch_info->data.table->table_size; k++)
2143 encode_value ((int)(gssize)table [k], p, &p);
2146 case MONO_PATCH_INFO_METHODCONST:
2147 case MONO_PATCH_INFO_METHOD:
2148 case MONO_PATCH_INFO_METHOD_JUMP:
2149 case MONO_PATCH_INFO_ICALL_ADDR:
2150 case MONO_PATCH_INFO_METHOD_RGCTX:
2151 encode_method_ref (acfg, patch_info->data.method, p, &p);
2153 case MONO_PATCH_INFO_INTERNAL_METHOD:
2154 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2155 guint32 len = strlen (patch_info->data.name);
2157 encode_value (len, p, &p);
2159 memcpy (p, patch_info->data.name, len);
2164 case MONO_PATCH_INFO_LDSTR: {
2165 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2166 guint32 token = patch_info->data.token->token;
2167 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2168 encode_value (image_index, p, &p);
2169 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2172 case MONO_PATCH_INFO_RVA:
2173 case MONO_PATCH_INFO_DECLSEC:
2174 case MONO_PATCH_INFO_LDTOKEN:
2175 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2176 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2177 encode_value (patch_info->data.token->token, p, &p);
2178 encode_value (patch_info->data.token->has_context, p, &p);
2179 if (patch_info->data.token->has_context)
2180 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2182 case MONO_PATCH_INFO_EXC_NAME: {
2183 MonoClass *ex_class;
2186 mono_class_from_name (mono_defaults.exception_class->image,
2187 "System", patch_info->data.target);
2188 g_assert (ex_class);
2189 encode_klass_ref (acfg, ex_class, p, &p);
2192 case MONO_PATCH_INFO_R4:
2193 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2195 case MONO_PATCH_INFO_R8:
2196 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2197 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2199 case MONO_PATCH_INFO_VTABLE:
2200 case MONO_PATCH_INFO_CLASS:
2201 case MONO_PATCH_INFO_IID:
2202 case MONO_PATCH_INFO_ADJUSTED_IID:
2203 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2205 case MONO_PATCH_INFO_CLASS_INIT:
2206 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2207 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2209 case MONO_PATCH_INFO_FIELD:
2210 case MONO_PATCH_INFO_SFLDA:
2211 encode_field_info (acfg, patch_info->data.field, p, &p);
2213 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2215 case MONO_PATCH_INFO_RGCTX_FETCH: {
2216 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2218 encode_method_ref (acfg, entry->method, p, &p);
2219 encode_value (entry->in_mrgctx, p, &p);
2220 encode_value (entry->info_type, p, &p);
2221 encode_value (entry->data->type, p, &p);
2222 encode_patch (acfg, entry->data, p, &p);
2225 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2226 case MONO_PATCH_INFO_MONITOR_ENTER:
2227 case MONO_PATCH_INFO_MONITOR_EXIT:
2230 g_warning ("unable to handle jump info %d", patch_info->type);
2231 g_assert_not_reached ();
2238 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2242 MonoJumpInfo *patch_info;
2244 encode_value (n_patches, p, &p);
2247 encode_value (first_got_offset, p, &p);
2249 for (pindex = 0; pindex < patches->len; ++pindex) {
2250 patch_info = g_ptr_array_index (patches, pindex);
2252 if (patch_info->type == MONO_PATCH_INFO_NONE)
2256 encode_value (patch_info->type, p, &p);
2257 if (mono_aot_is_shared_got_patch (patch_info)) {
2258 guint32 offset = get_got_offset (acfg, patch_info);
2259 encode_value (offset, p, &p);
2261 encode_patch (acfg, patch_info, p, &p);
2269 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2273 int pindex, buf_size, n_patches;
2277 MonoJumpInfo *patch_info;
2278 MonoMethodHeader *header;
2279 guint32 method_index;
2281 guint32 first_got_offset;
2283 method = cfg->orig_method;
2284 code = cfg->native_code;
2285 header = mono_method_get_header (method);
2287 method_index = get_method_index (acfg, method);
2289 /* Make the labels local */
2290 sprintf (symbol, ".Lm_%x_p", method_index);
2292 /* Sort relocations */
2293 patches = g_ptr_array_new ();
2294 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2295 g_ptr_array_add (patches, patch_info);
2296 g_ptr_array_sort (patches, compare_patches);
2298 first_got_offset = acfg->cfgs [method_index]->got_offset;
2300 /**********************/
2301 /* Encode method info */
2302 /**********************/
2304 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2305 p = buf = g_malloc (buf_size);
2307 if (mono_class_get_cctor (method->klass))
2308 encode_klass_ref (acfg, method->klass, p, &p);
2310 /* Not needed when loading the method */
2311 encode_value (0, p, &p);
2314 if (cfg->opt & MONO_OPT_SHARED) {
2315 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2316 for (l = cfg->ldstr_list; l; l = l->next) {
2317 encode_value ((long)l->data, p, &p);
2321 /* Used only in shared mode */
2322 g_assert (!cfg->ldstr_list);
2325 for (pindex = 0; pindex < patches->len; ++pindex) {
2326 patch_info = g_ptr_array_index (patches, pindex);
2328 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2329 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2330 patch_info->type = MONO_PATCH_INFO_NONE;
2335 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2336 /* Stored in a GOT slot initialized at module load time */
2337 patch_info->type = MONO_PATCH_INFO_NONE;
2341 if (is_plt_patch (patch_info)) {
2342 /* Calls are made through the PLT */
2343 patch_info->type = MONO_PATCH_INFO_NONE;
2351 g_assert (cfg->has_got_slots);
2353 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2355 acfg->stats.info_size += p - buf;
2357 /* Emit method info */
2359 emit_label (acfg, symbol);
2361 g_assert (p - buf < buf_size);
2362 emit_bytes (acfg, buf, p - buf);
2367 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2369 guint32 cache_index;
2372 /* Reuse the unwind module to canonize and store unwind info entries */
2373 cache_index = mono_cache_unwind_info (encoded, encoded_len);
2375 /* Use +/- 1 to distinguish 0s from missing entries */
2376 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2384 * It would be easier to use assembler symbols, but the caller needs an
2387 offset = acfg->unwind_info_offset;
2388 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2389 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2392 encode_value (encoded_len, p, &p);
2394 acfg->unwind_info_offset += encoded_len + (p - buf);
2400 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2403 int k, buf_size, method_index;
2404 guint32 debug_info_size;
2407 MonoMethodHeader *header;
2408 guint8 *p, *buf, *debug_info;
2409 MonoJitInfo *jinfo = cfg->jit_info;
2411 gboolean use_unwind_ops = FALSE;
2413 method = cfg->orig_method;
2414 code = cfg->native_code;
2415 header = mono_method_get_header (method);
2417 method_index = get_method_index (acfg, method);
2419 /* Make the labels local */
2420 sprintf (symbol, ".Le_%x_p", method_index);
2422 if (!acfg->aot_opts.nodebug) {
2423 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2426 debug_info_size = 0;
2429 buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2430 p = buf = g_malloc (buf_size);
2432 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2433 use_unwind_ops = cfg->unwind_ops != NULL;
2436 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2438 encode_value (jinfo->code_size, p, &p);
2439 encode_value (flags, p, &p);
2441 if (use_unwind_ops) {
2442 guint32 encoded_len;
2446 * This is a duplicate of the data in the .debug_frame section, but that
2447 * section cannot be accessed using the dl interface.
2449 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2450 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2453 encode_value (jinfo->used_regs, p, &p);
2456 /* Exception table */
2457 if (header->num_clauses) {
2458 for (k = 0; k < header->num_clauses; ++k) {
2459 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2461 encode_value (ei->exvar_offset, p, &p);
2463 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2464 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2466 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2467 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2468 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2472 if (jinfo->has_generic_jit_info) {
2473 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2475 encode_value (gi->has_this ? 1 : 0, p, &p);
2476 encode_value (gi->this_reg, p, &p);
2477 encode_value (gi->this_offset, p, &p);
2480 * Need to encode jinfo->method too, since it is not equal to 'method'
2481 * when using generic sharing.
2483 encode_method_ref (acfg, jinfo->method, p, &p);
2486 g_assert (debug_info_size < buf_size);
2488 encode_value (debug_info_size, p, &p);
2489 if (debug_info_size) {
2490 memcpy (p, debug_info, debug_info_size);
2491 p += debug_info_size;
2492 g_free (debug_info);
2495 acfg->stats.ex_info_size += p - buf;
2499 emit_label (acfg, symbol);
2501 g_assert (p - buf < buf_size);
2502 emit_bytes (acfg, buf, p - buf);
2507 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2509 MonoClass *klass = mono_class_get (acfg->image, token);
2513 gboolean no_special_static, cant_encode;
2514 gpointer iter = NULL;
2516 buf_size = 10240 + (klass->vtable_size * 16);
2517 p = buf = g_malloc (buf_size);
2521 mono_class_init (klass);
2523 mono_class_get_nested_types (klass, &iter);
2524 g_assert (klass->nested_classes_inited);
2526 mono_class_setup_vtable (klass);
2529 * Emit all the information which is required for creating vtables so
2530 * the runtime does not need to create the MonoMethod structures which
2531 * take up a lot of space.
2534 no_special_static = !mono_class_has_special_static_fields (klass);
2536 /* Check whenever we have enough info to encode the vtable */
2537 cant_encode = FALSE;
2538 for (i = 0; i < klass->vtable_size; ++i) {
2539 MonoMethod *cm = klass->vtable [i];
2541 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2545 if (klass->generic_container || cant_encode) {
2546 encode_value (-1, p, &p);
2548 encode_value (klass->vtable_size, p, &p);
2549 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);
2550 if (klass->has_cctor)
2551 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2552 if (klass->has_finalize)
2553 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2555 encode_value (klass->instance_size, p, &p);
2556 encode_value (mono_class_data_size (klass), p, &p);
2557 encode_value (klass->packing_size, p, &p);
2558 encode_value (klass->min_align, p, &p);
2560 for (i = 0; i < klass->vtable_size; ++i) {
2561 MonoMethod *cm = klass->vtable [i];
2564 encode_method_ref (acfg, cm, p, &p);
2566 encode_value (0, p, &p);
2570 acfg->stats.class_info_size += p - buf;
2573 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2574 emit_label (acfg, symbol);
2576 g_assert (p - buf < buf_size);
2577 emit_bytes (acfg, buf, p - buf);
2582 * Calls made from AOTed code are routed through a table of jumps similar to the
2583 * ELF PLT (Program Linkage Table). The differences are the following:
2584 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2585 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2586 * jumps. This means the jumps need to be patched when the address of the callee is
2587 * known. Initially the PLT entries jump to code which transfers control to the
2588 * AOT runtime through the first PLT entry.
2591 emit_plt (MonoAotCompile *acfg)
2597 sprintf (symbol, "plt");
2599 emit_section_change (acfg, ".text", 0);
2600 emit_global (acfg, symbol, TRUE);
2602 /* This section will be made read-write by the AOT loader */
2603 emit_alignment (acfg, mono_pagesize ());
2605 emit_alignment (acfg, 16);
2607 emit_label (acfg, symbol);
2609 for (i = 0; i < acfg->plt_offset; ++i) {
2612 sprintf (label, ".Lp_%d", i);
2613 emit_label (acfg, label);
2616 * The first plt entry is used to transfer code to the AOT loader.
2618 arch_emit_plt_entry (acfg, i);
2621 sprintf (symbol, "plt_end");
2622 emit_global (acfg, symbol, TRUE);
2623 emit_label (acfg, symbol);
2626 static G_GNUC_UNUSED void
2627 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
2628 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2632 MonoJumpInfo *patch_info;
2638 sprintf (symbol, "%s", name);
2640 emit_section_change (acfg, ".text", 0);
2641 emit_global (acfg, symbol, TRUE);
2642 emit_alignment (acfg, 16);
2643 emit_label (acfg, symbol);
2645 sprintf (symbol, ".Lnamed_%s", name);
2646 emit_label (acfg, symbol);
2649 * The code should access everything through the GOT, so we pass
2652 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2656 /* Sort relocations */
2657 patches = g_ptr_array_new ();
2658 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2659 g_ptr_array_add (patches, patch_info);
2660 g_ptr_array_sort (patches, compare_patches);
2662 buf_size = patches->len * 128 + 128;
2663 buf = g_malloc (buf_size);
2666 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2667 g_assert (p - buf < buf_size);
2669 sprintf (symbol, "%s_p", name);
2671 emit_section_change (acfg, ".text", 0);
2672 emit_global (acfg, symbol, FALSE);
2673 emit_label (acfg, symbol);
2675 emit_bytes (acfg, buf, p - buf);
2677 /* Emit debug info */
2681 sprintf (symbol, "%s", name);
2682 sprintf (symbol2, ".Lnamed_%s", name);
2685 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2690 emit_trampolines (MonoAotCompile *acfg)
2693 int i, tramp_got_offset;
2694 MonoAotTrampoline ntype;
2695 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2703 if (!acfg->aot_opts.full_aot)
2706 g_assert (acfg->image->assembly);
2708 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2709 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2710 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2712 * Emit the generic trampolines.
2714 * We could save some code by treating the generic trampolines as a wrapper
2715 * method, but that approach has its own complexities, so we choose the simpler
2718 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2719 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2721 /* Emit trampoline code */
2723 sprintf (symbol, "generic_trampoline_%d", tramp_type);
2725 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2728 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2729 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2730 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2731 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2732 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2733 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2734 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2737 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2738 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2740 /* Emit the exception related code pieces */
2741 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2742 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2743 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2744 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2745 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2746 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2747 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2748 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2749 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2750 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2751 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2752 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2754 #if defined(TARGET_AMD64)
2755 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2756 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2759 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2760 for (i = 0; i < 128; ++i) {
2763 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2764 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2765 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2766 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2768 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2769 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2770 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2771 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2775 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2779 /* delegate_invoke_impl trampolines */
2780 l = mono_arch_get_delegate_invoke_impls ();
2782 MonoAotTrampInfo *info = l->data;
2784 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
2790 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
2792 /* Emit trampolines which are numerous */
2795 * These include the following:
2796 * - specific trampolines
2797 * - static rgctx invoke trampolines
2799 * These trampolines have the same code, they are parameterized by GOT
2801 * They are defined in this file, in the arch_... routines instead of
2802 * in tramp-<ARCH>.c, since it is easier to do it this way.
2806 * When running in aot-only mode, we can't create specific trampolines at
2807 * runtime, so we create a few, and save them in the AOT file.
2808 * Normal trampolines embed their argument as a literal inside the
2809 * trampoline code, we can't do that here, so instead we embed an offset
2810 * which needs to be added to the trampoline address to get the address of
2811 * the GOT slot which contains the argument value.
2812 * The generated trampolines jump to the generic trampolines using another
2813 * GOT slot, which will be setup by the AOT loader to point to the
2814 * generic trampoline code of the given type.
2818 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2822 emit_section_change (acfg, ".text", 0);
2824 tramp_got_offset = acfg->got_offset;
2826 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
2828 case MONO_AOT_TRAMP_SPECIFIC:
2829 sprintf (symbol, "specific_trampolines");
2831 case MONO_AOT_TRAMP_STATIC_RGCTX:
2832 sprintf (symbol, "static_rgctx_trampolines");
2834 case MONO_AOT_TRAMP_IMT_THUNK:
2835 sprintf (symbol, "imt_thunks");
2838 g_assert_not_reached ();
2841 emit_global (acfg, symbol, TRUE);
2842 emit_alignment (acfg, 16);
2843 emit_label (acfg, symbol);
2845 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
2847 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
2851 case MONO_AOT_TRAMP_SPECIFIC:
2852 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
2853 tramp_got_offset += 2;
2855 case MONO_AOT_TRAMP_STATIC_RGCTX:
2856 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
2857 tramp_got_offset += 2;
2859 case MONO_AOT_TRAMP_IMT_THUNK:
2860 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
2861 tramp_got_offset += 1;
2864 g_assert_not_reached ();
2867 if (!acfg->trampoline_size [ntype]) {
2868 g_assert (tramp_size);
2869 acfg->trampoline_size [ntype] = tramp_size;
2874 /* Reserve some entries at the end of the GOT for our use */
2875 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
2878 /* Unbox trampolines */
2879 for (i = 0; i < acfg->methods->len; ++i) {
2880 MonoMethod *method = g_ptr_array_index (acfg->methods, i);
2882 char call_target [256];
2884 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2885 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2888 if (!method->wrapper_type && !method->is_inflated) {
2889 g_assert (method->token);
2890 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2892 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2895 emit_section_change (acfg, ".text", 0);
2896 emit_global (acfg, symbol, TRUE);
2897 emit_label (acfg, symbol);
2899 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2901 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2904 acfg->got_offset += acfg->num_trampoline_got_entries;
2908 str_begins_with (const char *str1, const char *str2)
2910 int len = strlen (str2);
2911 return strncmp (str1, str2, len) == 0;
2915 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2917 gchar **args, **ptr;
2919 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2920 for (ptr = args; ptr && *ptr; ptr ++) {
2921 const char *arg = *ptr;
2923 if (str_begins_with (arg, "outfile=")) {
2924 opts->outfile = g_strdup (arg + strlen ("outfile="));
2925 } else if (str_begins_with (arg, "save-temps")) {
2926 opts->save_temps = TRUE;
2927 } else if (str_begins_with (arg, "keep-temps")) {
2928 opts->save_temps = TRUE;
2929 } else if (str_begins_with (arg, "write-symbols")) {
2930 opts->write_symbols = TRUE;
2931 } else if (str_begins_with (arg, "metadata-only")) {
2932 opts->metadata_only = TRUE;
2933 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2934 opts->bind_to_runtime_version = TRUE;
2935 } else if (str_begins_with (arg, "full")) {
2936 opts->full_aot = TRUE;
2937 } else if (str_begins_with (arg, "threads=")) {
2938 opts->nthreads = atoi (arg + strlen ("threads="));
2939 } else if (str_begins_with (arg, "static")) {
2940 opts->static_link = TRUE;
2941 opts->no_dlsym = TRUE;
2942 } else if (str_begins_with (arg, "asmonly")) {
2943 opts->asm_only = TRUE;
2944 } else if (str_begins_with (arg, "asmwriter")) {
2945 opts->asm_writer = TRUE;
2946 } else if (str_begins_with (arg, "nodebug")) {
2947 opts->nodebug = TRUE;
2948 } else if (str_begins_with (arg, "ntrampolines=")) {
2949 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
2951 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2960 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2962 MonoMethod *method = (MonoMethod*)key;
2963 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2964 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2965 MonoAotCompile *acfg = user_data;
2967 new_ji->image = ji->image;
2968 new_ji->token = ji->token;
2969 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2973 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2975 if (klass->type_token)
2977 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2980 return can_encode_class (acfg, klass->element_class);
2985 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2987 switch (patch_info->type) {
2988 case MONO_PATCH_INFO_METHOD:
2989 case MONO_PATCH_INFO_METHODCONST: {
2990 MonoMethod *method = patch_info->data.method;
2992 if (method->wrapper_type) {
2993 switch (method->wrapper_type) {
2994 case MONO_WRAPPER_NONE:
2995 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2996 case MONO_WRAPPER_XDOMAIN_INVOKE:
2997 case MONO_WRAPPER_STFLD:
2998 case MONO_WRAPPER_LDFLD:
2999 case MONO_WRAPPER_LDFLDA:
3000 case MONO_WRAPPER_LDFLD_REMOTE:
3001 case MONO_WRAPPER_STFLD_REMOTE:
3002 case MONO_WRAPPER_STELEMREF:
3003 case MONO_WRAPPER_ISINST:
3004 case MONO_WRAPPER_PROXY_ISINST:
3005 case MONO_WRAPPER_ALLOC:
3006 case MONO_WRAPPER_REMOTING_INVOKE:
3007 case MONO_WRAPPER_UNKNOWN:
3009 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
3010 g_assert (!acfg->aot_opts.full_aot);
3013 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3017 if (!method->token) {
3018 /* The method is part of a constructed type like Int[,].Set (). */
3019 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3020 if (method->klass->rank)
3028 case MONO_PATCH_INFO_VTABLE:
3029 case MONO_PATCH_INFO_CLASS_INIT:
3030 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3031 case MONO_PATCH_INFO_CLASS:
3032 case MONO_PATCH_INFO_IID:
3033 case MONO_PATCH_INFO_ADJUSTED_IID:
3034 if (!can_encode_class (acfg, patch_info->data.klass)) {
3035 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3039 case MONO_PATCH_INFO_RGCTX_FETCH: {
3040 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3042 if (!can_encode_patch (acfg, entry->data))
3054 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3059 * AOT compile a given method.
3060 * This function might be called by multiple threads, so it must be thread-safe.
3063 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3066 MonoJumpInfo *patch_info;
3069 MonoMethod *wrapped;
3071 if (acfg->aot_opts.metadata_only)
3074 mono_acfg_lock (acfg);
3075 index = get_method_index (acfg, method);
3076 mono_acfg_unlock (acfg);
3078 /* fixme: maybe we can also precompile wrapper methods */
3079 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3080 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3081 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3082 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3086 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3089 wrapped = mono_marshal_method_from_wrapper (method);
3090 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3091 // FIXME: The wrapper should be generic too, but it is not
3094 InterlockedIncrement (&acfg->stats.mcount);
3097 if (method->is_generic || method->klass->generic_container) {
3098 InterlockedIncrement (&acfg->stats.genericcount);
3103 //acfg->aot_opts.print_skipped_methods = TRUE;
3106 * Since these methods are the only ones which are compiled with
3107 * AOT support, and they are not used by runtime startup/shutdown code,
3108 * the runtime will not see AOT methods during AOT compilation,so it
3109 * does not need to support them by creating a fake GOT etc.
3111 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3112 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3113 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3114 InterlockedIncrement (&acfg->stats.genericcount);
3117 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3118 /* Let the exception happen at runtime */
3122 if (cfg->disable_aot) {
3123 if (acfg->aot_opts.print_skipped_methods)
3124 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3125 InterlockedIncrement (&acfg->stats.ocount);
3126 mono_destroy_compile (cfg);
3130 /* Nullify patches which need no aot processing */
3131 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3132 switch (patch_info->type) {
3133 case MONO_PATCH_INFO_LABEL:
3134 case MONO_PATCH_INFO_BB:
3135 patch_info->type = MONO_PATCH_INFO_NONE;
3142 /* Collect method->token associations from the cfg */
3143 mono_acfg_lock (acfg);
3144 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3145 mono_acfg_unlock (acfg);
3148 * Check for absolute addresses.
3151 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3152 switch (patch_info->type) {
3153 case MONO_PATCH_INFO_ABS:
3154 /* unable to handle this */
3163 if (acfg->aot_opts.print_skipped_methods)
3164 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3165 InterlockedIncrement (&acfg->stats.abscount);
3166 mono_destroy_compile (cfg);
3170 /* Lock for the rest of the code */
3171 mono_acfg_lock (acfg);
3174 * Check for methods/klasses we can't encode.
3177 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3178 if (!can_encode_patch (acfg, patch_info))
3183 if (acfg->aot_opts.print_skipped_methods)
3184 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3185 acfg->stats.ocount++;
3186 mono_destroy_compile (cfg);
3187 mono_acfg_unlock (acfg);
3191 /* Adds generic instances referenced by this method */
3192 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3193 switch (patch_info->type) {
3194 case MONO_PATCH_INFO_METHOD: {
3195 MonoMethod *m = patch_info->data.method;
3196 if (m->is_inflated) {
3197 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3198 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3199 !method_has_type_vars (m)) {
3200 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3201 if (acfg->aot_opts.full_aot)
3202 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3204 add_extra_method (acfg, m);
3207 add_generic_class (acfg, m->klass);
3216 /* Determine whenever the method has GOT slots */
3217 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3218 switch (patch_info->type) {
3219 case MONO_PATCH_INFO_GOT_OFFSET:
3220 case MONO_PATCH_INFO_NONE:
3222 case MONO_PATCH_INFO_IMAGE:
3223 /* The assembly is stored in GOT slot 0 */
3224 if (patch_info->data.image != acfg->image)
3225 cfg->has_got_slots = TRUE;
3228 if (!is_plt_patch (patch_info))
3229 cfg->has_got_slots = TRUE;
3234 if (!cfg->has_got_slots)
3235 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3237 /* Make a copy of the patch info which is in the mempool */
3239 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3241 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3242 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3245 patches = new_patch_info;
3247 patches_end->next = new_patch_info;
3248 patches_end = new_patch_info;
3250 cfg->patch_info = patches;
3252 /* Make a copy of the unwind info */
3254 GSList *l, *unwind_ops;
3258 for (l = cfg->unwind_ops; l; l = l->next) {
3259 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3260 memcpy (op, l->data, sizeof (MonoUnwindOp));
3261 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3263 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3265 /* Make a copy of the argument/local info */
3267 MonoInst **args, **locals;
3268 MonoMethodSignature *sig;
3269 MonoMethodHeader *header;
3272 sig = mono_method_signature (method);
3273 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3274 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3275 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3276 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3280 header = mono_method_get_header (method);
3281 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3282 for (i = 0; i < header->num_locals; ++i) {
3283 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3284 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3286 cfg->locals = locals;
3289 /* Free some fields used by cfg to conserve memory */
3290 mono_mempool_destroy (cfg->mempool);
3291 cfg->mempool = NULL;
3292 g_free (cfg->varinfo);
3293 cfg->varinfo = NULL;
3297 mono_regstate_free (cfg->rs);
3301 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3303 while (index >= acfg->cfgs_size) {
3304 MonoCompile **new_cfgs;
3307 new_size = acfg->cfgs_size * 2;
3308 new_cfgs = g_new0 (MonoCompile*, new_size);
3309 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3310 g_free (acfg->cfgs);
3311 acfg->cfgs = new_cfgs;
3312 acfg->cfgs_size = new_size;
3314 acfg->cfgs [index] = cfg;
3316 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3319 if (cfg->orig_method->wrapper_type)
3320 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3323 mono_acfg_unlock (acfg);
3325 InterlockedIncrement (&acfg->stats.ccount);
3329 compile_thread_main (gpointer *user_data)
3331 MonoDomain *domain = user_data [0];
3332 MonoAotCompile *acfg = user_data [1];
3333 GPtrArray *methods = user_data [2];
3336 mono_thread_attach (domain);
3338 for (i = 0; i < methods->len; ++i)
3339 compile_method (acfg, g_ptr_array_index (methods, i));
3343 load_profile_files (MonoAotCompile *acfg)
3347 int file_index, res, method_index, i;
3354 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);
3356 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3361 infile = fopen (tmp, "r");
3364 printf ("Using profile data file '%s'\n", tmp);
3369 res = fscanf (infile, "%32s\n", ver);
3370 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3371 printf ("Profile file has wrong version or invalid.\n");
3377 res = fscanf (infile, "%d\n", &token);
3381 method_index = mono_metadata_token_index (token) - 1;
3383 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3384 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3389 /* Add missing methods */
3391 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3392 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3393 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3395 unordered = g_list_reverse (unordered);
3396 if (acfg->method_order)
3397 g_list_last (acfg->method_order)->next = unordered;
3399 acfg->method_order = unordered;
3405 * Collect all patches which have shared GOT entries and alloc entries for them. The
3406 * rest will get entries allocated during emit_code ().
3409 alloc_got_slots (MonoAotCompile *acfg)
3415 /* Slot 0 is reserved for the address of the current assembly */
3416 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3417 ji->type = MONO_PATCH_INFO_IMAGE;
3418 ji->data.image = acfg->image;
3420 get_shared_got_offset (acfg, ji);
3422 for (l = acfg->method_order; l != NULL; l = l->next) {
3423 i = GPOINTER_TO_UINT (l->data);
3425 if (acfg->cfgs [i]) {
3426 MonoCompile *cfg = acfg->cfgs [i];
3428 for (ji = cfg->patch_info; ji; ji = ji->next) {
3429 if (mono_aot_is_shared_got_patch (ji))
3430 get_shared_got_offset (acfg, ji);
3437 emit_code (MonoAotCompile *acfg)
3443 sprintf (symbol, "methods");
3444 emit_section_change (acfg, ".text", 0);
3445 emit_global (acfg, symbol, TRUE);
3446 emit_alignment (acfg, 8);
3447 emit_label (acfg, symbol);
3450 * Emit some padding so the local symbol for the first method doesn't have the
3451 * same address as 'methods'.
3453 emit_zero_bytes (acfg, 16);
3455 for (l = acfg->method_order; l != NULL; l = l->next) {
3456 i = GPOINTER_TO_UINT (l->data);
3459 emit_method_code (acfg, acfg->cfgs [i]);
3462 sprintf (symbol, "methods_end");
3463 emit_section_change (acfg, ".text", 0);
3464 emit_global (acfg, symbol, FALSE);
3465 emit_alignment (acfg, 8);
3466 emit_label (acfg, symbol);
3468 sprintf (symbol, "method_offsets");
3469 emit_section_change (acfg, ".text", 1);
3470 emit_global (acfg, symbol, FALSE);
3471 emit_alignment (acfg, 8);
3472 emit_label (acfg, symbol);
3474 for (i = 0; i < acfg->nmethods; ++i) {
3475 if (acfg->cfgs [i]) {
3476 sprintf (symbol, ".Lm_%x", i);
3477 emit_symbol_diff (acfg, symbol, "methods", 0);
3479 emit_int32 (acfg, 0xffffffff);
3486 emit_info (MonoAotCompile *acfg)
3492 /* Emit method info */
3493 sprintf (symbol, "method_info");
3494 emit_section_change (acfg, ".text", 1);
3495 emit_global (acfg, symbol, FALSE);
3496 emit_alignment (acfg, 8);
3497 emit_label (acfg, symbol);
3499 /* To reduce size of generated assembly code */
3500 sprintf (symbol, "mi");
3501 emit_label (acfg, symbol);
3503 for (l = acfg->method_order; l != NULL; l = l->next) {
3504 i = GPOINTER_TO_UINT (l->data);
3507 emit_method_info (acfg, acfg->cfgs [i]);
3510 sprintf (symbol, "method_info_offsets");
3511 emit_section_change (acfg, ".text", 1);
3512 emit_global (acfg, symbol, FALSE);
3513 emit_alignment (acfg, 8);
3514 emit_label (acfg, symbol);
3516 for (i = 0; i < acfg->nmethods; ++i) {
3517 if (acfg->cfgs [i]) {
3518 sprintf (symbol, ".Lm_%x_p", i);
3519 emit_symbol_diff (acfg, symbol, "mi", 0);
3521 emit_int32 (acfg, 0);
3527 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
3530 * mono_aot_str_hash:
3532 * Hash function for strings which we use to hash strings for things which are
3533 * saved in the AOT image, since g_str_hash () can change.
3536 mono_aot_str_hash (gconstpointer v1)
3538 /* Same as g_str_hash () in glib */
3539 char *p = (char *) v1;
3544 hash = (hash << 5) - hash + *p;
3550 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
3551 #define mix(a,b,c) { \
3552 a -= c; a ^= rot(c, 4); c += b; \
3553 b -= a; b ^= rot(a, 6); a += c; \
3554 c -= b; c ^= rot(b, 8); b += a; \
3555 a -= c; a ^= rot(c,16); c += b; \
3556 b -= a; b ^= rot(a,19); a += c; \
3557 c -= b; c ^= rot(b, 4); b += a; \
3559 #define final(a,b,c) { \
3560 c ^= b; c -= rot(b,14); \
3561 a ^= c; a -= rot(c,11); \
3562 b ^= a; b -= rot(a,25); \
3563 c ^= b; c -= rot(b,16); \
3564 a ^= c; a -= rot(c,4); \
3565 b ^= a; b -= rot(a,14); \
3566 c ^= b; c -= rot(b,24); \
3570 mono_aot_type_hash (MonoType *t1)
3572 guint hash = t1->type;
3574 hash |= t1->byref << 6; /* do not collide with t1->type values */
3576 case MONO_TYPE_VALUETYPE:
3577 case MONO_TYPE_CLASS:
3578 case MONO_TYPE_SZARRAY:
3579 /* check if the distribution is good enough */
3580 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
3582 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
3583 case MONO_TYPE_ARRAY:
3584 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
3585 case MONO_TYPE_GENERICINST:
3586 return ((hash << 5) - hash) ^ 0;
3592 * mono_aot_method_hash:
3594 * Return a hash code for methods which only depends on metadata.
3597 mono_aot_method_hash (MonoMethod *method)
3599 MonoMethodSignature *sig;
3603 guint32 *hashes_start, *hashes;
3606 /* Similar to the hash in mono_method_get_imt_slot () */
3608 sig = mono_method_signature (method);
3610 hashes_count = sig->param_count + 5;
3611 hashes_start = malloc (hashes_count * sizeof (guint32));
3612 hashes = hashes_start;
3614 /* Some wrappers are assigned to random classes */
3615 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3616 klass = method->klass;
3618 klass = mono_defaults.object_class;
3620 if (!method->wrapper_type) {
3621 char *full_name = mono_type_full_name (&klass->byval_arg);
3623 hashes [0] = mono_aot_str_hash (full_name);
3627 hashes [0] = mono_aot_str_hash (klass->name);
3628 hashes [1] = mono_aot_str_hash (klass->name_space);
3630 hashes [2] = mono_aot_str_hash (method->name);
3631 hashes [3] = method->wrapper_type;
3632 hashes [4] = mono_aot_type_hash (sig->ret);
3633 for (i = 0; i < sig->param_count; i++) {
3634 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
3637 /* Setup internal state */
3638 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
3640 /* Handle most of the hashes */
3641 while (hashes_count > 3) {
3650 /* Handle the last 3 hashes (all the case statements fall through) */
3651 switch (hashes_count) {
3652 case 3 : c += hashes [2];
3653 case 2 : b += hashes [1];
3654 case 1 : a += hashes [0];
3656 case 0: /* nothing left to add */
3660 free (hashes_start);
3669 * mono_aot_wrapper_name:
3671 * Return a string which uniqely identifies the given wrapper method.
3674 mono_aot_wrapper_name (MonoMethod *method)
3676 char *name, *tmpsig, *klass_desc;
3678 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3680 switch (method->wrapper_type) {
3681 case MONO_WRAPPER_RUNTIME_INVOKE:
3682 case MONO_WRAPPER_DELEGATE_INVOKE:
3683 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3684 case MONO_WRAPPER_DELEGATE_END_INVOKE:
3685 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
3686 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
3689 klass_desc = mono_type_full_name (&method->klass->byval_arg);
3691 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
3701 * mono_aot_tramp_info_create:
3703 * Create a MonoAotTrampInfo structure from the arguments.
3706 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
3708 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
3710 info->name = (char*)name;
3712 info->code_size = code_size;
3718 * mono_is_shared_got_patch:
3720 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
3724 mono_aot_is_shared_got_patch (MonoJumpInfo *patch_info)
3726 switch (patch_info->type) {
3727 case MONO_PATCH_INFO_VTABLE:
3728 case MONO_PATCH_INFO_CLASS:
3729 case MONO_PATCH_INFO_IID:
3730 case MONO_PATCH_INFO_ADJUSTED_IID:
3731 case MONO_PATCH_INFO_FIELD:
3732 case MONO_PATCH_INFO_SFLDA:
3733 case MONO_PATCH_INFO_DECLSEC:
3734 case MONO_PATCH_INFO_LDTOKEN:
3735 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3736 case MONO_PATCH_INFO_RVA:
3737 case MONO_PATCH_INFO_METHODCONST:
3738 case MONO_PATCH_INFO_IMAGE:
3745 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
3747 typedef struct HashEntry {
3748 guint32 key, value, index;
3749 struct HashEntry *next;
3753 * emit_extra_methods:
3755 * Emit methods which are not in the METHOD table, like wrappers.
3758 emit_extra_methods (MonoAotCompile *acfg)
3760 int i, table_size, buf_size;
3763 guint32 *info_offsets;
3766 HashEntry *entry, *new_entry;
3767 int nmethods, max_chain_length;
3770 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3772 buf_size = acfg->extra_methods->len * 256 + 256;
3773 p = buf = g_malloc (buf_size);
3775 /* Encode method info */
3777 /* So offsets are > 0 */
3780 for (i = 0; i < acfg->extra_methods->len; ++i) {
3781 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3782 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3789 info_offsets [i] = p - buf;
3792 if (method->wrapper_type) {
3794 * We encode some wrappers using their name, since encoding them
3795 * directly would be difficult. This also avoids creating the wrapper
3796 * methods at runtime, since they are not needed anyway.
3798 switch (method->wrapper_type) {
3799 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3800 case MONO_WRAPPER_SYNCHRONIZED:
3801 /* encode_method_ref () can handle these */
3803 case MONO_WRAPPER_RUNTIME_INVOKE:
3804 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
3805 /* Direct wrapper, encode normally */
3809 name = mono_aot_wrapper_name (method);
3815 encode_value (1, p, &p);
3816 encode_value (method->wrapper_type, p, &p);
3817 strcpy ((char*)p, name);
3818 p += strlen (name ) + 1;
3821 encode_value (0, p, &p);
3822 encode_method_ref (acfg, method, p, &p);
3825 g_assert ((p - buf) < buf_size);
3828 g_assert ((p - buf) < buf_size);
3830 /* Emit method info */
3831 sprintf (symbol, "extra_method_info");
3832 emit_section_change (acfg, ".text", 1);
3833 emit_global (acfg, symbol, FALSE);
3834 emit_alignment (acfg, 8);
3835 emit_label (acfg, symbol);
3837 emit_bytes (acfg, buf, p - buf);
3842 * Construct a chained hash table for mapping indexes in extra_method_info to
3845 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3846 table = g_ptr_array_sized_new (table_size);
3847 for (i = 0; i < table_size; ++i)
3848 g_ptr_array_add (table, NULL);
3849 chain_lengths = g_new0 (int, table_size);
3850 max_chain_length = 0;
3851 for (i = 0; i < acfg->extra_methods->len; ++i) {
3852 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3853 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3859 key = info_offsets [i];
3860 value = get_method_index (acfg, method);
3862 hash = mono_aot_method_hash (method) % table_size;
3864 chain_lengths [hash] ++;
3865 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3867 /* FIXME: Allocate from the mempool */
3868 new_entry = g_new0 (HashEntry, 1);
3869 new_entry->key = key;
3870 new_entry->value = value;
3872 entry = g_ptr_array_index (table, hash);
3873 if (entry == NULL) {
3874 new_entry->index = hash;
3875 g_ptr_array_index (table, hash) = new_entry;
3878 entry = entry->next;
3880 entry->next = new_entry;
3881 new_entry->index = table->len;
3882 g_ptr_array_add (table, new_entry);
3886 //printf ("MAX: %d\n", max_chain_length);
3888 /* Emit the table */
3889 sprintf (symbol, "extra_method_table");
3890 emit_section_change (acfg, ".text", 0);
3891 emit_global (acfg, symbol, FALSE);
3892 emit_alignment (acfg, 8);
3893 emit_label (acfg, symbol);
3895 g_assert (table_size < 65000);
3896 emit_int32 (acfg, table_size);
3897 g_assert (table->len < 65000);
3898 for (i = 0; i < table->len; ++i) {
3899 HashEntry *entry = g_ptr_array_index (table, i);
3901 if (entry == NULL) {
3902 emit_int32 (acfg, 0);
3903 emit_int32 (acfg, 0);
3904 emit_int32 (acfg, 0);
3906 g_assert (entry->key > 0);
3907 emit_int32 (acfg, entry->key);
3908 emit_int32 (acfg, entry->value);
3910 emit_int32 (acfg, entry->next->index);
3912 emit_int32 (acfg, 0);
3917 * Emit a table reverse mapping method indexes to their index in extra_method_info.
3918 * This is used by mono_aot_find_jit_info ().
3920 sprintf (symbol, "extra_method_info_offsets");
3921 emit_section_change (acfg, ".text", 0);
3922 emit_global (acfg, symbol, FALSE);
3923 emit_alignment (acfg, 8);
3924 emit_label (acfg, symbol);
3926 emit_int32 (acfg, acfg->extra_methods->len);
3927 for (i = 0; i < acfg->extra_methods->len; ++i) {
3928 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3930 emit_int32 (acfg, get_method_index (acfg, method));
3931 emit_int32 (acfg, info_offsets [i]);
3936 emit_method_order (MonoAotCompile *acfg)
3942 sprintf (symbol, "method_order");
3943 emit_section_change (acfg, ".text", 1);
3944 emit_global (acfg, symbol, FALSE);
3945 emit_alignment (acfg, 8);
3946 emit_label (acfg, symbol);
3948 /* First emit an index table */
3951 for (l = acfg->method_order; l != NULL; l = l->next) {
3952 i = GPOINTER_TO_UINT (l->data);
3954 if (acfg->cfgs [i]) {
3955 if ((index % 1024) == 0) {
3956 emit_int32 (acfg, i);
3964 emit_int32 (acfg, 0xffffff);
3966 /* Then emit the whole method order */
3967 for (l = acfg->method_order; l != NULL; l = l->next) {
3968 i = GPOINTER_TO_UINT (l->data);
3970 if (acfg->cfgs [i]) {
3971 emit_int32 (acfg, i);
3976 sprintf (symbol, "method_order_end");
3977 emit_section_change (acfg, ".text", 1);
3978 emit_global (acfg, symbol, FALSE);
3979 emit_label (acfg, symbol);
3983 emit_exception_info (MonoAotCompile *acfg)
3988 sprintf (symbol, "ex_info");
3989 emit_section_change (acfg, ".text", 1);
3990 emit_global (acfg, symbol, FALSE);
3991 emit_alignment (acfg, 8);
3992 emit_label (acfg, symbol);
3994 /* To reduce size of generated assembly */
3995 sprintf (symbol, "ex");
3996 emit_label (acfg, symbol);
3998 for (i = 0; i < acfg->nmethods; ++i) {
4000 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4003 sprintf (symbol, "ex_info_offsets");
4004 emit_section_change (acfg, ".text", 1);
4005 emit_global (acfg, symbol, FALSE);
4006 emit_alignment (acfg, 8);
4007 emit_label (acfg, symbol);
4009 for (i = 0; i < acfg->nmethods; ++i) {
4010 if (acfg->cfgs [i]) {
4011 sprintf (symbol, ".Le_%x_p", i);
4012 emit_symbol_diff (acfg, symbol, "ex", 0);
4014 emit_int32 (acfg, 0);
4021 emit_unwind_info (MonoAotCompile *acfg)
4027 * The unwind info contains a lot of duplicates so we emit each unique
4028 * entry once, and only store the offset from the start of the table in the
4032 sprintf (symbol, "unwind_info");
4033 emit_section_change (acfg, ".text", 1);
4034 emit_alignment (acfg, 8);
4035 emit_label (acfg, symbol);
4036 emit_global (acfg, symbol, FALSE);
4038 for (i = 0; i < acfg->unwind_ops->len; ++i) {
4039 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4040 guint8 *unwind_info;
4041 guint32 unwind_info_len;
4045 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4048 encode_value (unwind_info_len, p, &p);
4049 emit_bytes (acfg, buf, p - buf);
4050 emit_bytes (acfg, unwind_info, unwind_info_len);
4052 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4057 emit_class_info (MonoAotCompile *acfg)
4062 sprintf (symbol, "class_info");
4063 emit_section_change (acfg, ".text", 1);
4064 emit_global (acfg, symbol, FALSE);
4065 emit_alignment (acfg, 8);
4066 emit_label (acfg, symbol);
4068 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4069 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4071 sprintf (symbol, "class_info_offsets");
4072 emit_section_change (acfg, ".text", 1);
4073 emit_global (acfg, symbol, FALSE);
4074 emit_alignment (acfg, 8);
4075 emit_label (acfg, symbol);
4077 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4078 sprintf (symbol, ".LK_I_%x", i);
4079 emit_symbol_diff (acfg, symbol, "class_info", 0);
4084 typedef struct ClassNameTableEntry {
4085 guint32 token, index;
4086 struct ClassNameTableEntry *next;
4087 } ClassNameTableEntry;
4090 emit_class_name_table (MonoAotCompile *acfg)
4093 guint32 token, hash;
4098 ClassNameTableEntry *entry, *new_entry;
4101 * Construct a chained hash table for mapping class names to typedef tokens.
4103 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4104 table = g_ptr_array_sized_new (table_size);
4105 for (i = 0; i < table_size; ++i)
4106 g_ptr_array_add (table, NULL);
4107 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4108 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4109 klass = mono_class_get (acfg->image, token);
4110 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4111 hash = mono_aot_str_hash (full_name) % table_size;
4114 /* FIXME: Allocate from the mempool */
4115 new_entry = g_new0 (ClassNameTableEntry, 1);
4116 new_entry->token = token;
4118 entry = g_ptr_array_index (table, hash);
4119 if (entry == NULL) {
4120 new_entry->index = hash;
4121 g_ptr_array_index (table, hash) = new_entry;
4124 entry = entry->next;
4126 entry->next = new_entry;
4127 new_entry->index = table->len;
4128 g_ptr_array_add (table, new_entry);
4132 /* Emit the table */
4133 sprintf (symbol, "class_name_table");
4134 emit_section_change (acfg, ".text", 0);
4135 emit_global (acfg, symbol, FALSE);
4136 emit_alignment (acfg, 8);
4137 emit_label (acfg, symbol);
4139 /* FIXME: Optimize memory usage */
4140 g_assert (table_size < 65000);
4141 emit_int16 (acfg, table_size);
4142 g_assert (table->len < 65000);
4143 for (i = 0; i < table->len; ++i) {
4144 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4146 if (entry == NULL) {
4147 emit_int16 (acfg, 0);
4148 emit_int16 (acfg, 0);
4150 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4152 emit_int16 (acfg, entry->next->index);
4154 emit_int16 (acfg, 0);
4160 emit_image_table (MonoAotCompile *acfg)
4166 * The image table is small but referenced in a lot of places.
4167 * So we emit it at once, and reference its elements by an index.
4170 sprintf (symbol, "mono_image_table");
4171 emit_section_change (acfg, ".text", 1);
4172 emit_global (acfg, symbol, FALSE);
4173 emit_alignment (acfg, 8);
4174 emit_label (acfg, symbol);
4176 emit_int32 (acfg, acfg->image_table->len);
4177 for (i = 0; i < acfg->image_table->len; i++) {
4178 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4179 MonoAssemblyName *aname = &image->assembly->aname;
4181 /* FIXME: Support multi-module assemblies */
4182 g_assert (image->assembly->image == image);
4184 emit_string (acfg, image->assembly_name);
4185 emit_string (acfg, image->guid);
4186 emit_string (acfg, aname->culture ? aname->culture : "");
4187 emit_string (acfg, (const char*)aname->public_key_token);
4189 emit_alignment (acfg, 8);
4190 emit_int32 (acfg, aname->flags);
4191 emit_int32 (acfg, aname->major);
4192 emit_int32 (acfg, aname->minor);
4193 emit_int32 (acfg, aname->build);
4194 emit_int32 (acfg, aname->revision);
4199 emit_got_info (MonoAotCompile *acfg)
4202 int i, first_plt_got_patch, buf_size;
4204 guint32 *got_info_offsets;
4206 /* Add the patches needed by the PLT to the GOT */
4207 acfg->plt_got_offset_base = acfg->got_offset;
4208 first_plt_got_patch = acfg->shared_patches->len;
4209 for (i = 1; i < acfg->plt_offset; ++i) {
4210 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4212 g_ptr_array_add (acfg->shared_patches, patch_info);
4215 acfg->got_offset += acfg->plt_offset;
4219 * - optimize offsets table.
4220 * - reduce number of exported symbols.
4221 * - emit info for a klass only once.
4222 * - determine when a method uses a GOT slot which is guaranteed to be already
4224 * - clean up and document the code.
4225 * - use String.Empty in class libs.
4228 /* Encode info required to decode shared GOT entries */
4229 buf_size = acfg->shared_patches->len * 64;
4230 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4231 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4232 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4233 for (i = 0; i < acfg->shared_patches->len; ++i) {
4234 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4236 got_info_offsets [i] = p - buf;
4237 /* No need to encode the patch type for non-PLT patches */
4238 if (i >= first_plt_got_patch) {
4239 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4240 encode_value (ji->type, p, &p);
4242 encode_patch (acfg, ji, p, &p);
4245 g_assert (p - buf <= buf_size);
4247 acfg->stats.got_info_size = p - buf;
4249 /* Emit got_info table */
4250 sprintf (symbol, "got_info");
4251 emit_section_change (acfg, ".text", 1);
4252 emit_global (acfg, symbol, FALSE);
4253 emit_alignment (acfg, 8);
4254 emit_label (acfg, symbol);
4256 emit_bytes (acfg, buf, p - buf);
4258 /* Emit got_info_offsets table */
4259 sprintf (symbol, "got_info_offsets");
4260 emit_section_change (acfg, ".text", 1);
4261 emit_global (acfg, symbol, FALSE);
4262 emit_alignment (acfg, 8);
4263 emit_label (acfg, symbol);
4265 for (i = 0; i < acfg->shared_patches->len; ++i)
4266 emit_int32 (acfg, got_info_offsets [i]);
4268 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4272 emit_got (MonoAotCompile *acfg)
4276 /* Don't make GOT global so accesses to it don't need relocations */
4277 sprintf (symbol, acfg->got_symbol);
4278 emit_section_change (acfg, ".bss", 0);
4279 emit_alignment (acfg, 8);
4280 emit_local_symbol (acfg, symbol, "got_end", FALSE);
4281 emit_label (acfg, symbol);
4282 if (acfg->got_offset > 0)
4283 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4285 sprintf (symbol, "got_end");
4286 emit_label (acfg, symbol);
4288 sprintf (symbol, "mono_aot_got_addr");
4289 emit_section_change (acfg, ".data", 0);
4290 emit_global (acfg, symbol, FALSE);
4291 emit_alignment (acfg, 8);
4292 emit_label (acfg, symbol);
4293 emit_pointer (acfg, acfg->got_symbol);
4297 emit_globals (MonoAotCompile *acfg)
4302 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4304 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4306 opts_str = g_strdup_printf ("%d", acfg->opts);
4307 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4310 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4312 if (acfg->aot_opts.bind_to_runtime_version) {
4313 build_info = mono_get_runtime_build_info ();
4314 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4315 g_free (build_info);
4317 emit_string_symbol (acfg, "mono_runtime_version", "");
4321 * When static linking, we emit a global which will point to the symbol table.
4323 if (acfg->aot_opts.static_link) {
4328 /* Emit a string holding the assembly name */
4329 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4331 /* Emit the names */
4332 for (i = 0; i < acfg->globals->len; ++i) {
4333 char *name = g_ptr_array_index (acfg->globals, i);
4335 sprintf (symbol, "name_%d", i);
4336 emit_section_change (acfg, ".text", 1);
4337 emit_label (acfg, symbol);
4338 emit_string (acfg, name);
4341 /* Emit the globals table */
4342 sprintf (symbol, "globals");
4343 emit_section_change (acfg, ".data", 0);
4344 /* This is not a global, since it is accessed by the init function */
4345 emit_alignment (acfg, 8);
4346 emit_label (acfg, symbol);
4348 for (i = 0; i < acfg->globals->len; ++i) {
4349 char *name = g_ptr_array_index (acfg->globals, i);
4351 sprintf (symbol, "name_%d", i);
4352 emit_pointer (acfg, symbol);
4354 sprintf (symbol, "%s", name);
4355 emit_pointer (acfg, symbol);
4357 /* Null terminate the table */
4358 emit_int32 (acfg, 0);
4359 emit_int32 (acfg, 0);
4362 * Emit a global symbol which can be passed by an embedding app to
4363 * mono_aot_register_module ().
4365 #if defined(__MACH__)
4366 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4368 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4371 /* Get rid of characters which cannot occur in symbols */
4373 for (p = symbol; *p; ++p) {
4374 if (!(isalnum (*p) || *p == '_'))
4377 acfg->static_linking_symbol = g_strdup (symbol);
4378 emit_global_inner (acfg, symbol, FALSE);
4379 emit_alignment (acfg, 8);
4380 emit_label (acfg, symbol);
4381 emit_pointer (acfg, "globals");
4386 emit_mem_end (MonoAotCompile *acfg)
4390 sprintf (symbol, "mem_end");
4391 emit_section_change (acfg, ".text", 1);
4392 emit_global (acfg, symbol, FALSE);
4393 emit_alignment (acfg, 8);
4394 emit_label (acfg, symbol);
4398 * Emit a structure containing all the information not stored elsewhere.
4401 emit_file_info (MonoAotCompile *acfg)
4406 sprintf (symbol, "mono_aot_file_info");
4407 emit_section_change (acfg, ".data", 0);
4408 emit_alignment (acfg, 8);
4409 emit_label (acfg, symbol);
4410 emit_global (acfg, symbol, FALSE);
4412 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4413 emit_int32 (acfg, acfg->plt_got_offset_base);
4414 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4415 emit_int32 (acfg, acfg->plt_offset);
4417 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4418 emit_int32 (acfg, acfg->num_trampolines [i]);
4419 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4420 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4421 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4422 emit_int32 (acfg, acfg->trampoline_size [i]);
4426 emit_dwarf_info (MonoAotCompile *acfg)
4428 #ifdef EMIT_DWARF_INFO
4430 char symbol [128], symbol2 [128];
4432 /* DIEs for methods */
4433 for (i = 0; i < acfg->nmethods; ++i) {
4434 MonoCompile *cfg = acfg->cfgs [i];
4439 sprintf (symbol, ".Lm_%x", i);
4440 sprintf (symbol2, ".Lme_%x", i);
4442 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
4448 collect_methods (MonoAotCompile *acfg)
4451 MonoImage *image = acfg->image;
4453 /* Collect methods */
4454 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4456 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4458 method = mono_get_method (acfg->image, token, NULL);
4461 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4465 /* Load all methods eagerly to skip the slower lazy loading code */
4466 mono_class_setup_methods (method->klass);
4468 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4469 /* Compile the wrapper instead */
4470 /* We do this here instead of add_wrappers () because it is easy to do it here */
4471 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4475 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4476 add_method_with_index (acfg, method, i, FALSE);
4477 acfg->method_index ++;
4480 add_generic_instances (acfg);
4482 if (acfg->aot_opts.full_aot)
4483 add_wrappers (acfg);
4487 compile_methods (MonoAotCompile *acfg)
4491 if (acfg->aot_opts.nthreads > 0) {
4496 gpointer *user_data;
4497 MonoMethod **methods;
4499 methods_len = acfg->methods->len;
4501 len = acfg->methods->len / acfg->aot_opts.nthreads;
4504 * Partition the list of methods into fragments, and hand it to threads to
4507 threads = g_ptr_array_new ();
4508 /* Make a copy since acfg->methods is modified by compile_method () */
4509 methods = g_new0 (MonoMethod*, methods_len);
4510 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4511 for (i = 0; i < methods_len; ++i)
4512 methods [i] = g_ptr_array_index (acfg->methods, i);
4514 while (i < methods_len) {
4515 frag = g_ptr_array_new ();
4516 for (j = 0; j < len; ++j) {
4517 if (i < methods_len) {
4518 g_ptr_array_add (frag, methods [i]);
4523 user_data = g_new0 (gpointer, 3);
4524 user_data [0] = mono_domain_get ();
4525 user_data [1] = acfg;
4526 user_data [2] = frag;
4528 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4529 g_ptr_array_add (threads, handle);
4533 for (i = 0; i < threads->len; ++i) {
4534 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4540 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4541 for (i = methods_len; i < acfg->methods->len; ++i) {
4542 /* This can new methods to acfg->methods */
4543 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4548 compile_asm (MonoAotCompile *acfg)
4550 char *command, *objfile;
4551 char *outfile_name, *tmp_outfile_name;
4553 #if defined(TARGET_AMD64)
4554 #define AS_OPTIONS "--64"
4555 #elif defined(sparc) && SIZEOF_VOID_P == 8
4556 #define AS_OPTIONS "-xarch=v9"
4558 #define AS_OPTIONS ""
4561 if (acfg->aot_opts.asm_only) {
4562 printf ("Output file: '%s'.\n", acfg->tmpfname);
4563 if (acfg->aot_opts.static_link)
4564 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4568 if (acfg->aot_opts.static_link) {
4569 if (acfg->aot_opts.outfile)
4570 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4572 objfile = g_strdup_printf ("%s.o", acfg->image->name);
4574 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
4576 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
4577 printf ("Executing the native assembler: %s\n", command);
4578 if (system (command) != 0) {
4586 if (acfg->aot_opts.static_link) {
4587 printf ("Output file: '%s'.\n", objfile);
4588 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4593 if (acfg->aot_opts.outfile)
4594 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4596 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4598 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4601 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4602 #elif defined(__ppc__) && defined(__MACH__)
4603 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4604 #elif defined(PLATFORM_WIN32)
4605 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4607 command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4609 printf ("Executing the native linker: %s\n", command);
4610 if (system (command) != 0) {
4611 g_free (tmp_outfile_name);
4612 g_free (outfile_name);
4620 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
4621 printf ("Stripping the binary: %s\n", com);
4625 #if defined(TARGET_ARM) && !defined(__MACH__)
4627 * gas generates 'mapping symbols' each time code and data is mixed, which
4628 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
4630 command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
4631 printf ("Stripping the binary: %s\n", command);
4632 if (system (command) != 0) {
4633 g_free (tmp_outfile_name);
4634 g_free (outfile_name);
4641 rename (tmp_outfile_name, outfile_name);
4643 g_free (tmp_outfile_name);
4644 g_free (outfile_name);
4647 if (acfg->aot_opts.save_temps)
4648 printf ("Retained input file.\n");
4650 unlink (acfg->tmpfname);
4655 static MonoAotCompile*
4656 acfg_create (MonoAssembly *ass, guint32 opts)
4658 MonoImage *image = ass->image;
4659 MonoAotCompile *acfg;
4661 acfg = g_new0 (MonoAotCompile, 1);
4662 acfg->methods = g_ptr_array_new ();
4663 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4664 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4665 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4666 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4667 acfg->shared_patches = g_ptr_array_new ();
4668 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4669 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4670 acfg->image_hash = g_hash_table_new (NULL, NULL);
4671 acfg->image_table = g_ptr_array_new ();
4672 acfg->globals = g_ptr_array_new ();
4673 acfg->image = image;
4675 acfg->mempool = mono_mempool_new ();
4676 acfg->extra_methods = g_ptr_array_new ();
4677 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
4678 acfg->unwind_ops = g_ptr_array_new ();
4679 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4680 InitializeCriticalSection (&acfg->mutex);
4686 acfg_free (MonoAotCompile *acfg)
4690 img_writer_destroy (acfg->w);
4691 for (i = 0; i < acfg->nmethods; ++i)
4693 g_free (acfg->cfgs [i]);
4694 g_free (acfg->cfgs);
4695 g_free (acfg->static_linking_symbol);
4696 g_ptr_array_free (acfg->methods, TRUE);
4697 g_ptr_array_free (acfg->shared_patches, TRUE);
4698 g_ptr_array_free (acfg->image_table, TRUE);
4699 g_ptr_array_free (acfg->globals, TRUE);
4700 g_ptr_array_free (acfg->unwind_ops, TRUE);
4701 g_hash_table_destroy (acfg->method_indexes);
4702 g_hash_table_destroy (acfg->plt_offset_to_patch);
4703 g_hash_table_destroy (acfg->patch_to_plt_offset);
4704 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4705 g_hash_table_destroy (acfg->method_to_cfg);
4706 g_hash_table_destroy (acfg->token_info_hash);
4707 g_hash_table_destroy (acfg->image_hash);
4708 g_hash_table_destroy (acfg->unwind_info_offsets);
4709 g_hash_table_destroy (acfg->method_label_hash);
4710 mono_mempool_destroy (acfg->mempool);
4715 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4717 MonoImage *image = ass->image;
4719 MonoAotCompile *acfg;
4720 char *outfile_name, *tmp_outfile_name, *p;
4724 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4726 acfg = acfg_create (ass, opts);
4728 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4729 acfg->aot_opts.write_symbols = TRUE;
4730 acfg->aot_opts.ntrampolines = 10240;
4732 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4734 //acfg->aot_opts.print_skipped_methods = TRUE;
4736 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4737 if (acfg->aot_opts.full_aot) {
4738 printf ("--aot=full is not supported on this platform.\n");
4743 if (acfg->aot_opts.static_link)
4744 acfg->aot_opts.asm_writer = TRUE;
4746 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4747 if (acfg->aot_opts.outfile)
4748 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4750 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4752 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4754 acfg->fp = fopen (tmp_outfile_name, "w");
4755 g_assert (acfg->fp);
4757 acfg->w = img_writer_create (acfg->fp, TRUE);
4758 acfg->use_bin_writer = TRUE;
4760 if (acfg->aot_opts.asm_only) {
4761 if (acfg->aot_opts.outfile)
4762 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4764 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4765 acfg->fp = fopen (acfg->tmpfname, "w+");
4767 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4768 acfg->fp = fdopen (i, "w+");
4770 g_assert (acfg->fp);
4772 acfg->w = img_writer_create (acfg->fp, FALSE);
4774 tmp_outfile_name = NULL;
4775 outfile_name = NULL;
4778 load_profile_files (acfg);
4780 if (!acfg->aot_opts.nodebug)
4781 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4783 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
4784 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
4785 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
4787 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
4789 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
4791 /* Get rid of characters which cannot occur in symbols */
4792 p = acfg->got_symbol;
4793 for (p = acfg->got_symbol; *p; ++p) {
4794 if (!(isalnum (*p) || *p == '_'))
4798 acfg->method_index = 1;
4800 collect_methods (acfg);
4802 acfg->cfgs_size = acfg->methods->len + 32;
4803 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4805 /* PLT offset 0 is reserved for the PLT trampoline */
4806 acfg->plt_offset = 1;
4810 compile_methods (acfg);
4814 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4818 alloc_got_slots (acfg);
4820 img_writer_emit_start (acfg->w);
4823 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4829 emit_extra_methods (acfg);
4831 emit_method_order (acfg);
4833 emit_trampolines (acfg);
4835 emit_class_name_table (acfg);
4837 emit_got_info (acfg);
4839 emit_exception_info (acfg);
4841 emit_unwind_info (acfg);
4843 emit_class_info (acfg);
4847 emit_image_table (acfg);
4851 emit_file_info (acfg);
4853 emit_globals (acfg);
4856 emit_dwarf_info (acfg);
4858 emit_mem_end (acfg);
4862 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4864 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)));
4867 res = img_writer_emit_writeout (acfg->w);
4872 if (acfg->use_bin_writer) {
4873 rename (tmp_outfile_name, outfile_name);
4875 res = compile_asm (acfg);
4882 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4884 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);
4885 if (acfg->stats.genericcount)
4886 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4887 if (acfg->stats.abscount)
4888 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4889 if (acfg->stats.lmfcount)
4890 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4891 if (acfg->stats.ocount)
4892 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4893 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);
4894 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4897 printf ("GOT slot distribution:\n");
4898 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4899 if (acfg->stats.got_slot_types [i])
4900 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4903 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);
4911 * Support for emitting debug info for JITted code.
4913 * This works as follows:
4914 * - the runtime writes out an xdb.s file containing DWARF debug info.
4915 * - the user calls a gdb macro
4916 * - the macro compiles and loads this shared library using add-symbol-file.
4918 * This is based on the xdebug functionality in the Kaffe Java VM.
4920 * We emit assembly code instead of using the ELF writer, so we can emit debug info
4921 * incrementally as each method is JITted, and the debugger doesn't have to call
4922 * into the runtime to emit the shared library, which would cause all kinds of
4923 * complications, like threading issues, and the fact that the ELF writer's
4924 * emit_writeout () function cannot be called more than once.
4927 /* The recommended gdb macro is: */
4930 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4931 add-symbol-file xdb.so 0
4935 static MonoDwarfWriter *xdebug_writer;
4936 static FILE *xdebug_fp;
4939 mono_xdebug_init (void)
4945 xdebug_fp = fopen ("xdb.s", "w");
4947 w = img_writer_create (xdebug_fp, FALSE);
4949 img_writer_emit_start (w);
4951 /* This file will contain the IL code for methods which don't have debug info */
4952 il_file = fopen ("xdb.il", "w");
4954 xdebug_writer = mono_dwarf_writer_create (w, il_file);
4956 /* Emit something so the file has a text segment */
4957 img_writer_emit_section_change (w, ".text", 0);
4958 img_writer_emit_string (w, "");
4960 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4964 * mono_save_xdebug_info:
4966 * Emit debugging info for METHOD into an assembly file which can be assembled
4967 * and loaded into gdb to provide debugging info for JITted code.
4968 * LOCKING: Acquires the loader lock.
4971 mono_save_xdebug_info (MonoCompile *cfg)
4976 mono_loader_lock ();
4977 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 ()));
4979 mono_loader_unlock ();
4983 * mono_save_trampoline_xdebug_info:
4985 * Same as mono_save_xdebug_info, but for trampolines.
4986 * LOCKING: Acquires the loader lock.
4989 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4994 mono_loader_lock ();
4995 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4997 mono_loader_unlock ();
5005 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5011 mono_xdebug_init (void)
5016 mono_save_xdebug_info (MonoCompile *cfg)
5021 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)