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
47 #include <limits.h> /* for PAGESIZE */
52 #include <mono/metadata/tabledefs.h>
53 #include <mono/metadata/class.h>
54 #include <mono/metadata/object.h>
55 #include <mono/metadata/tokentype.h>
56 #include <mono/metadata/appdomain.h>
57 #include <mono/metadata/debug-helpers.h>
58 #include <mono/metadata/assembly.h>
59 #include <mono/metadata/metadata-internals.h>
60 #include <mono/metadata/marshal.h>
61 #include <mono/metadata/gc-internal.h>
62 #include <mono/metadata/method-builder.h>
63 #include <mono/metadata/monitor.h>
64 #include <mono/metadata/mempool-internals.h>
65 #include <mono/metadata/mono-endian.h>
66 #include <mono/metadata/mono-debug.h>
67 #include <mono/metadata/debug-mono-symfile.h>
68 #include <mono/utils/mono-logger.h>
69 #include <mono/utils/mono-compiler.h>
70 #include <mono/utils/mono-time.h>
72 #ifndef PLATFORM_WIN32
73 #include <mono/utils/freebsd-elf32.h>
74 #include <mono/utils/freebsd-elf64.h>
77 #include <mono/utils/freebsd-dwarf.h>
80 #include "image-writer.h"
81 #include "dwarfwriter.h"
85 #define TV_DECLARE(name) gint64 name
86 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
87 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
90 #define SHARED_EXT ".dll"
91 #elif defined(__ppc__) && defined(__MACH__)
92 #define SHARED_EXT ".dylib"
94 #define SHARED_EXT ".so"
97 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
98 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
99 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
101 typedef struct MonoAotOptions {
104 gboolean write_symbols;
105 gboolean metadata_only;
106 gboolean bind_to_runtime_version;
109 gboolean static_link;
113 gboolean print_skipped_methods;
116 typedef struct MonoAotStats {
117 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
118 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
119 int methods_without_got_slots, direct_calls, all_calls;
121 int got_slot_types [MONO_PATCH_INFO_NONE];
122 int jit_time, gen_time, link_time;
125 typedef struct MonoAotCompile {
128 GHashTable *method_indexes;
131 GHashTable *patch_to_plt_offset;
132 GHashTable *plt_offset_to_patch;
133 GHashTable *patch_to_shared_got_offset;
134 GPtrArray *shared_patches;
135 GHashTable *image_hash;
136 GHashTable *method_to_cfg;
137 GHashTable *token_info_hash;
138 GPtrArray *extra_methods;
139 GPtrArray *image_table;
142 guint32 *plt_got_info_offsets;
143 /* Number of trampolines emitted into the AOT file */
144 guint32 num_aot_trampolines;
145 guint32 got_offset, plt_offset, plt_got_offset_base;
146 /* Number of GOT entries reserved for trampolines */
147 guint32 num_trampoline_got_entries;
148 guint32 trampoline_got_offset_base;
149 guint32 specific_trampoline_size;
150 MonoAotOptions aot_opts;
153 MonoMemPool *mempool;
156 char *static_linking_symbol;
157 CRITICAL_SECTION mutex;
158 gboolean use_bin_writer;
160 MonoDwarfWriter *dwarf;
161 const char *current_section;
162 int current_subsection;
163 const char *section_stack [16];
164 int subsection_stack [16];
171 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
172 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
174 #ifdef HAVE_ARRAY_ELEM_INIT
175 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
176 #define MSGSTRFIELD1(line) str##line
177 static const struct msgstr_t {
178 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
179 #include "patch-info.h"
182 #define PATCH_INFO(a,b) b,
183 #include "patch-info.h"
186 static const gint16 opidx [] = {
187 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
188 #include "patch-info.h"
193 get_patch_name (int info)
195 return (const char*)&opstr + opidx [info];
199 #define PATCH_INFO(a,b) b,
200 static const char* const
201 patch_types [MONO_PATCH_INFO_NUM + 1] = {
202 #include "patch-info.h"
207 get_patch_name (int info)
209 return patch_types [info];
215 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
217 /* Wrappers around the image writer functions */
220 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
222 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
226 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
228 img_writer_emit_push_section (acfg->w, section_name, subsection);
232 emit_pop_section (MonoAotCompile *acfg)
234 img_writer_emit_pop_section (acfg->w);
238 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
240 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
244 emit_label (MonoAotCompile *acfg, const char *name)
246 img_writer_emit_label (acfg->w, name);
250 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
252 img_writer_emit_bytes (acfg->w, buf, size);
256 emit_string (MonoAotCompile *acfg, const char *value)
258 img_writer_emit_string (acfg->w, value);
262 emit_line (MonoAotCompile *acfg)
264 img_writer_emit_line (acfg->w);
268 emit_alignment (MonoAotCompile *acfg, int size)
270 img_writer_emit_alignment (acfg->w, size);
274 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
276 img_writer_emit_pointer_unaligned (acfg->w, target);
280 emit_pointer (MonoAotCompile *acfg, const char *target)
282 img_writer_emit_pointer (acfg->w, target);
286 emit_int16 (MonoAotCompile *acfg, int value)
288 img_writer_emit_int16 (acfg->w, value);
292 emit_int32 (MonoAotCompile *acfg, int value)
294 img_writer_emit_int32 (acfg->w, value);
298 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
300 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
304 emit_zero_bytes (MonoAotCompile *acfg, int num)
306 img_writer_emit_zero_bytes (acfg->w, num);
310 emit_byte (MonoAotCompile *acfg, guint8 val)
312 img_writer_emit_byte (acfg->w, val);
315 static G_GNUC_UNUSED void
316 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
318 img_writer_emit_global (acfg->w, name, func);
322 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
324 if (acfg->aot_opts.no_dlsym) {
325 g_ptr_array_add (acfg->globals, g_strdup (name));
327 img_writer_emit_global (acfg->w, name, func);
332 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
334 img_writer_emit_section_change (acfg->w, ".text", 1);
335 emit_global (acfg, name, FALSE);
336 img_writer_emit_label (acfg->w, name);
337 img_writer_emit_string (acfg->w, value);
340 static G_GNUC_UNUSED void
341 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
344 guint8 b = value & 0x7f;
346 if (value != 0) /* more bytes to come */
352 static G_GNUC_UNUSED void
353 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
356 gboolean negative = (value < 0);
363 /* the following is unnecessary if the
364 * implementation of >>= uses an arithmetic rather
365 * than logical shift for a signed left operand
369 value |= - ((gint64)1 <<(size - 7));
370 /* sign bit of byte is second high order bit (0x40) */
371 if ((value == 0 && !(byte & 0x40)) ||
372 (value == -1 && (byte & 0x40)))
376 emit_byte (acfg, byte);
380 static G_GNUC_UNUSED void
381 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
386 guint8 b = value & 0x7f;
388 if (value != 0) /* more bytes to come */
396 static G_GNUC_UNUSED void
397 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
400 gboolean negative = (value < 0);
408 /* the following is unnecessary if the
409 * implementation of >>= uses an arithmetic rather
410 * than logical shift for a signed left operand
414 value |= - (1 <<(size - 7));
415 /* sign bit of byte is second high order bit (0x40) */
416 if ((value == 0 && !(byte & 0x40)) ||
417 (value == -1 && (byte & 0x40)))
427 /* ARCHITECTURE SPECIFIC CODE */
429 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
430 #define EMIT_DWARF_INFO 1
434 * arch_emit_direct_call:
436 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
440 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
442 #if defined(__i386__) || defined(__x86_64__)
443 /* Need to make sure this is exactly 5 bytes long */
444 emit_byte (acfg, '\xe8');
445 emit_symbol_diff (acfg, target, ".", -4);
447 #elif defined(__arm__)
448 if (acfg->use_bin_writer) {
455 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
456 emit_bytes (acfg, buf, 4);
458 img_writer_emit_unset_mode (acfg->w);
459 fprintf (acfg->fp, "bl %s\n", target);
463 g_assert_not_reached ();
468 * arch_emit_got_access:
470 * The memory pointed to by CODE should hold native code for loading a GOT
471 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
472 * CODE_SIZE is set to the number of bytes emitted.
475 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
477 /* Emit beginning of instruction */
478 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
480 /* Emit the offset */
482 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
483 #elif defined(__i386__)
484 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
485 #elif defined(__arm__)
486 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
488 g_assert_not_reached ();
491 *code_size = mono_arch_get_patch_offset (code) + 4;
495 * arch_emit_plt_entry:
497 * Emit code for the PLT entry with index INDEX.
500 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
502 #if defined(__i386__)
504 /* It is filled up during loading by the AOT loader. */
505 emit_zero_bytes (acfg, 16);
507 /* Need to make sure this is 9 bytes long */
508 emit_byte (acfg, '\xe9');
509 emit_symbol_diff (acfg, "plt", ".", -4);
510 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
512 #elif defined(__x86_64__)
514 * We can't emit jumps because they are 32 bits only so they can't be patched.
515 * So we make indirect calls through GOT entries which are patched by the AOT
516 * loader to point to .Lpd entries.
517 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
519 /* jmpq *<offset>(%rip) */
520 emit_byte (acfg, '\xff');
521 emit_byte (acfg, '\x25');
522 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
523 /* Used by mono_aot_get_plt_info_offset */
524 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
525 #elif defined(__arm__)
530 * - optimize OP_AOTCONST implementation
531 * - optimize the PLT entries
532 * - optimize SWITCH AOT implementation
533 * - implement IMT support
536 if (acfg->use_bin_writer) {
537 /* We only emit 1 relocation since we implement it ourselves anyway */
538 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
539 /* FIXME: A 2 instruction encoding is sufficient in most cases */
540 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
541 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
542 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
543 emit_bytes (acfg, buf, code - buf);
544 /* FIXME: Get rid of this */
545 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
546 /* Used by mono_aot_get_plt_info_offset */
547 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
549 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
550 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
551 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
552 emit_bytes (acfg, buf, code - buf);
553 emit_symbol_diff (acfg, "got", ".", ((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]);
558 g_assert_not_reached ();
563 * arch_emit_specific_trampoline:
565 * Emit code for a specific trampoline. OFFSET is the offset of the first of
566 * two GOT slots which contain the generic trampoline address and the trampoline
567 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
570 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
573 * The trampolines created here are variations of the specific
574 * trampolines created in mono_arch_create_specific_trampoline (). The
576 * - the generic trampoline address is taken from a got slot.
577 * - the offset of the got slot where the trampoline argument is stored
578 * is embedded in the instruction stream, and the generic trampoline
579 * can load the argument by loading the offset, adding it to the
580 * address of the trampoline to get the address of the got slot, and
581 * loading the argument from there.
582 * - all the trampolines should be of the same length.
584 #if defined(__x86_64__)
585 /* This should be exactly 16 bytes long */
587 /* call *<offset>(%rip) */
588 emit_byte (acfg, '\x41');
589 emit_byte (acfg, '\xff');
590 emit_byte (acfg, '\x15');
591 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
592 /* This should be relative to the start of the trampoline */
593 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
594 emit_zero_bytes (acfg, 5);
595 #elif defined(__arm__)
599 /* This should be exactly 28 bytes long */
602 ARM_PUSH (code, 0x5fff);
603 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
604 /* Load the value from the GOT */
605 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
607 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
608 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
610 g_assert (code - buf == 20);
613 emit_bytes (acfg, buf, code - buf);
614 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
615 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
617 g_assert_not_reached ();
622 * arch_emit_unbox_trampoline:
624 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
625 * CALL_TARGET is the symbol pointing to the native code of METHOD.
628 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
630 #if defined(__x86_64__)
635 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
637 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
639 emit_bytes (acfg, buf, code - buf);
641 emit_byte (acfg, '\xe9');
642 emit_symbol_diff (acfg, call_target, ".", -4);
643 #elif defined(__arm__)
650 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
653 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
655 emit_bytes (acfg, buf, code - buf);
657 if (acfg->use_bin_writer)
658 g_assert_not_reached ();
660 fprintf (acfg->fp, "\n\tb %s\n", call_target);
662 g_assert_not_reached ();
667 * arch_get_cie_program:
669 * Get the unwind bytecode for the DWARF CIE.
672 arch_get_cie_program (void)
677 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
678 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
686 /* END OF ARCH SPECIFIC CODE */
689 mono_get_field_token (MonoClassField *field)
691 MonoClass *klass = field->parent;
694 for (i = 0; i < klass->field.count; ++i) {
695 if (field == &klass->fields [i])
696 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
699 g_assert_not_reached ();
704 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
708 //printf ("ENCODE: %d 0x%x.\n", value, value);
711 * Same encoding as the one used in the metadata, extended to handle values
712 * greater than 0x1fffffff.
714 if ((value >= 0) && (value <= 127))
716 else if ((value >= 0) && (value <= 16383)) {
717 p [0] = 0x80 | (value >> 8);
718 p [1] = value & 0xff;
720 } else if ((value >= 0) && (value <= 0x1fffffff)) {
721 p [0] = (value >> 24) | 0xc0;
722 p [1] = (value >> 16) & 0xff;
723 p [2] = (value >> 8) & 0xff;
724 p [3] = value & 0xff;
729 p [1] = (value >> 24) & 0xff;
730 p [2] = (value >> 16) & 0xff;
731 p [3] = (value >> 8) & 0xff;
732 p [4] = value & 0xff;
740 get_image_index (MonoAotCompile *cfg, MonoImage *image)
744 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
748 index = g_hash_table_size (cfg->image_hash);
749 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
750 g_ptr_array_add (cfg->image_table, image);
756 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
761 /* FIXME: Search referenced images as well */
762 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
763 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
768 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
769 return MONO_TOKEN_TYPE_SPEC | (i + 1);
775 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
780 * Encode a reference to KLASS. We use our home-grown encoding instead of the
781 * standard metadata encoding.
784 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
788 if (klass->generic_class) {
790 g_assert (klass->type_token);
792 /* Find a typespec for a class if possible */
793 token = find_typespec_for_class (acfg, klass);
795 encode_value (token, p, &p);
796 encode_value (get_image_index (acfg, acfg->image), p, &p);
798 MonoClass *gclass = klass->generic_class->container_class;
799 MonoGenericInst *inst = klass->generic_class->context.class_inst;
802 /* Encode it ourselves */
804 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
805 encode_value (MONO_TYPE_GENERICINST, p, &p);
806 encode_klass_ref (acfg, gclass, p, &p);
807 encode_value (inst->type_argc, p, &p);
808 for (i = 0; i < inst->type_argc; ++i)
809 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
811 } else if (klass->type_token) {
812 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
813 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
814 encode_value (get_image_index (acfg, klass->image), p, &p);
815 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
816 MonoGenericParam *param = klass->byval_arg.data.generic_param;
819 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
820 encode_value (klass->byval_arg.type, p, &p);
822 encode_value (param->num, p, &p);
824 g_assert (param->owner);
825 encode_value (param->owner->is_method, p, &p);
826 if (param->owner->is_method)
827 encode_method_ref (acfg, param->owner->owner.method, p, &p);
829 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
832 g_assert (klass->rank > 0);
833 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
834 encode_value (get_image_index (acfg, klass->image), p, &p);
835 encode_value (klass->rank, p, &p);
836 encode_klass_ref (acfg, klass->element_class, p, &p);
842 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
844 guint32 token = mono_get_field_token (field);
847 encode_klass_ref (cfg, field->parent, p, &p);
848 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
849 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
854 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
858 MonoGenericInst *inst;
860 /* Encode the context */
861 inst = context->class_inst;
862 encode_value (inst ? 1 : 0, p, &p);
864 encode_value (inst->type_argc, p, &p);
865 for (i = 0; i < inst->type_argc; ++i)
866 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
868 inst = context->method_inst;
869 encode_value (inst ? 1 : 0, p, &p);
871 encode_value (inst->type_argc, p, &p);
872 for (i = 0; i < inst->type_argc; ++i)
873 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
879 #define MAX_IMAGE_INDEX 250
882 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
884 guint32 image_index = get_image_index (acfg, method->klass->image);
885 guint32 token = method->token;
886 MonoJumpInfoToken *ji;
891 * The encoding for most methods is as follows:
892 * - image index encoded as a leb128
893 * - token index encoded as a leb128
894 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
895 * types of method encodings.
898 g_assert (image_index < MONO_AOT_METHODREF_MIN);
900 /* Mark methods which can't use aot trampolines because they need the further
901 * processing in mono_magic_trampoline () which requires a MonoMethod*.
903 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
904 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
905 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
908 * Some wrapper methods are shared using their signature, encode their
909 * stringified signature instead.
910 * FIXME: Optimize disk usage
913 if (method->wrapper_type) {
914 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
915 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
916 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
918 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
919 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
920 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
922 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
923 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
924 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
926 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
927 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
928 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
934 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
935 strcpy ((char*)p, name);
936 p += strlen (name) + 1;
938 } else if (method->wrapper_type) {
939 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
941 encode_value (method->wrapper_type, p, &p);
943 switch (method->wrapper_type) {
944 case MONO_WRAPPER_REMOTING_INVOKE:
945 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
946 case MONO_WRAPPER_XDOMAIN_INVOKE: {
949 m = mono_marshal_method_from_wrapper (method);
951 encode_method_ref (acfg, m, p, &p);
954 case MONO_WRAPPER_PROXY_ISINST:
955 case MONO_WRAPPER_LDFLD:
956 case MONO_WRAPPER_LDFLDA:
957 case MONO_WRAPPER_STFLD:
958 case MONO_WRAPPER_ISINST: {
959 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
960 encode_klass_ref (acfg, proxy_class, p, &p);
963 case MONO_WRAPPER_LDFLD_REMOTE:
964 case MONO_WRAPPER_STFLD_REMOTE:
966 case MONO_WRAPPER_ALLOC: {
967 int alloc_type = mono_gc_get_managed_allocator_type (method);
968 g_assert (alloc_type != -1);
969 encode_value (alloc_type, p, &p);
972 case MONO_WRAPPER_STELEMREF:
974 case MONO_WRAPPER_UNKNOWN:
975 if (strcmp (method->name, "FastMonitorEnter") == 0)
976 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
977 else if (strcmp (method->name, "FastMonitorExit") == 0)
978 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
980 g_assert_not_reached ();
982 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
983 case MONO_WRAPPER_SYNCHRONIZED: {
986 m = mono_marshal_method_from_wrapper (method);
988 encode_method_ref (acfg, m, p, &p);
992 g_assert_not_reached ();
994 } else if (mono_method_signature (method)->is_inflated) {
996 * This is a generic method, find the original token which referenced it and
998 * Obtain the token from information recorded by the JIT.
1000 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1002 image_index = get_image_index (acfg, ji->image);
1003 g_assert (image_index < MAX_IMAGE_INDEX);
1006 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1007 encode_value (image_index, p, &p);
1008 encode_value (token, p, &p);
1010 MonoMethod *declaring;
1011 MonoGenericContext *context = mono_method_get_context (method);
1013 g_assert (method->is_inflated);
1014 declaring = ((MonoMethodInflated*)method)->declaring;
1017 * This might be a non-generic method of a generic instance, which
1018 * doesn't have a token since the reference is generated by the JIT
1019 * like Nullable:Box/Unbox, or by generic sharing.
1022 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1023 /* Encode the klass */
1024 encode_klass_ref (acfg, method->klass, p, &p);
1025 /* Encode the method */
1026 image_index = get_image_index (acfg, method->klass->image);
1027 g_assert (image_index < MAX_IMAGE_INDEX);
1028 g_assert (declaring->token);
1029 token = declaring->token;
1030 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1031 encode_value (image_index, p, &p);
1032 encode_value (token, p, &p);
1033 encode_generic_context (acfg, context, p, &p);
1035 } else if (token == 0) {
1036 /* This might be a method of a constructed type like int[,].Set */
1037 /* Obtain the token from information recorded by the JIT */
1038 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1040 image_index = get_image_index (acfg, ji->image);
1041 g_assert (image_index < MAX_IMAGE_INDEX);
1044 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1045 encode_value (image_index, p, &p);
1046 encode_value (token, p, &p);
1049 g_assert (method->klass->rank);
1051 /* Encode directly */
1052 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1053 encode_klass_ref (acfg, method->klass, p, &p);
1054 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1055 encode_value (0, p, &p);
1056 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1057 encode_value (1, p, &p);
1058 else if (!strcmp (method->name, "Get"))
1059 encode_value (2, p, &p);
1060 else if (!strcmp (method->name, "Address"))
1061 encode_value (3, p, &p);
1062 else if (!strcmp (method->name, "Set"))
1063 encode_value (4, p, &p);
1065 g_assert_not_reached ();
1068 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1069 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1075 compare_patches (gconstpointer a, gconstpointer b)
1079 i = (*(MonoJumpInfo**)a)->ip.i;
1080 j = (*(MonoJumpInfo**)b)->ip.i;
1094 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1097 static inline gboolean
1098 is_plt_patch (MonoJumpInfo *patch_info)
1100 switch (patch_info->type) {
1101 case MONO_PATCH_INFO_METHOD:
1102 case MONO_PATCH_INFO_INTERNAL_METHOD:
1103 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1104 case MONO_PATCH_INFO_ICALL_ADDR:
1105 case MONO_PATCH_INFO_CLASS_INIT:
1106 case MONO_PATCH_INFO_RGCTX_FETCH:
1107 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1108 case MONO_PATCH_INFO_MONITOR_ENTER:
1109 case MONO_PATCH_INFO_MONITOR_EXIT:
1117 is_got_patch (MonoJumpInfoType patch_type)
1123 * is_shared_got_patch:
1125 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
1127 * Keep it in sync with the version in aot-runtime.c.
1129 static inline gboolean
1130 is_shared_got_patch (MonoJumpInfo *patch_info)
1132 switch (patch_info->type) {
1133 case MONO_PATCH_INFO_VTABLE:
1134 case MONO_PATCH_INFO_CLASS:
1135 case MONO_PATCH_INFO_IID:
1136 case MONO_PATCH_INFO_ADJUSTED_IID:
1137 case MONO_PATCH_INFO_FIELD:
1138 case MONO_PATCH_INFO_SFLDA:
1139 case MONO_PATCH_INFO_DECLSEC:
1140 case MONO_PATCH_INFO_LDTOKEN:
1141 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1142 case MONO_PATCH_INFO_RVA:
1143 case MONO_PATCH_INFO_METHODCONST:
1144 case MONO_PATCH_INFO_IMAGE:
1152 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1156 if (is_plt_patch (patch_info)) {
1157 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1159 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1161 * Allocate a separate PLT slot for each such patch, since some plt
1162 * entries will refer to the method itself, and some will refer to
1171 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1173 res = acfg->plt_offset;
1174 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1175 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1176 acfg->plt_offset ++;
1186 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1187 * JI could be found if it exists, otherwise allocates a new one.
1190 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1194 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1196 return got_offset - 1;
1198 got_offset = acfg->got_offset;
1199 acfg->got_offset ++;
1201 acfg->stats.got_slots ++;
1202 acfg->stats.got_slot_types [ji->type] ++;
1208 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1213 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1214 got_offset = get_got_offset (acfg, ji);
1215 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1216 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1217 g_ptr_array_add (acfg->shared_patches, copy);
1220 return get_got_offset (acfg, ji);
1223 /* Add a method to the list of methods which need to be emitted */
1225 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1228 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1229 g_ptr_array_add (acfg->methods, method);
1230 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1231 acfg->nmethods = acfg->methods->len + 1;
1236 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1238 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1246 add_method (MonoAotCompile *acfg, MonoMethod *method)
1250 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1254 index = acfg->method_index;
1255 add_method_with_index (acfg, method, index);
1257 /* FIXME: Fix quadratic behavior */
1258 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1260 acfg->method_index ++;
1266 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1270 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1273 add_method (acfg, method);
1274 g_ptr_array_add (acfg->extra_methods, method);
1278 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1280 MonoAotCompile *acfg = user_data;
1281 MonoJitICallInfo *callinfo = value;
1282 MonoMethod *wrapper;
1288 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1289 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1292 add_method (acfg, wrapper);
1296 get_runtime_invoke_sig (MonoMethodSignature *sig)
1298 MonoMethodBuilder *mb;
1301 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1302 m = mono_mb_create_method (mb, sig, 16);
1303 return mono_marshal_get_runtime_invoke (m);
1307 add_wrappers (MonoAotCompile *acfg)
1309 MonoMethod *method, *m;
1310 int i, j, nallocators;
1311 MonoMethodSignature *sig, *csig;
1315 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1316 * so there is only one wrapper of a given type, or inlining their contents into their
1321 * FIXME: This depends on the fact that different wrappers have different
1325 /* FIXME: Collect these automatically */
1327 /* Runtime invoke wrappers */
1329 /* void runtime-invoke () [.cctor] */
1330 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1331 csig->ret = &mono_defaults.void_class->byval_arg;
1332 add_method (acfg, get_runtime_invoke_sig (csig));
1334 /* void runtime-invoke () [Finalize] */
1335 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1337 csig->ret = &mono_defaults.void_class->byval_arg;
1338 add_method (acfg, get_runtime_invoke_sig (csig));
1340 /* void runtime-invoke (string) [exception ctor] */
1341 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1343 csig->ret = &mono_defaults.void_class->byval_arg;
1344 csig->params [0] = &mono_defaults.string_class->byval_arg;
1345 add_method (acfg, get_runtime_invoke_sig (csig));
1347 /* void runtime-invoke (string, string) [exception ctor] */
1348 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1350 csig->ret = &mono_defaults.void_class->byval_arg;
1351 csig->params [0] = &mono_defaults.string_class->byval_arg;
1352 csig->params [1] = &mono_defaults.string_class->byval_arg;
1353 add_method (acfg, get_runtime_invoke_sig (csig));
1355 /* string runtime-invoke () [Exception.ToString ()] */
1356 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1358 csig->ret = &mono_defaults.string_class->byval_arg;
1359 add_method (acfg, get_runtime_invoke_sig (csig));
1361 /* void runtime-invoke (string, Exception) [exception ctor] */
1362 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1364 csig->ret = &mono_defaults.void_class->byval_arg;
1365 csig->params [0] = &mono_defaults.string_class->byval_arg;
1366 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1367 add_method (acfg, get_runtime_invoke_sig (csig));
1369 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1370 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1372 csig->ret = &(mono_class_from_name (
1373 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1374 csig->params [0] = &mono_defaults.string_class->byval_arg;
1375 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1376 add_method (acfg, get_runtime_invoke_sig (csig));
1378 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1380 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1381 gboolean skip = FALSE;
1383 method = mono_get_method (acfg->image, token, NULL);
1385 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1386 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1387 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1390 if (method->is_generic || method->klass->generic_container)
1393 /* Skip methods which can not be handled by get_runtime_invoke () */
1394 sig = mono_method_signature (method);
1395 if ((sig->ret->type == MONO_TYPE_PTR) ||
1396 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1399 for (j = 0; j < sig->param_count; j++) {
1400 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1405 add_method (acfg, mono_marshal_get_runtime_invoke (method));
1408 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1409 MonoMethodDesc *desc;
1410 MonoMethod *orig_method;
1412 /* JIT icall wrappers */
1413 /* FIXME: locking */
1414 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1416 /* Managed Allocators */
1417 nallocators = mono_gc_get_managed_allocator_types ();
1418 for (i = 0; i < nallocators; ++i) {
1419 m = mono_gc_get_managed_allocator_by_type (i);
1421 add_method (acfg, m);
1425 add_method (acfg, mono_marshal_get_stelemref ());
1427 /* Monitor Enter/Exit */
1428 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1429 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1430 g_assert (orig_method);
1431 mono_method_desc_free (desc);
1432 method = mono_monitor_get_fast_path (orig_method);
1434 add_method (acfg, method);
1436 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1437 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1438 g_assert (orig_method);
1439 mono_method_desc_free (desc);
1440 method = mono_monitor_get_fast_path (orig_method);
1442 add_method (acfg, method);
1445 /* remoting-invoke wrappers */
1446 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1447 MonoMethodSignature *sig;
1449 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1450 method = mono_get_method (acfg->image, token, NULL);
1452 sig = mono_method_signature (method);
1454 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
1455 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
1456 m = mono_marshal_get_remoting_invoke_with_check (method);
1458 add_method (acfg, m);
1462 /* delegate-invoke wrappers */
1463 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1466 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1467 klass = mono_class_get (acfg->image, token);
1469 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1470 method = mono_get_delegate_invoke (klass);
1472 m = mono_marshal_get_delegate_invoke (method, NULL);
1474 add_method (acfg, m);
1476 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1477 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1479 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1480 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1484 /* Synchronized wrappers */
1485 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1486 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1487 method = mono_get_method (acfg->image, token, NULL);
1489 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1490 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1494 /* static rgctx wrappers */
1495 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
1496 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1497 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1498 method = mono_get_method (acfg->image, token, NULL);
1500 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
1501 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
1502 mono_class_generic_sharing_enabled (method->klass) &&
1503 mono_method_is_generic_sharable_impl (method, FALSE)) {
1504 m = mono_marshal_get_static_rgctx_invoke (method);
1505 add_method (acfg, m);
1510 /* pinvoke wrappers */
1511 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1513 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1515 method = mono_get_method (acfg->image, token, NULL);
1517 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1518 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1519 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1525 has_type_vars (MonoClass *klass)
1527 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1530 return has_type_vars (klass->element_class);
1531 if (klass->generic_class) {
1532 MonoGenericContext *context = &klass->generic_class->context;
1533 if (context->class_inst) {
1536 for (i = 0; i < context->class_inst->type_argc; ++i)
1537 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1545 method_has_type_vars (MonoMethod *method)
1547 if (has_type_vars (method->klass))
1550 if (method->is_inflated) {
1551 MonoGenericContext *context = mono_method_get_context (method);
1552 if (context->method_inst) {
1555 for (i = 0; i < context->method_inst->type_argc; ++i)
1556 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1564 * add_generic_class:
1566 * Add all methods of a generic class.
1569 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1574 mono_class_init (klass);
1576 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1579 if (has_type_vars (klass))
1582 if (!klass->generic_class && !klass->rank)
1586 * Add rgctx wrappers for cctors since those are called by the runtime, so
1587 * there is no methodspec for them. This is needed even for shared classes,
1588 * since rgctx wrappers belong to inflated methods.
1590 method = mono_class_get_cctor (klass);
1592 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1595 while ((method = mono_class_get_methods (klass, &iter))) {
1596 if (mono_method_is_generic_sharable_impl (method, FALSE))
1600 if (method->is_generic)
1605 * FIXME: Instances which are referenced by these methods are not added,
1606 * for example Array.Resize<int> for List<int>.Add ().
1608 add_extra_method (acfg, method);
1613 * add_generic_instances:
1615 * Add instances referenced by the METHODSPEC/TYPESPEC table.
1618 add_generic_instances (MonoAotCompile *acfg)
1623 MonoGenericContext *context;
1625 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1626 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1627 method = mono_get_method (acfg->image, token, NULL);
1629 context = mono_method_get_context (method);
1630 if (context && ((context->class_inst && context->class_inst->is_open) ||
1631 (context->method_inst && context->method_inst->is_open)))
1634 if (method->klass->image != acfg->image)
1637 if (mono_method_is_generic_sharable_impl (method, FALSE))
1641 add_extra_method (acfg, method);
1644 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1647 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1649 klass = mono_class_get (acfg->image, token);
1653 add_generic_class (acfg, klass);
1658 * emit_and_reloc_code:
1660 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1661 * is true, calls are made through the GOT too. This is used for emitting trampolines
1662 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1663 * since trampolines are needed to make PTL work.
1666 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1668 int i, pindex, start_index, method_index;
1670 MonoJumpInfo *patch_info;
1671 MonoMethodHeader *header;
1672 gboolean skip, direct_call;
1674 char direct_call_target [128];
1677 header = mono_method_get_header (method);
1679 method_index = get_method_index (acfg, method);
1682 /* Collect and sort relocations */
1683 patches = g_ptr_array_new ();
1684 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1685 g_ptr_array_add (patches, patch_info);
1686 g_ptr_array_sort (patches, compare_patches);
1689 for (i = 0; i < code_len; i++) {
1691 for (pindex = start_index; pindex < patches->len; ++pindex) {
1692 patch_info = g_ptr_array_index (patches, pindex);
1693 if (patch_info->ip.i >= i)
1697 #ifdef MONO_ARCH_AOT_SUPPORTED
1699 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1700 start_index = pindex;
1702 switch (patch_info->type) {
1703 case MONO_PATCH_INFO_NONE:
1705 case MONO_PATCH_INFO_GOT_OFFSET: {
1706 guint32 offset = mono_arch_get_patch_offset (code + i);
1707 emit_bytes (acfg, code + i, offset);
1708 emit_symbol_diff (acfg, "got", ".", offset);
1710 i += offset + 4 - 1;
1715 if (!is_got_patch (patch_info->type))
1719 * If this patch is a call, try emitting a direct call instead of
1720 * through a PLT entry. This is possible if the called method is in
1721 * the same assembly and requires no initialization.
1723 direct_call = FALSE;
1724 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1725 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1727 gboolean direct_callable = TRUE;
1729 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1730 direct_callable = FALSE;
1731 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1732 // FIXME: Maybe call the wrapper directly ?
1733 direct_callable = FALSE;
1734 if (direct_callable) {
1735 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1737 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1738 patch_info->type = MONO_PATCH_INFO_NONE;
1739 acfg->stats.direct_calls ++;
1743 acfg->stats.all_calls ++;
1746 if (!got_only && !direct_call) {
1747 int plt_offset = get_plt_offset (acfg, patch_info);
1748 if (plt_offset != -1) {
1749 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1751 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1753 /* Nullify the patch */
1754 patch_info->type = MONO_PATCH_INFO_NONE;
1761 arch_emit_direct_call (acfg, direct_call_target, &call_size);
1766 got_slot = get_got_offset (acfg, patch_info);
1768 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1775 #endif /* MONO_ARCH_AOT_SUPPORTED */
1778 /* Find next patch */
1780 for (pindex = start_index; pindex < patches->len; ++pindex) {
1781 patch_info = g_ptr_array_index (patches, pindex);
1782 if (patch_info->ip.i >= i)
1786 /* Try to emit multiple bytes at once */
1787 if (pindex < patches->len && patch_info->ip.i > i) {
1788 emit_bytes (acfg, code + i, patch_info->ip.i - i);
1789 i = patch_info->ip.i - 1;
1791 emit_bytes (acfg, code + i, 1);
1798 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1804 int func_alignment = 16;
1805 MonoMethodHeader *header;
1807 method = cfg->orig_method;
1808 code = cfg->native_code;
1809 header = mono_method_get_header (method);
1811 method_index = get_method_index (acfg, method);
1813 /* Make the labels local */
1814 sprintf (symbol, ".Lm_%x", method_index);
1816 emit_alignment (acfg, func_alignment);
1817 emit_label (acfg, symbol);
1819 if (acfg->aot_opts.write_symbols && acfg->use_bin_writer) {
1821 /* Emit a local symbol into the symbol table */
1822 full_name = mono_method_full_name (method, TRUE);
1823 sprintf (symbol, ".Lme_%x", method_index);
1824 emit_local_symbol (acfg, full_name, symbol, TRUE);
1825 emit_label (acfg, full_name);
1829 if (cfg->verbose_level > 0)
1830 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
1832 acfg->stats.code_size += cfg->code_len;
1834 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
1836 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
1840 sprintf (symbol, ".Lme_%x", method_index);
1841 emit_label (acfg, symbol);
1847 * Encode PATCH_INFO into its disk representation.
1850 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
1854 switch (patch_info->type) {
1855 case MONO_PATCH_INFO_NONE:
1857 case MONO_PATCH_INFO_IMAGE:
1858 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
1860 case MONO_PATCH_INFO_METHOD_REL:
1861 encode_value ((gint)patch_info->data.offset, p, &p);
1863 case MONO_PATCH_INFO_SWITCH: {
1864 gpointer *table = (gpointer *)patch_info->data.table->table;
1867 encode_value (patch_info->data.table->table_size, p, &p);
1868 for (k = 0; k < patch_info->data.table->table_size; k++)
1869 encode_value ((int)(gssize)table [k], p, &p);
1872 case MONO_PATCH_INFO_METHODCONST:
1873 case MONO_PATCH_INFO_METHOD:
1874 case MONO_PATCH_INFO_METHOD_JUMP:
1875 case MONO_PATCH_INFO_ICALL_ADDR:
1876 case MONO_PATCH_INFO_METHOD_RGCTX:
1877 encode_method_ref (acfg, patch_info->data.method, p, &p);
1879 case MONO_PATCH_INFO_INTERNAL_METHOD:
1880 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1881 guint32 len = strlen (patch_info->data.name);
1883 encode_value (len, p, &p);
1885 memcpy (p, patch_info->data.name, len);
1890 case MONO_PATCH_INFO_LDSTR: {
1891 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
1892 guint32 token = patch_info->data.token->token;
1893 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
1894 encode_value (image_index, p, &p);
1895 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
1898 case MONO_PATCH_INFO_RVA:
1899 case MONO_PATCH_INFO_DECLSEC:
1900 case MONO_PATCH_INFO_LDTOKEN:
1901 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1902 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
1903 encode_value (patch_info->data.token->token, p, &p);
1904 encode_value (patch_info->data.token->has_context, p, &p);
1905 if (patch_info->data.token->has_context)
1906 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
1908 case MONO_PATCH_INFO_EXC_NAME: {
1909 MonoClass *ex_class;
1912 mono_class_from_name (mono_defaults.exception_class->image,
1913 "System", patch_info->data.target);
1914 g_assert (ex_class);
1915 encode_klass_ref (acfg, ex_class, p, &p);
1918 case MONO_PATCH_INFO_R4:
1919 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1921 case MONO_PATCH_INFO_R8:
1922 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1923 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
1925 case MONO_PATCH_INFO_VTABLE:
1926 case MONO_PATCH_INFO_CLASS:
1927 case MONO_PATCH_INFO_IID:
1928 case MONO_PATCH_INFO_ADJUSTED_IID:
1929 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
1931 case MONO_PATCH_INFO_CLASS_INIT:
1932 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1933 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
1935 case MONO_PATCH_INFO_FIELD:
1936 case MONO_PATCH_INFO_SFLDA:
1937 encode_field_info (acfg, patch_info->data.field, p, &p);
1939 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1941 case MONO_PATCH_INFO_RGCTX_FETCH: {
1942 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
1944 encode_method_ref (acfg, entry->method, p, &p);
1945 encode_value (entry->in_mrgctx, p, &p);
1946 encode_value (entry->info_type, p, &p);
1947 encode_value (entry->data->type, p, &p);
1948 encode_patch (acfg, entry->data, p, &p);
1951 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1952 case MONO_PATCH_INFO_MONITOR_ENTER:
1953 case MONO_PATCH_INFO_MONITOR_EXIT:
1956 g_warning ("unable to handle jump info %d", patch_info->type);
1957 g_assert_not_reached ();
1964 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
1967 guint32 last_offset, j, pindex;
1968 MonoJumpInfo *patch_info;
1970 encode_value (n_patches, p, &p);
1973 encode_value (first_got_offset, p, &p);
1975 /* First encode the type+position table */
1978 for (pindex = 0; pindex < patches->len; ++pindex) {
1980 patch_info = g_ptr_array_index (patches, pindex);
1982 if (patch_info->type == MONO_PATCH_INFO_NONE)
1987 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
1988 offset = patch_info->ip.i - last_offset;
1989 last_offset = patch_info->ip.i;
1991 /* Only the type is needed */
1992 *p = patch_info->type;
1996 /* Then encode the other info */
1997 for (pindex = 0; pindex < patches->len; ++pindex) {
1998 patch_info = g_ptr_array_index (patches, pindex);
2000 if (is_shared_got_patch (patch_info)) {
2001 guint32 offset = get_got_offset (acfg, patch_info);
2002 encode_value (offset, p, &p);
2004 encode_patch (acfg, patch_info, p, &p);
2012 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2016 int pindex, buf_size, n_patches;
2020 MonoJumpInfo *patch_info;
2021 MonoMethodHeader *header;
2022 guint32 method_index;
2024 guint32 first_got_offset;
2026 method = cfg->orig_method;
2027 code = cfg->native_code;
2028 header = mono_method_get_header (method);
2030 method_index = get_method_index (acfg, method);
2032 /* Make the labels local */
2033 sprintf (symbol, ".Lm_%x_p", method_index);
2035 /* Sort relocations */
2036 patches = g_ptr_array_new ();
2037 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2038 g_ptr_array_add (patches, patch_info);
2039 g_ptr_array_sort (patches, compare_patches);
2041 first_got_offset = acfg->cfgs [method_index]->got_offset;
2043 /**********************/
2044 /* Encode method info */
2045 /**********************/
2047 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2048 p = buf = g_malloc (buf_size);
2050 if (mono_class_get_cctor (method->klass))
2051 encode_klass_ref (acfg, method->klass, p, &p);
2053 /* Not needed when loading the method */
2054 encode_value (0, p, &p);
2057 if (cfg->opt & MONO_OPT_SHARED) {
2058 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2059 for (l = cfg->ldstr_list; l; l = l->next) {
2060 encode_value ((long)l->data, p, &p);
2064 /* Used only in shared mode */
2065 g_assert (!cfg->ldstr_list);
2068 for (pindex = 0; pindex < patches->len; ++pindex) {
2069 patch_info = g_ptr_array_index (patches, pindex);
2071 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2072 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2073 patch_info->type = MONO_PATCH_INFO_NONE;
2078 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2079 /* Stored in a GOT slot initialized at module load time */
2080 patch_info->type = MONO_PATCH_INFO_NONE;
2084 if (is_plt_patch (patch_info)) {
2085 /* Calls are made through the PLT */
2086 patch_info->type = MONO_PATCH_INFO_NONE;
2094 g_assert (cfg->has_got_slots);
2096 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2098 acfg->stats.info_size += p - buf;
2100 /* Emit method info */
2102 emit_label (acfg, symbol);
2104 g_assert (p - buf < buf_size);
2105 emit_bytes (acfg, buf, p - buf);
2110 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2113 int k, buf_size, method_index;
2114 guint32 debug_info_size;
2117 MonoMethodHeader *header;
2118 guint8 *p, *buf, *debug_info;
2119 MonoJitInfo *jinfo = cfg->jit_info;
2121 gboolean use_unwind_ops = FALSE;
2123 method = cfg->orig_method;
2124 code = cfg->native_code;
2125 header = mono_method_get_header (method);
2127 method_index = get_method_index (acfg, method);
2129 /* Make the labels local */
2130 sprintf (symbol, ".Le_%x_p", method_index);
2132 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2134 buf_size = header->num_clauses * 256 + debug_info_size + 256;
2135 p = buf = g_malloc (buf_size);
2137 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2138 use_unwind_ops = cfg->unwind_ops != NULL;
2141 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2143 encode_value (jinfo->code_size, p, &p);
2144 encode_value (flags, p, &p);
2146 if (use_unwind_ops) {
2147 guint32 encoded_len;
2151 * This is a duplicate of the data in the .debug_frame section, but that
2152 * section cannot be accessed using the dl interface.
2154 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2155 encode_value (encoded_len, p, &p);
2156 memcpy (p, encoded, encoded_len);
2160 encode_value (jinfo->used_regs, p, &p);
2163 /* Exception table */
2164 if (header->num_clauses) {
2165 for (k = 0; k < header->num_clauses; ++k) {
2166 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2168 encode_value (ei->exvar_offset, p, &p);
2170 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2171 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2173 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2174 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2175 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2179 if (jinfo->has_generic_jit_info) {
2180 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2182 encode_value (gi->has_this ? 1 : 0, p, &p);
2183 encode_value (gi->this_reg, p, &p);
2184 encode_value (gi->this_offset, p, &p);
2187 * Need to encode jinfo->method too, since it is not equal to 'method'
2188 * when using generic sharing.
2190 encode_method_ref (acfg, jinfo->method, p, &p);
2193 g_assert (debug_info_size < buf_size);
2195 encode_value (debug_info_size, p, &p);
2196 if (debug_info_size) {
2197 memcpy (p, debug_info, debug_info_size);
2198 p += debug_info_size;
2199 g_free (debug_info);
2202 acfg->stats.ex_info_size += p - buf;
2206 emit_label (acfg, symbol);
2208 g_assert (p - buf < buf_size);
2209 emit_bytes (acfg, buf, p - buf);
2214 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2216 MonoClass *klass = mono_class_get (acfg->image, token);
2220 gboolean no_special_static, cant_encode;
2221 gpointer iter = NULL;
2223 buf_size = 10240 + (klass->vtable_size * 16);
2224 p = buf = g_malloc (buf_size);
2228 mono_class_init (klass);
2230 mono_class_get_nested_types (klass, &iter);
2231 g_assert (klass->nested_classes_inited);
2233 mono_class_setup_vtable (klass);
2236 * Emit all the information which is required for creating vtables so
2237 * the runtime does not need to create the MonoMethod structures which
2238 * take up a lot of space.
2241 no_special_static = !mono_class_has_special_static_fields (klass);
2243 /* Check whenever we have enough info to encode the vtable */
2244 cant_encode = FALSE;
2245 for (i = 0; i < klass->vtable_size; ++i) {
2246 MonoMethod *cm = klass->vtable [i];
2248 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2252 if (klass->generic_container || cant_encode) {
2253 encode_value (-1, p, &p);
2255 encode_value (klass->vtable_size, p, &p);
2256 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);
2257 if (klass->has_cctor)
2258 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2259 if (klass->has_finalize)
2260 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2262 encode_value (klass->instance_size, p, &p);
2263 encode_value (mono_class_data_size (klass), p, &p);
2264 encode_value (klass->packing_size, p, &p);
2265 encode_value (klass->min_align, p, &p);
2267 for (i = 0; i < klass->vtable_size; ++i) {
2268 MonoMethod *cm = klass->vtable [i];
2271 encode_method_ref (acfg, cm, p, &p);
2273 encode_value (0, p, &p);
2277 acfg->stats.class_info_size += p - buf;
2280 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2281 emit_label (acfg, symbol);
2283 g_assert (p - buf < buf_size);
2284 emit_bytes (acfg, buf, p - buf);
2289 * Calls made from AOTed code are routed through a table of jumps similar to the
2290 * ELF PLT (Program Linkage Table). The differences are the following:
2291 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2292 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2293 * jumps. This means the jumps need to be patched when the address of the callee is
2294 * known. Initially the PLT entries jump to code which transfers control to the
2295 * AOT runtime through the first PLT entry.
2298 emit_plt (MonoAotCompile *acfg)
2304 sprintf (symbol, "plt");
2306 emit_section_change (acfg, ".text", 0);
2307 emit_global (acfg, symbol, TRUE);
2309 /* This section will be made read-write by the AOT loader */
2310 emit_alignment (acfg, PAGESIZE);
2312 emit_alignment (acfg, 16);
2314 emit_label (acfg, symbol);
2316 for (i = 0; i < acfg->plt_offset; ++i) {
2319 sprintf (label, ".Lp_%d", i);
2320 emit_label (acfg, label);
2323 * The first plt entry is used to transfer code to the AOT loader.
2325 arch_emit_plt_entry (acfg, i);
2328 sprintf (symbol, "plt_end");
2329 emit_global (acfg, symbol, TRUE);
2330 emit_label (acfg, symbol);
2333 static G_GNUC_UNUSED void
2334 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
2335 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2339 MonoJumpInfo *patch_info;
2345 sprintf (symbol, "%s", name);
2347 emit_section_change (acfg, ".text", 0);
2348 emit_global (acfg, symbol, TRUE);
2349 emit_alignment (acfg, 16);
2350 emit_label (acfg, symbol);
2352 sprintf (symbol, ".Lnamed_%s", name);
2353 emit_label (acfg, symbol);
2356 * The code should access everything through the GOT, so we pass
2359 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2363 /* Sort relocations */
2364 patches = g_ptr_array_new ();
2365 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2366 g_ptr_array_add (patches, patch_info);
2367 g_ptr_array_sort (patches, compare_patches);
2369 buf_size = patches->len * 128 + 128;
2370 buf = g_malloc (buf_size);
2373 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2374 g_assert (p - buf < buf_size);
2376 sprintf (symbol, "%s_p", name);
2378 emit_section_change (acfg, ".text", 0);
2379 emit_global (acfg, symbol, FALSE);
2380 emit_label (acfg, symbol);
2382 emit_bytes (acfg, buf, p - buf);
2384 /* Emit debug info */
2388 sprintf (symbol, "%s", name);
2389 sprintf (symbol2, ".Lnamed_%s", name);
2391 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2396 * When running in aot-only mode, we can't create trampolines at runtime, so we create
2397 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
2398 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
2399 * which needs to be added to the trampoline address to get the address of the GOT slot
2400 * which contains the argument value.
2401 * The generated trampolines jump to the generic trampolines using another GOT slot, which
2402 * will be setup by the AOT loader to point to the generic trampoline code of the given
2406 emit_trampolines (MonoAotCompile *acfg)
2410 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2418 if (!acfg->aot_opts.full_aot)
2421 g_assert (acfg->image->assembly);
2423 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2424 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2425 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2427 * Emit the generic trampolines.
2429 * We could save some code by treating the generic trampolines as a wrapper
2430 * method, but that approach has its own complexities, so we choose the simpler
2433 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2434 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2436 /* Emit trampoline code */
2438 sprintf (symbol, "generic_trampoline_%d", tramp_type);
2440 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2443 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2444 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2445 #if defined(__x86_64__) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2446 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2447 emit_named_code (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2448 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2449 emit_named_code (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2452 #if defined(__x86_64__)
2453 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2454 emit_named_code (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2457 /* Emit the exception related code pieces */
2458 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2459 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2460 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2461 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2462 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2463 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2464 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2465 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2466 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2467 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2468 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2469 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2471 #if defined(__x86_64__)
2472 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2473 emit_named_code (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2476 #if defined(__x86_64__) || defined(__arm__)
2477 for (i = 0; i < 128; ++i) {
2480 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2481 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2482 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2483 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2485 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2486 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2487 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2488 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2494 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2498 /* Reserve some entries at the end of the GOT for our use */
2499 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
2501 sprintf (symbol, "trampolines");
2503 emit_section_change (acfg, ".text", 0);
2504 emit_global (acfg, symbol, TRUE);
2505 emit_alignment (acfg, 16);
2506 emit_label (acfg, symbol);
2508 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
2511 offset = acfg->got_offset + (i * 2);
2513 arch_emit_specific_trampoline (acfg, offset, &tramp_size);
2514 if (!acfg->specific_trampoline_size) {
2515 g_assert (tramp_size);
2516 acfg->specific_trampoline_size = tramp_size;
2521 /* Unbox trampolines */
2523 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2525 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2527 char call_target [256];
2529 method = mono_get_method (acfg->image, token, NULL);
2531 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2532 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2535 sprintf (symbol, "unbox_trampoline_%d", i);
2537 emit_section_change (acfg, ".text", 0);
2538 emit_global (acfg, symbol, TRUE);
2539 emit_label (acfg, symbol);
2541 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2543 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2546 acfg->trampoline_got_offset_base = acfg->got_offset;
2548 acfg->got_offset += acfg->num_trampoline_got_entries;
2552 str_begins_with (const char *str1, const char *str2)
2554 int len = strlen (str2);
2555 return strncmp (str1, str2, len) == 0;
2559 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2561 gchar **args, **ptr;
2563 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2564 for (ptr = args; ptr && *ptr; ptr ++) {
2565 const char *arg = *ptr;
2567 if (str_begins_with (arg, "outfile=")) {
2568 opts->outfile = g_strdup (arg + strlen ("outfile="));
2569 } else if (str_begins_with (arg, "save-temps")) {
2570 opts->save_temps = TRUE;
2571 } else if (str_begins_with (arg, "keep-temps")) {
2572 opts->save_temps = TRUE;
2573 } else if (str_begins_with (arg, "write-symbols")) {
2574 opts->write_symbols = TRUE;
2575 } else if (str_begins_with (arg, "metadata-only")) {
2576 opts->metadata_only = TRUE;
2577 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2578 opts->bind_to_runtime_version = TRUE;
2579 } else if (str_begins_with (arg, "full")) {
2580 opts->full_aot = TRUE;
2582 * The no-dlsym option is only useful on the iphone, and even there,
2583 * do to other limitations of the dynamic linker, it doesn't seem to
2584 * work. So disable it for now so we don't have to support it.
2587 } else if (str_begins_with (arg, "no-dlsym")) {
2588 opts->no_dlsym = TRUE;
2590 } else if (str_begins_with (arg, "threads=")) {
2591 opts->nthreads = atoi (arg + strlen ("threads="));
2592 } else if (str_begins_with (arg, "static")) {
2593 opts->static_link = TRUE;
2594 opts->no_dlsym = TRUE;
2595 } else if (str_begins_with (arg, "asmonly")) {
2596 opts->asm_only = TRUE;
2597 } else if (str_begins_with (arg, "asmwriter")) {
2598 opts->asm_writer = TRUE;
2600 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2609 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2611 MonoMethod *method = (MonoMethod*)key;
2612 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2613 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2614 MonoAotCompile *acfg = user_data;
2616 new_ji->image = ji->image;
2617 new_ji->token = ji->token;
2618 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2622 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2624 if (klass->type_token)
2626 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2629 return can_encode_class (acfg, klass->element_class);
2634 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2636 switch (patch_info->type) {
2637 case MONO_PATCH_INFO_METHOD:
2638 case MONO_PATCH_INFO_METHODCONST: {
2639 MonoMethod *method = patch_info->data.method;
2641 if (method->wrapper_type) {
2642 switch (method->wrapper_type) {
2643 case MONO_WRAPPER_NONE:
2644 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2645 case MONO_WRAPPER_XDOMAIN_INVOKE:
2646 case MONO_WRAPPER_STFLD:
2647 case MONO_WRAPPER_LDFLD:
2648 case MONO_WRAPPER_LDFLDA:
2649 case MONO_WRAPPER_LDFLD_REMOTE:
2650 case MONO_WRAPPER_STFLD_REMOTE:
2651 case MONO_WRAPPER_STELEMREF:
2652 case MONO_WRAPPER_ISINST:
2653 case MONO_WRAPPER_PROXY_ISINST:
2654 case MONO_WRAPPER_ALLOC:
2655 case MONO_WRAPPER_REMOTING_INVOKE:
2656 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
2657 case MONO_WRAPPER_UNKNOWN:
2660 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2664 if (!method->token) {
2665 /* The method is part of a constructed type like Int[,].Set (). */
2666 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2667 if (method->klass->rank)
2675 case MONO_PATCH_INFO_VTABLE:
2676 case MONO_PATCH_INFO_CLASS_INIT:
2677 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2678 case MONO_PATCH_INFO_CLASS:
2679 case MONO_PATCH_INFO_IID:
2680 case MONO_PATCH_INFO_ADJUSTED_IID:
2681 if (!can_encode_class (acfg, patch_info->data.klass)) {
2682 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
2686 case MONO_PATCH_INFO_RGCTX_FETCH: {
2687 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2689 if (!can_encode_patch (acfg, entry->data))
2701 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
2706 * AOT compile a given method.
2707 * This function might be called by multiple threads, so it must be thread-safe.
2710 compile_method (MonoAotCompile *acfg, MonoMethod *method)
2713 MonoJumpInfo *patch_info;
2716 MonoMethod *wrapped;
2718 if (acfg->aot_opts.metadata_only)
2721 mono_acfg_lock (acfg);
2722 index = get_method_index (acfg, method);
2723 mono_acfg_unlock (acfg);
2725 /* fixme: maybe we can also precompile wrapper methods */
2726 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2727 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2728 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
2729 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
2733 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2736 wrapped = mono_marshal_method_from_wrapper (method);
2737 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
2738 // FIXME: The wrapper should be generic too, but it is not
2741 InterlockedIncrement (&acfg->stats.mcount);
2744 if (method->is_generic || method->klass->generic_container) {
2745 InterlockedIncrement (&acfg->stats.genericcount);
2750 //acfg->aot_opts.print_skipped_methods = TRUE;
2752 if (acfg->aot_opts.full_aot)
2753 mono_use_imt = FALSE;
2756 * Since these methods are the only ones which are compiled with
2757 * AOT support, and they are not used by runtime startup/shutdown code,
2758 * the runtime will not see AOT methods during AOT compilation,so it
2759 * does not need to support them by creating a fake GOT etc.
2761 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
2762 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
2763 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2764 InterlockedIncrement (&acfg->stats.genericcount);
2767 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
2768 /* Let the exception happen at runtime */
2772 if (cfg->disable_aot) {
2773 if (acfg->aot_opts.print_skipped_methods)
2774 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
2775 InterlockedIncrement (&acfg->stats.ocount);
2776 mono_destroy_compile (cfg);
2780 /* Nullify patches which need no aot processing */
2781 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2782 switch (patch_info->type) {
2783 case MONO_PATCH_INFO_LABEL:
2784 case MONO_PATCH_INFO_BB:
2785 patch_info->type = MONO_PATCH_INFO_NONE;
2792 /* Collect method->token associations from the cfg */
2793 mono_acfg_lock (acfg);
2794 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
2795 mono_acfg_unlock (acfg);
2798 * Check for absolute addresses.
2801 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2802 switch (patch_info->type) {
2803 case MONO_PATCH_INFO_ABS:
2804 /* unable to handle this */
2813 if (acfg->aot_opts.print_skipped_methods)
2814 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
2815 InterlockedIncrement (&acfg->stats.abscount);
2816 mono_destroy_compile (cfg);
2820 /* Lock for the rest of the code */
2821 mono_acfg_lock (acfg);
2824 * Check for methods/klasses we can't encode.
2827 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2828 if (!can_encode_patch (acfg, patch_info))
2833 if (acfg->aot_opts.print_skipped_methods)
2834 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
2835 acfg->stats.ocount++;
2836 mono_destroy_compile (cfg);
2837 mono_acfg_unlock (acfg);
2841 /* Adds generic instances referenced by this method */
2842 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2843 switch (patch_info->type) {
2844 case MONO_PATCH_INFO_METHOD: {
2845 MonoMethod *m = patch_info->data.method;
2846 if (m->is_inflated) {
2847 if (!(mono_class_generic_sharing_enabled (m->klass) &&
2848 mono_method_is_generic_sharable_impl (m, FALSE)) &&
2849 !method_has_type_vars (m)) {
2850 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2851 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
2853 add_extra_method (acfg, m);
2855 add_generic_class (acfg, m->klass);
2864 /* Determine whenever the method has GOT slots */
2865 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2866 switch (patch_info->type) {
2867 case MONO_PATCH_INFO_GOT_OFFSET:
2868 case MONO_PATCH_INFO_NONE:
2870 case MONO_PATCH_INFO_IMAGE:
2871 /* The assembly is stored in GOT slot 0 */
2872 if (patch_info->data.image != acfg->image)
2873 cfg->has_got_slots = TRUE;
2876 if (!is_plt_patch (patch_info))
2877 cfg->has_got_slots = TRUE;
2882 if (!cfg->has_got_slots)
2883 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
2885 /* Make a copy of the patch info which is in the mempool */
2887 MonoJumpInfo *patches = NULL, *patches_end = NULL;
2889 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2890 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2893 patches = new_patch_info;
2895 patches_end->next = new_patch_info;
2896 patches_end = new_patch_info;
2898 cfg->patch_info = patches;
2900 /* Make a copy of the unwind info */
2902 GSList *l, *unwind_ops;
2906 for (l = cfg->unwind_ops; l; l = l->next) {
2907 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
2908 memcpy (op, l->data, sizeof (MonoUnwindOp));
2909 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
2911 cfg->unwind_ops = g_slist_reverse (unwind_ops);
2913 /* Make a copy of the argument/local info */
2915 MonoInst **args, **locals;
2916 MonoMethodSignature *sig;
2917 MonoMethodHeader *header;
2920 sig = mono_method_signature (method);
2921 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
2922 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2923 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
2924 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
2928 header = mono_method_get_header (method);
2929 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
2930 for (i = 0; i < header->num_locals; ++i) {
2931 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
2932 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
2934 cfg->locals = locals;
2937 /* Free some fields used by cfg to conserve memory */
2938 mono_mempool_destroy (cfg->mempool);
2939 cfg->mempool = NULL;
2940 g_free (cfg->varinfo);
2941 cfg->varinfo = NULL;
2945 mono_regstate_free (cfg->rs);
2949 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
2951 while (index >= acfg->cfgs_size) {
2952 MonoCompile **new_cfgs;
2955 new_size = acfg->cfgs_size * 2;
2956 new_cfgs = g_new0 (MonoCompile*, new_size);
2957 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
2958 g_free (acfg->cfgs);
2959 acfg->cfgs = new_cfgs;
2960 acfg->cfgs_size = new_size;
2962 acfg->cfgs [index] = cfg;
2964 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
2966 if (cfg->orig_method->wrapper_type)
2967 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
2969 mono_acfg_unlock (acfg);
2971 InterlockedIncrement (&acfg->stats.ccount);
2975 compile_thread_main (gpointer *user_data)
2977 MonoDomain *domain = user_data [0];
2978 MonoAotCompile *acfg = user_data [1];
2979 GPtrArray *methods = user_data [2];
2982 mono_thread_attach (domain);
2984 for (i = 0; i < methods->len; ++i)
2985 compile_method (acfg, g_ptr_array_index (methods, i));
2989 load_profile_files (MonoAotCompile *acfg)
2993 int file_index, res, method_index, i;
3000 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);
3002 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3007 infile = fopen (tmp, "r");
3010 printf ("Using profile data file '%s'\n", tmp);
3015 res = fscanf (infile, "%32s\n", ver);
3016 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3017 printf ("Profile file has wrong version or invalid.\n");
3023 res = fscanf (infile, "%d\n", &token);
3027 method_index = mono_metadata_token_index (token) - 1;
3029 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3030 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3035 /* Add missing methods */
3037 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3038 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3039 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3041 unordered = g_list_reverse (unordered);
3042 if (acfg->method_order)
3043 g_list_last (acfg->method_order)->next = unordered;
3045 acfg->method_order = unordered;
3051 * Collect all patches which have shared GOT entries and alloc entries for them. The
3052 * rest will get entries allocated during emit_code ().
3055 alloc_got_slots (MonoAotCompile *acfg)
3061 /* Slot 0 is reserved for the address of the current assembly */
3062 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3063 ji->type = MONO_PATCH_INFO_IMAGE;
3064 ji->data.image = acfg->image;
3066 get_shared_got_offset (acfg, ji);
3068 for (l = acfg->method_order; l != NULL; l = l->next) {
3069 i = GPOINTER_TO_UINT (l->data);
3071 if (acfg->cfgs [i]) {
3072 MonoCompile *cfg = acfg->cfgs [i];
3074 for (ji = cfg->patch_info; ji; ji = ji->next) {
3075 if (is_shared_got_patch (ji))
3076 get_shared_got_offset (acfg, ji);
3083 emit_code (MonoAotCompile *acfg)
3089 sprintf (symbol, "methods");
3090 emit_section_change (acfg, ".text", 0);
3091 emit_global (acfg, symbol, TRUE);
3092 emit_alignment (acfg, 8);
3093 emit_label (acfg, symbol);
3096 * Emit some padding so the local symbol for the first method doesn't have the
3097 * same address as 'methods'.
3099 emit_zero_bytes (acfg, 16);
3101 for (l = acfg->method_order; l != NULL; l = l->next) {
3102 i = GPOINTER_TO_UINT (l->data);
3105 emit_method_code (acfg, acfg->cfgs [i]);
3108 sprintf (symbol, "methods_end");
3109 emit_section_change (acfg, ".text", 0);
3110 emit_global (acfg, symbol, FALSE);
3111 emit_alignment (acfg, 8);
3112 emit_label (acfg, symbol);
3114 sprintf (symbol, "method_offsets");
3115 emit_section_change (acfg, ".text", 1);
3116 emit_global (acfg, symbol, FALSE);
3117 emit_alignment (acfg, 8);
3118 emit_label (acfg, symbol);
3120 for (i = 0; i < acfg->nmethods; ++i) {
3121 if (acfg->cfgs [i]) {
3122 sprintf (symbol, ".Lm_%x", i);
3123 emit_symbol_diff (acfg, symbol, "methods", 0);
3125 emit_int32 (acfg, 0xffffffff);
3132 emit_info (MonoAotCompile *acfg)
3138 /* Emit method info */
3139 sprintf (symbol, "method_info");
3140 emit_section_change (acfg, ".text", 1);
3141 emit_global (acfg, symbol, FALSE);
3142 emit_alignment (acfg, 8);
3143 emit_label (acfg, symbol);
3145 /* To reduce size of generated assembly code */
3146 sprintf (symbol, "mi");
3147 emit_label (acfg, symbol);
3149 for (l = acfg->method_order; l != NULL; l = l->next) {
3150 i = GPOINTER_TO_UINT (l->data);
3153 emit_method_info (acfg, acfg->cfgs [i]);
3156 sprintf (symbol, "method_info_offsets");
3157 emit_section_change (acfg, ".text", 1);
3158 emit_global (acfg, symbol, FALSE);
3159 emit_alignment (acfg, 8);
3160 emit_label (acfg, symbol);
3162 for (i = 0; i < acfg->nmethods; ++i) {
3163 if (acfg->cfgs [i]) {
3164 sprintf (symbol, ".Lm_%x_p", i);
3165 emit_symbol_diff (acfg, symbol, "mi", 0);
3167 emit_int32 (acfg, 0);
3173 typedef struct HashEntry {
3174 guint32 key, value, index;
3175 struct HashEntry *next;
3179 * emit_extra_methods:
3181 * Emit methods which are not in the METHOD table, like wrappers.
3184 emit_extra_methods (MonoAotCompile *acfg)
3186 int i, table_size, buf_size;
3189 guint32 *info_offsets;
3192 HashEntry *entry, *new_entry;
3195 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3197 buf_size = acfg->extra_methods->len * 256 + 256;
3198 p = buf = g_malloc (buf_size);
3200 /* Encode method info */
3202 /* So offsets are > 0 */
3205 for (i = 0; i < acfg->extra_methods->len; ++i) {
3206 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3207 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3213 info_offsets [i] = p - buf;
3215 if (method->wrapper_type) {
3218 // FIXME: Optimize disk usage
3219 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
3220 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3221 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
3223 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
3224 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3225 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
3227 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
3228 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3229 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
3231 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
3232 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3233 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
3236 name = mono_method_full_name (cfg->orig_method, TRUE);
3239 encode_value (1, p, &p);
3240 strcpy ((char*)p, name);
3241 p += strlen (name ) + 1;
3244 encode_value (0, p, &p);
3245 encode_method_ref (acfg, method, p, &p);
3248 g_assert ((p - buf) < buf_size);
3251 g_assert ((p - buf) < buf_size);
3253 /* Emit method info */
3254 sprintf (symbol, "extra_method_info");
3255 emit_section_change (acfg, ".text", 1);
3256 emit_global (acfg, symbol, FALSE);
3257 emit_alignment (acfg, 8);
3258 emit_label (acfg, symbol);
3260 emit_bytes (acfg, buf, p - buf);
3265 * Construct a chained hash table for mapping indexes in extra_method_info to
3268 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3269 table = g_ptr_array_sized_new (table_size);
3270 for (i = 0; i < table_size; ++i)
3271 g_ptr_array_add (table, NULL);
3272 for (i = 0; i < acfg->extra_methods->len; ++i) {
3273 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3274 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3280 key = info_offsets [i];
3281 value = get_method_index (acfg, method);
3283 if (method->wrapper_type) {
3284 hash = g_str_hash (method->name) % table_size;
3287 hash = 0 % table_size;
3290 /* FIXME: Allocate from the mempool */
3291 new_entry = g_new0 (HashEntry, 1);
3292 new_entry->key = key;
3293 new_entry->value = value;
3295 entry = g_ptr_array_index (table, hash);
3296 if (entry == NULL) {
3297 new_entry->index = hash;
3298 g_ptr_array_index (table, hash) = new_entry;
3301 entry = entry->next;
3303 entry->next = new_entry;
3304 new_entry->index = table->len;
3305 g_ptr_array_add (table, new_entry);
3309 /* Emit the table */
3310 sprintf (symbol, "extra_method_table");
3311 emit_section_change (acfg, ".text", 0);
3312 emit_global (acfg, symbol, FALSE);
3313 emit_alignment (acfg, 8);
3314 emit_label (acfg, symbol);
3316 g_assert (table_size < 65000);
3317 emit_int32 (acfg, table_size);
3318 g_assert (table->len < 65000);
3319 for (i = 0; i < table->len; ++i) {
3320 HashEntry *entry = g_ptr_array_index (table, i);
3322 if (entry == NULL) {
3323 emit_int32 (acfg, 0);
3324 emit_int32 (acfg, 0);
3325 emit_int32 (acfg, 0);
3327 g_assert (entry->key > 0);
3328 emit_int32 (acfg, entry->key);
3329 emit_int32 (acfg, entry->value);
3331 emit_int32 (acfg, entry->next->index);
3333 emit_int32 (acfg, 0);
3338 * Emit a table reverse mapping method indexes to their index in extra_method_info.
3339 * This is used by mono_aot_find_jit_info ().
3341 sprintf (symbol, "extra_method_info_offsets");
3342 emit_section_change (acfg, ".text", 0);
3343 emit_global (acfg, symbol, FALSE);
3344 emit_alignment (acfg, 8);
3345 emit_label (acfg, symbol);
3347 emit_int32 (acfg, acfg->extra_methods->len);
3348 for (i = 0; i < acfg->extra_methods->len; ++i) {
3349 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3351 emit_int32 (acfg, get_method_index (acfg, method));
3352 emit_int32 (acfg, info_offsets [i]);
3357 emit_method_order (MonoAotCompile *acfg)
3363 sprintf (symbol, "method_order");
3364 emit_section_change (acfg, ".text", 1);
3365 emit_global (acfg, symbol, FALSE);
3366 emit_alignment (acfg, 8);
3367 emit_label (acfg, symbol);
3369 /* First emit an index table */
3372 for (l = acfg->method_order; l != NULL; l = l->next) {
3373 i = GPOINTER_TO_UINT (l->data);
3375 if (acfg->cfgs [i]) {
3376 if ((index % 1024) == 0) {
3377 emit_int32 (acfg, i);
3385 emit_int32 (acfg, 0xffffff);
3387 /* Then emit the whole method order */
3388 for (l = acfg->method_order; l != NULL; l = l->next) {
3389 i = GPOINTER_TO_UINT (l->data);
3391 if (acfg->cfgs [i]) {
3392 emit_int32 (acfg, i);
3397 sprintf (symbol, "method_order_end");
3398 emit_section_change (acfg, ".text", 1);
3399 emit_global (acfg, symbol, FALSE);
3400 emit_label (acfg, symbol);
3404 emit_exception_info (MonoAotCompile *acfg)
3409 sprintf (symbol, "ex_info");
3410 emit_section_change (acfg, ".text", 1);
3411 emit_global (acfg, symbol, FALSE);
3412 emit_alignment (acfg, 8);
3413 emit_label (acfg, symbol);
3415 /* To reduce size of generated assembly */
3416 sprintf (symbol, "ex");
3417 emit_label (acfg, symbol);
3419 for (i = 0; i < acfg->nmethods; ++i) {
3421 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3424 sprintf (symbol, "ex_info_offsets");
3425 emit_section_change (acfg, ".text", 1);
3426 emit_global (acfg, symbol, FALSE);
3427 emit_alignment (acfg, 8);
3428 emit_label (acfg, symbol);
3430 for (i = 0; i < acfg->nmethods; ++i) {
3431 if (acfg->cfgs [i]) {
3432 sprintf (symbol, ".Le_%x_p", i);
3433 emit_symbol_diff (acfg, symbol, "ex", 0);
3435 emit_int32 (acfg, 0);
3442 emit_class_info (MonoAotCompile *acfg)
3447 sprintf (symbol, "class_info");
3448 emit_section_change (acfg, ".text", 1);
3449 emit_global (acfg, symbol, FALSE);
3450 emit_alignment (acfg, 8);
3451 emit_label (acfg, symbol);
3453 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3454 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3456 sprintf (symbol, "class_info_offsets");
3457 emit_section_change (acfg, ".text", 1);
3458 emit_global (acfg, symbol, FALSE);
3459 emit_alignment (acfg, 8);
3460 emit_label (acfg, symbol);
3462 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3463 sprintf (symbol, ".LK_I_%x", i);
3464 emit_symbol_diff (acfg, symbol, "class_info", 0);
3469 typedef struct ClassNameTableEntry {
3470 guint32 token, index;
3471 struct ClassNameTableEntry *next;
3472 } ClassNameTableEntry;
3475 emit_class_name_table (MonoAotCompile *acfg)
3478 guint32 token, hash;
3483 ClassNameTableEntry *entry, *new_entry;
3486 * Construct a chained hash table for mapping class names to typedef tokens.
3488 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
3489 table = g_ptr_array_sized_new (table_size);
3490 for (i = 0; i < table_size; ++i)
3491 g_ptr_array_add (table, NULL);
3492 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3493 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3494 klass = mono_class_get (acfg->image, token);
3495 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
3496 hash = g_str_hash (full_name) % table_size;
3499 /* FIXME: Allocate from the mempool */
3500 new_entry = g_new0 (ClassNameTableEntry, 1);
3501 new_entry->token = token;
3503 entry = g_ptr_array_index (table, hash);
3504 if (entry == NULL) {
3505 new_entry->index = hash;
3506 g_ptr_array_index (table, hash) = new_entry;
3509 entry = entry->next;
3511 entry->next = new_entry;
3512 new_entry->index = table->len;
3513 g_ptr_array_add (table, new_entry);
3517 /* Emit the table */
3518 sprintf (symbol, "class_name_table");
3519 emit_section_change (acfg, ".text", 0);
3520 emit_global (acfg, symbol, FALSE);
3521 emit_alignment (acfg, 8);
3522 emit_label (acfg, symbol);
3524 /* FIXME: Optimize memory usage */
3525 g_assert (table_size < 65000);
3526 emit_int16 (acfg, table_size);
3527 g_assert (table->len < 65000);
3528 for (i = 0; i < table->len; ++i) {
3529 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3531 if (entry == NULL) {
3532 emit_int16 (acfg, 0);
3533 emit_int16 (acfg, 0);
3535 emit_int16 (acfg, mono_metadata_token_index (entry->token));
3537 emit_int16 (acfg, entry->next->index);
3539 emit_int16 (acfg, 0);
3545 emit_image_table (MonoAotCompile *acfg)
3551 * The image table is small but referenced in a lot of places.
3552 * So we emit it at once, and reference its elements by an index.
3555 sprintf (symbol, "mono_image_table");
3556 emit_section_change (acfg, ".text", 1);
3557 emit_global (acfg, symbol, FALSE);
3558 emit_alignment (acfg, 8);
3559 emit_label (acfg, symbol);
3561 emit_int32 (acfg, acfg->image_table->len);
3562 for (i = 0; i < acfg->image_table->len; i++) {
3563 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3564 MonoAssemblyName *aname = &image->assembly->aname;
3566 /* FIXME: Support multi-module assemblies */
3567 g_assert (image->assembly->image == image);
3569 emit_string (acfg, image->assembly_name);
3570 emit_string (acfg, image->guid);
3571 emit_string (acfg, aname->culture ? aname->culture : "");
3572 emit_string (acfg, (const char*)aname->public_key_token);
3574 emit_alignment (acfg, 8);
3575 emit_int32 (acfg, aname->flags);
3576 emit_int32 (acfg, aname->major);
3577 emit_int32 (acfg, aname->minor);
3578 emit_int32 (acfg, aname->build);
3579 emit_int32 (acfg, aname->revision);
3584 emit_got_info (MonoAotCompile *acfg)
3587 int i, first_plt_got_patch, buf_size;
3589 guint32 *got_info_offsets;
3591 /* Add the patches needed by the PLT to the GOT */
3592 acfg->plt_got_offset_base = acfg->got_offset;
3593 first_plt_got_patch = acfg->shared_patches->len;
3594 for (i = 1; i < acfg->plt_offset; ++i) {
3595 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3597 g_ptr_array_add (acfg->shared_patches, patch_info);
3600 acfg->got_offset += acfg->plt_offset;
3604 * - optimize offsets table.
3605 * - reduce number of exported symbols.
3606 * - emit info for a klass only once.
3607 * - determine when a method uses a GOT slot which is guaranteed to be already
3609 * - clean up and document the code.
3610 * - use String.Empty in class libs.
3613 /* Encode info required to decode shared GOT entries */
3614 buf_size = acfg->shared_patches->len * 64;
3615 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3616 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3617 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
3618 for (i = 0; i < acfg->shared_patches->len; ++i) {
3619 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3621 got_info_offsets [i] = p - buf;
3622 /* No need to encode the patch type for non-PLT patches */
3623 if (i >= first_plt_got_patch) {
3624 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
3625 encode_value (ji->type, p, &p);
3627 encode_patch (acfg, ji, p, &p);
3630 g_assert (p - buf <= buf_size);
3632 acfg->stats.got_info_size = p - buf;
3634 /* Emit got_info table */
3635 sprintf (symbol, "got_info");
3636 emit_section_change (acfg, ".text", 1);
3637 emit_global (acfg, symbol, FALSE);
3638 emit_alignment (acfg, 8);
3639 emit_label (acfg, symbol);
3641 emit_bytes (acfg, buf, p - buf);
3643 /* Emit got_info_offsets table */
3644 sprintf (symbol, "got_info_offsets");
3645 emit_section_change (acfg, ".text", 1);
3646 emit_global (acfg, symbol, FALSE);
3647 emit_alignment (acfg, 8);
3648 emit_label (acfg, symbol);
3650 for (i = 0; i < acfg->shared_patches->len; ++i)
3651 emit_int32 (acfg, got_info_offsets [i]);
3653 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3657 emit_got (MonoAotCompile *acfg)
3661 /* Don't make GOT global so accesses to it don't need relocations */
3662 sprintf (symbol, "got");
3663 emit_section_change (acfg, ".bss", 0);
3664 emit_alignment (acfg, 8);
3665 emit_label (acfg, symbol);
3666 if (acfg->got_offset > 0)
3667 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3671 emit_globals (MonoAotCompile *acfg)
3676 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3678 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3680 opts_str = g_strdup_printf ("%d", acfg->opts);
3681 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3684 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
3686 if (acfg->aot_opts.bind_to_runtime_version) {
3687 build_info = mono_get_runtime_build_info ();
3688 emit_string_symbol (acfg, "mono_runtime_version", build_info);
3689 g_free (build_info);
3691 emit_string_symbol (acfg, "mono_runtime_version", "");
3695 * Some platforms like the iphone have no working dlsym (). To work around this,
3696 * we create an ELF ctor function which will be invoked by dlopen, and which
3697 * will call a function in the AOT loader to register the symbols used by the
3699 * When static linking, we emit a global which will point to the symbol table.
3701 if (acfg->aot_opts.no_dlsym) {
3705 if (acfg->aot_opts.static_link)
3706 /* Emit a string holding the assembly name */
3707 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
3709 /* Emit the names */
3710 for (i = 0; i < acfg->globals->len; ++i) {
3711 char *name = g_ptr_array_index (acfg->globals, i);
3713 sprintf (symbol, "name_%d", i);
3714 emit_section_change (acfg, ".text", 1);
3715 emit_label (acfg, symbol);
3716 emit_string (acfg, name);
3719 /* Emit the globals table */
3720 sprintf (symbol, "globals");
3721 emit_section_change (acfg, ".data", 0);
3722 /* This is not a global, since it is accessed by the init function */
3723 emit_alignment (acfg, 8);
3724 emit_label (acfg, symbol);
3726 for (i = 0; i < acfg->globals->len; ++i) {
3727 char *name = g_ptr_array_index (acfg->globals, i);
3729 sprintf (symbol, "name_%d", i);
3730 emit_pointer (acfg, symbol);
3732 sprintf (symbol, "%s", name);
3733 emit_pointer (acfg, symbol);
3735 /* Null terminate the table */
3736 emit_pointer (acfg, NULL);
3737 emit_pointer (acfg, NULL);
3740 if (acfg->aot_opts.static_link) {
3744 * Emit a global symbol which can be passed by an embedding app to
3745 * mono_aot_register_module ().
3747 #if defined(__MACH__)
3748 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
3750 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
3753 /* Get rid of characters which cannot occur in symbols */
3755 for (p = symbol; *p; ++p) {
3756 if (!(isalnum (*p) || *p == '_'))
3759 acfg->static_linking_symbol = g_strdup (symbol);
3760 emit_global_inner (acfg, symbol, FALSE);
3761 emit_alignment (acfg, 8);
3762 emit_label (acfg, symbol);
3763 emit_pointer (acfg, "globals");
3765 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
3766 emit_section_change (acfg, ".text", 1);
3767 emit_alignment (acfg, 8);
3768 emit_label (acfg, symbol);
3769 if (acfg->use_bin_writer)
3770 g_assert_not_reached ();
3772 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
3773 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
3774 fprintf (acfg->fp, "ret\n");
3775 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
3776 emit_alignment (acfg, 8);
3777 emit_pointer (acfg, symbol);
3778 #elif defined(__arm__) && defined(__MACH__)
3780 fprintf (acfg->fp, ".text\n");
3781 fprintf (acfg->fp, ".align 3\n");
3783 fprintf (acfg->fp, "ldr r0, .L5\n");
3784 fprintf (acfg->fp, ".LPIC0:\n");
3785 fprintf (acfg->fp, "add r0, pc, r0\n");
3786 fprintf (acfg->fp, "ldr r0, [r0]\n");
3787 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
3788 fprintf (acfg->fp, ".align 2\n");
3790 fprintf (acfg->fp, ".L5:\n");
3791 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
3793 fprintf (acfg->fp, ".data\n");
3794 fprintf (acfg->fp, ".align 2\n");
3795 fprintf (acfg->fp, "globals_ptr:\n");
3796 fprintf (acfg->fp, ".long globals\n");
3798 fprintf (acfg->fp, ".mod_init_func\n");
3799 fprintf (acfg->fp, ".align 2\n");
3800 fprintf (acfg->fp, ".long %s@target1\n", symbol);
3802 #elif defined(__arm__)
3804 * Taken from gcc generated code for:
3806 * void foo () { bar (&i); }
3807 * gcc --shared -fPIC -O2
3809 fprintf (acfg->fp, "ldr r3, .L5\n");
3810 fprintf (acfg->fp, "ldr r0, .L5+4\n");
3811 fprintf (acfg->fp, ".LPIC0:\n");
3812 fprintf (acfg->fp, "add r3, pc, r3\n");
3813 fprintf (acfg->fp, "add r0, r3, r0\n");
3814 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
3816 fprintf (acfg->fp, ".L5:\n");
3817 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
3818 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
3820 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
3821 fprintf (acfg->fp, ".align 2\n");
3822 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
3824 g_assert_not_reached ();
3832 * Emit a structure containing all the information not stored elsewhere.
3835 emit_file_info (MonoAotCompile *acfg)
3839 sprintf (symbol, "mono_aot_file_info");
3840 emit_section_change (acfg, ".data", 0);
3841 emit_alignment (acfg, 8);
3842 emit_label (acfg, symbol);
3843 emit_global (acfg, symbol, FALSE);
3845 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
3846 emit_int32 (acfg, acfg->plt_got_offset_base);
3847 emit_int32 (acfg, acfg->trampoline_got_offset_base);
3848 emit_int32 (acfg, acfg->num_aot_trampolines);
3849 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3850 emit_int32 (acfg, acfg->plt_offset);
3851 emit_int32 (acfg, acfg->specific_trampoline_size);
3852 emit_pointer (acfg, "got");
3855 /*****************************************/
3856 /* Emitting DWARF debug information */
3857 /*****************************************/
3860 emit_dwarf_info (MonoAotCompile *acfg)
3862 #ifdef EMIT_DWARF_INFO
3864 char symbol [128], symbol2 [128];
3866 /* DIEs for methods */
3867 for (i = 0; i < acfg->nmethods; ++i) {
3868 MonoCompile *cfg = acfg->cfgs [i];
3873 sprintf (symbol, ".Lm_%x", i);
3874 sprintf (symbol2, ".Lme_%x", i);
3876 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
3882 compile_asm (MonoAotCompile *acfg)
3884 char *command, *objfile;
3885 char *outfile_name, *tmp_outfile_name;
3887 #if defined(__x86_64__)
3888 #define AS_OPTIONS "--64"
3889 #elif defined(sparc) && SIZEOF_VOID_P == 8
3890 #define AS_OPTIONS "-xarch=v9"
3892 #define AS_OPTIONS ""
3895 if (acfg->aot_opts.asm_only) {
3896 printf ("Output file: '%s'.\n", acfg->tmpfname);
3897 if (acfg->aot_opts.static_link)
3898 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
3902 if (acfg->aot_opts.static_link) {
3903 if (acfg->aot_opts.outfile)
3904 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
3906 objfile = g_strdup_printf ("%s.o", acfg->image->name);
3908 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
3910 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
3911 printf ("Executing the native assembler: %s\n", command);
3912 if (system (command) != 0) {
3920 if (acfg->aot_opts.static_link) {
3921 printf ("Output file: '%s'.\n", objfile);
3922 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
3927 if (acfg->aot_opts.outfile)
3928 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
3930 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
3932 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
3935 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
3936 #elif defined(__ppc__) && defined(__MACH__)
3937 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
3938 #elif defined(PLATFORM_WIN32)
3939 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
3941 if (acfg->aot_opts.no_dlsym) {
3943 * Need to link using gcc so our ctor function gets called.
3945 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
3947 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
3950 printf ("Executing the native linker: %s\n", command);
3951 if (system (command) != 0) {
3952 g_free (tmp_outfile_name);
3953 g_free (outfile_name);
3961 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
3962 printf ("Stripping the binary: %s\n", com);
3966 rename (tmp_outfile_name, outfile_name);
3968 g_free (tmp_outfile_name);
3969 g_free (outfile_name);
3972 if (acfg->aot_opts.save_temps)
3973 printf ("Retained input file.\n");
3975 unlink (acfg->tmpfname);
3981 acfg_free (MonoAotCompile *acfg)
3985 img_writer_destroy (acfg->w);
3986 for (i = 0; i < acfg->nmethods; ++i)
3988 g_free (acfg->cfgs [i]);
3989 g_free (acfg->cfgs);
3990 g_free (acfg->static_linking_symbol);
3991 g_ptr_array_free (acfg->methods, TRUE);
3992 g_ptr_array_free (acfg->shared_patches, TRUE);
3993 g_ptr_array_free (acfg->image_table, TRUE);
3994 g_ptr_array_free (acfg->globals, TRUE);
3995 g_hash_table_destroy (acfg->method_indexes);
3996 g_hash_table_destroy (acfg->plt_offset_to_patch);
3997 g_hash_table_destroy (acfg->patch_to_plt_offset);
3998 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
3999 g_hash_table_destroy (acfg->method_to_cfg);
4000 g_hash_table_destroy (acfg->token_info_hash);
4001 g_hash_table_destroy (acfg->image_hash);
4002 mono_mempool_destroy (acfg->mempool);
4007 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4009 MonoImage *image = ass->image;
4011 int i, res, methods_len;
4012 MonoAotCompile *acfg;
4013 char *outfile_name, *tmp_outfile_name;
4017 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4019 acfg = g_new0 (MonoAotCompile, 1);
4020 acfg->methods = g_ptr_array_new ();
4021 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4022 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4023 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4024 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4025 acfg->shared_patches = g_ptr_array_new ();
4026 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4027 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4028 acfg->image_hash = g_hash_table_new (NULL, NULL);
4029 acfg->image_table = g_ptr_array_new ();
4030 acfg->globals = g_ptr_array_new ();
4031 acfg->image = image;
4033 acfg->mempool = mono_mempool_new ();
4034 acfg->extra_methods = g_ptr_array_new ();
4035 InitializeCriticalSection (&acfg->mutex);
4037 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4038 acfg->aot_opts.write_symbols = TRUE;
4040 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4042 //acfg->aot_opts.print_skipped_methods = TRUE;
4044 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4045 if (acfg->aot_opts.outfile)
4046 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4048 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4050 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4052 acfg->fp = fopen (tmp_outfile_name, "w");
4053 g_assert (acfg->fp);
4055 acfg->w = img_writer_create (acfg->fp, TRUE);
4056 acfg->use_bin_writer = TRUE;
4058 if (acfg->aot_opts.asm_only) {
4059 if (acfg->aot_opts.outfile)
4060 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4062 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4063 acfg->fp = fopen (acfg->tmpfname, "w+");
4065 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4066 acfg->fp = fdopen (i, "w+");
4068 g_assert (acfg->fp);
4070 acfg->w = img_writer_create (acfg->fp, FALSE);
4072 /* hush compiler warnings about these being possibly uninitialized */
4073 tmp_outfile_name = NULL;
4074 outfile_name = NULL;
4077 load_profile_files (acfg);
4079 img_writer_emit_start (acfg->w);
4081 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4083 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4085 acfg->method_index = 1;
4087 /* Collect methods */
4088 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4090 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4092 method = mono_get_method (acfg->image, token, NULL);
4095 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4099 /* Load all methods eagerly to skip the slower lazy loading code */
4100 mono_class_setup_methods (method->klass);
4102 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4103 /* Compile the wrapper instead */
4104 /* We do this here instead of add_wrappers () because it is easy to do it here */
4105 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4109 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4110 add_method_with_index (acfg, method, i);
4111 acfg->method_index ++;
4114 add_generic_instances (acfg);
4116 if (acfg->aot_opts.full_aot)
4117 add_wrappers (acfg);
4119 acfg->cfgs_size = acfg->methods->len + 32;
4120 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4122 /* PLT offset 0 is reserved for the PLT trampoline */
4123 acfg->plt_offset = 1;
4125 /* Compile methods */
4128 if (acfg->aot_opts.nthreads > 0) {
4133 gpointer *user_data;
4134 MonoMethod **methods;
4136 methods_len = acfg->methods->len;
4138 len = acfg->methods->len / acfg->aot_opts.nthreads;
4141 * Partition the list of methods into fragments, and hand it to threads to
4144 threads = g_ptr_array_new ();
4145 /* Make a copy since acfg->methods is modified by compile_method () */
4146 methods = g_new0 (MonoMethod*, methods_len);
4147 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4148 for (i = 0; i < methods_len; ++i)
4149 methods [i] = g_ptr_array_index (acfg->methods, i);
4151 while (i < methods_len) {
4152 frag = g_ptr_array_new ();
4153 for (j = 0; j < len; ++j) {
4154 if (i < methods_len) {
4155 g_ptr_array_add (frag, methods [i]);
4160 user_data = g_new0 (gpointer, 3);
4161 user_data [0] = mono_domain_get ();
4162 user_data [1] = acfg;
4163 user_data [2] = frag;
4165 handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4166 g_ptr_array_add (threads, handle);
4170 for (i = 0; i < threads->len; ++i) {
4171 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4177 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4178 for (i = methods_len; i < acfg->methods->len; ++i) {
4179 /* This can new methods to acfg->methods */
4180 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4185 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4189 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4191 alloc_got_slots (acfg);
4197 emit_extra_methods (acfg);
4199 emit_method_order (acfg);
4201 emit_trampolines (acfg);
4203 emit_class_name_table (acfg);
4205 emit_got_info (acfg);
4207 emit_exception_info (acfg);
4209 emit_class_info (acfg);
4213 emit_image_table (acfg);
4217 emit_file_info (acfg);
4219 emit_globals (acfg);
4221 emit_dwarf_info (acfg);
4223 sprintf (symbol, "mem_end");
4224 emit_section_change (acfg, ".text", 1);
4225 emit_global (acfg, symbol, FALSE);
4226 emit_alignment (acfg, 8);
4227 emit_label (acfg, symbol);
4231 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4233 printf ("Code: %d Info: %d Ex 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.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
4236 res = img_writer_emit_writeout (acfg->w);
4241 if (acfg->use_bin_writer) {
4242 rename (tmp_outfile_name, outfile_name);
4251 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4253 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);
4254 if (acfg->stats.genericcount)
4255 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4256 if (acfg->stats.abscount)
4257 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4258 if (acfg->stats.lmfcount)
4259 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4260 if (acfg->stats.ocount)
4261 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4262 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);
4263 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4264 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);
4266 printf ("GOT slot distribution:\n");
4267 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4268 if (acfg->stats.got_slot_types [i])
4269 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4277 * Support for emitting debug info for JITted code.
4279 * This works as follows:
4280 * - the runtime writes out an xdb.s file containing DWARF debug info.
4281 * - the user calls a gdb macro
4282 * - the macro compiles and loads this shared library using add-symbol-file.
4284 * This is based on the xdebug functionality in the Kaffe Java VM.
4286 * We emit assembly code instead of using the ELF writer, so we can emit debug info
4287 * incrementally as each method is JITted, and the debugger doesn't have to call
4288 * into the runtime to emit the shared library, which would cause all kinds of
4289 * complications, like threading issues, and the fact that the ELF writer's
4290 * emit_writeout () function cannot be called more than once.
4293 /* The recommended gdb macro is: */
4296 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4297 add-symbol-file xdb.so 0
4301 static MonoDwarfWriter *xdebug_writer;
4302 static CRITICAL_SECTION xdebug_mutex;
4303 static FILE *xdebug_fp;
4306 mono_xdebug_init (void)
4311 InitializeCriticalSection (&xdebug_mutex);
4314 xdebug_fp = fopen ("xdb.s", "w");
4316 w = img_writer_create (xdebug_fp, FALSE);
4318 img_writer_emit_start (w);
4320 /* This file will contain the IL code for methods which don't have debug info */
4321 il_file = fopen ("xdb.il", "w");
4323 xdebug_writer = mono_dwarf_writer_create (w, il_file);
4325 /* Emit something so the file has a text segment */
4326 img_writer_emit_section_change (w, ".text", 0);
4327 img_writer_emit_string (w, "");
4329 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4333 * mono_save_xdebug_info:
4335 * Emit debugging info for METHOD into an assembly file which can be assembled
4336 * and loaded into gdb to provide debugging info for JITted code.
4339 mono_save_xdebug_info (MonoCompile *cfg)
4344 EnterCriticalSection (&xdebug_mutex);
4345 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 ()));
4347 LeaveCriticalSection (&xdebug_mutex);
4351 * mono_save_trampoline_xdebug_info:
4353 * Same as mono_save_xdebug_info, but for trampolines.
4356 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4361 EnterCriticalSection (&xdebug_mutex);
4362 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4364 LeaveCriticalSection (&xdebug_mutex);
4372 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4378 mono_xdebug_init (void)
4383 mono_save_xdebug_info (MonoCompile *cfg)
4388 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)