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/monitor.h>
63 #include <mono/metadata/mempool-internals.h>
64 #include <mono/metadata/mono-endian.h>
65 #include <mono/utils/mono-logger.h>
66 #include <mono/utils/mono-compiler.h>
67 #include <mono/utils/mono-time.h>
70 #include "image-writer.h"
71 #include "dwarfwriter.h"
75 #define TV_DECLARE(name) gint64 name
76 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
77 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
80 #define SHARED_EXT ".dll"
81 #elif defined(__ppc__) && defined(__MACH__)
82 #define SHARED_EXT ".dylib"
84 #define SHARED_EXT ".so"
87 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
88 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
89 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
91 typedef struct MonoAotOptions {
94 gboolean write_symbols;
95 gboolean metadata_only;
96 gboolean bind_to_runtime_version;
103 gboolean print_skipped_methods;
106 typedef struct MonoAotStats {
107 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
108 int code_size, info_size, ex_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
109 int methods_without_got_slots, direct_calls, all_calls;
111 int got_slot_types [MONO_PATCH_INFO_NONE];
112 int jit_time, gen_time, link_time;
115 typedef struct MonoAotCompile {
118 GHashTable *method_indexes;
121 GHashTable *patch_to_plt_offset;
122 GHashTable *plt_offset_to_patch;
123 GHashTable *patch_to_shared_got_offset;
124 GPtrArray *shared_patches;
125 GHashTable *image_hash;
126 GHashTable *method_to_cfg;
127 GHashTable *token_info_hash;
128 GPtrArray *extra_methods;
129 GPtrArray *image_table;
132 guint32 *plt_got_info_offsets;
133 /* Number of trampolines emitted into the AOT file */
134 guint32 num_aot_trampolines;
135 guint32 got_offset, plt_offset, plt_got_offset_base;
136 /* Number of GOT entries reserved for trampolines */
137 guint32 num_trampoline_got_entries;
138 guint32 trampoline_got_offset_base;
139 guint32 specific_trampoline_size;
140 MonoAotOptions aot_opts;
143 MonoMemPool *mempool;
146 char *static_linking_symbol;
147 CRITICAL_SECTION mutex;
148 gboolean use_bin_writer;
150 MonoDwarfWriter *dwarf;
156 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
157 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
159 #ifdef HAVE_ARRAY_ELEM_INIT
160 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
161 #define MSGSTRFIELD1(line) str##line
162 static const struct msgstr_t {
163 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
164 #include "patch-info.h"
167 #define PATCH_INFO(a,b) b,
168 #include "patch-info.h"
171 static const gint16 opidx [] = {
172 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
173 #include "patch-info.h"
178 get_patch_name (int info)
180 return (const char*)&opstr + opidx [info];
184 #define PATCH_INFO(a,b) b,
185 static const char* const
186 patch_types [MONO_PATCH_INFO_NUM + 1] = {
187 #include "patch-info.h"
192 get_patch_name (int info)
194 return patch_types [info];
200 emit_global (MonoAotCompile *acfg, const char *name, gboolean func);
202 /* Wrappers around the image writer functions */
205 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
207 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
211 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
213 img_writer_emit_push_section (acfg->w, section_name, subsection);
217 emit_pop_section (MonoAotCompile *acfg)
219 img_writer_emit_pop_section (acfg->w);
223 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
225 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
229 emit_label (MonoAotCompile *acfg, const char *name)
231 img_writer_emit_label (acfg->w, name);
235 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
237 img_writer_emit_bytes (acfg->w, buf, size);
241 emit_string (MonoAotCompile *acfg, const char *value)
243 img_writer_emit_string (acfg->w, value);
247 emit_line (MonoAotCompile *acfg)
249 img_writer_emit_line (acfg->w);
253 emit_alignment (MonoAotCompile *acfg, int size)
255 img_writer_emit_alignment (acfg->w, size);
259 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
261 img_writer_emit_pointer_unaligned (acfg->w, target);
265 emit_pointer (MonoAotCompile *acfg, const char *target)
267 img_writer_emit_pointer (acfg->w, target);
271 emit_int16 (MonoAotCompile *acfg, int value)
273 img_writer_emit_int16 (acfg->w, value);
277 emit_int32 (MonoAotCompile *acfg, int value)
279 img_writer_emit_int32 (acfg->w, value);
283 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
285 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
289 emit_zero_bytes (MonoAotCompile *acfg, int num)
291 img_writer_emit_zero_bytes (acfg->w, num);
295 emit_byte (MonoAotCompile *acfg, guint8 val)
297 img_writer_emit_byte (acfg->w, val);
300 static G_GNUC_UNUSED void
301 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
303 img_writer_emit_global (acfg->w, name, func);
307 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
309 if (acfg->aot_opts.no_dlsym) {
310 g_ptr_array_add (acfg->globals, g_strdup (name));
312 img_writer_emit_global (acfg->w, name, func);
317 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
319 img_writer_emit_section_change (acfg->w, ".text", 1);
320 emit_global (acfg, name, FALSE);
321 img_writer_emit_label (acfg->w, name);
322 img_writer_emit_string (acfg->w, value);
325 static G_GNUC_UNUSED void
326 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
329 guint8 b = value & 0x7f;
331 if (value != 0) /* more bytes to come */
337 static G_GNUC_UNUSED void
338 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
341 gboolean negative = (value < 0);
348 /* the following is unnecessary if the
349 * implementation of >>= uses an arithmetic rather
350 * than logical shift for a signed left operand
354 value |= - ((gint64)1 <<(size - 7));
355 /* sign bit of byte is second high order bit (0x40) */
356 if ((value == 0 && !(byte & 0x40)) ||
357 (value == -1 && (byte & 0x40)))
361 emit_byte (acfg, byte);
365 static G_GNUC_UNUSED void
366 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
371 guint8 b = value & 0x7f;
373 if (value != 0) /* more bytes to come */
381 static G_GNUC_UNUSED void
382 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
385 gboolean negative = (value < 0);
393 /* the following is unnecessary if the
394 * implementation of >>= uses an arithmetic rather
395 * than logical shift for a signed left operand
399 value |= - (1 <<(size - 7));
400 /* sign bit of byte is second high order bit (0x40) */
401 if ((value == 0 && !(byte & 0x40)) ||
402 (value == -1 && (byte & 0x40)))
412 /* ARCHITECTURE SPECIFIC CODE */
414 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
415 #define EMIT_DWARF_INFO 1
419 * arch_emit_direct_call:
421 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
425 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
427 #if defined(__i386__) || defined(__x86_64__)
428 /* Need to make sure this is exactly 5 bytes long */
429 emit_byte (acfg, '\xe8');
430 emit_symbol_diff (acfg, target, ".", -4);
432 #elif defined(__arm__)
433 if (acfg->use_bin_writer) {
440 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
441 emit_bytes (acfg, buf, 4);
443 img_writer_emit_unset_mode (acfg->w);
444 fprintf (acfg->fp, "bl %s\n", target);
448 g_assert_not_reached ();
453 * arch_emit_got_access:
455 * The memory pointed to by CODE should hold native code for loading a GOT
456 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
457 * CODE_SIZE is set to the number of bytes emitted.
460 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
462 /* Emit beginning of instruction */
463 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
465 /* Emit the offset */
467 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
468 #elif defined(__i386__)
469 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
470 #elif defined(__arm__)
471 emit_symbol_diff (acfg, "got", ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
473 g_assert_not_reached ();
476 *code_size = mono_arch_get_patch_offset (code) + 4;
480 * arch_emit_plt_entry:
482 * Emit code for the PLT entry with index INDEX.
485 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
487 #if defined(__i386__)
489 /* It is filled up during loading by the AOT loader. */
490 emit_zero_bytes (acfg, 16);
492 /* Need to make sure this is 9 bytes long */
493 emit_byte (acfg, '\xe9');
494 emit_symbol_diff (acfg, "plt", ".", -4);
495 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
497 #elif defined(__x86_64__)
499 * We can't emit jumps because they are 32 bits only so they can't be patched.
500 * So we make indirect calls through GOT entries which are patched by the AOT
501 * loader to point to .Lpd entries.
502 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
504 /* jmpq *<offset>(%rip) */
505 emit_byte (acfg, '\xff');
506 emit_byte (acfg, '\x25');
507 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
508 /* Used by mono_aot_get_plt_info_offset */
509 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
510 #elif defined(__arm__)
515 * - optimize OP_AOTCONST implementation
516 * - optimize the PLT entries
517 * - optimize SWITCH AOT implementation
518 * - implement IMT support
521 if (acfg->use_bin_writer) {
522 /* We only emit 1 relocation since we implement it ourselves anyway */
523 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, "got", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
524 /* FIXME: A 2 instruction encoding is sufficient in most cases */
525 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
526 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
527 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
528 emit_bytes (acfg, buf, code - buf);
529 /* FIXME: Get rid of this */
530 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
531 /* Used by mono_aot_get_plt_info_offset */
532 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
534 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
535 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
536 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
537 emit_bytes (acfg, buf, code - buf);
538 emit_symbol_diff (acfg, "got", ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
539 /* Used by mono_aot_get_plt_info_offset */
540 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
543 g_assert_not_reached ();
548 * arch_emit_specific_trampoline:
550 * Emit code for a specific trampoline. OFFSET is the offset of the first of
551 * two GOT slots which contain the generic trampoline address and the trampoline
552 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
555 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
558 * The trampolines created here are variations of the specific
559 * trampolines created in mono_arch_create_specific_trampoline (). The
561 * - the generic trampoline address is taken from a got slot.
562 * - the offset of the got slot where the trampoline argument is stored
563 * is embedded in the instruction stream, and the generic trampoline
564 * can load the argument by loading the offset, adding it to the
565 * address of the trampoline to get the address of the got slot, and
566 * loading the argument from there.
567 * - all the trampolines should be of the same length.
569 #if defined(__x86_64__)
570 /* This should be exactly 16 bytes long */
572 /* call *<offset>(%rip) */
573 emit_byte (acfg, '\x41');
574 emit_byte (acfg, '\xff');
575 emit_byte (acfg, '\x15');
576 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4);
577 /* This should be relative to the start of the trampoline */
578 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 19);
579 emit_zero_bytes (acfg, 5);
580 #elif defined(__arm__)
584 /* This should be exactly 28 bytes long */
587 ARM_PUSH (code, 0x5fff);
588 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
589 /* Load the value from the GOT */
590 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
592 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
593 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
595 g_assert (code - buf == 20);
598 emit_bytes (acfg, buf, code - buf);
599 emit_symbol_diff (acfg, "got", ".", (offset * sizeof (gpointer)) - 4 + 8);
600 emit_symbol_diff (acfg, "got", ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
602 g_assert_not_reached ();
607 * arch_emit_unbox_trampoline:
609 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
610 * CALL_TARGET is the symbol pointing to the native code of METHOD.
613 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
615 #if defined(__x86_64__)
620 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
622 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
624 emit_bytes (acfg, buf, code - buf);
626 emit_byte (acfg, '\xe9');
627 emit_symbol_diff (acfg, call_target, ".", -4);
628 #elif defined(__arm__)
635 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
638 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
640 emit_bytes (acfg, buf, code - buf);
642 if (acfg->use_bin_writer)
643 g_assert_not_reached ();
645 fprintf (acfg->fp, "\n\tb %s\n", call_target);
647 g_assert_not_reached ();
652 * arch_get_cie_program:
654 * Get the unwind bytecode for the DWARF CIE.
657 arch_get_cie_program (void)
662 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
663 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
671 /* END OF ARCH SPECIFIC CODE */
674 mono_get_field_token (MonoClassField *field)
676 MonoClass *klass = field->parent;
679 for (i = 0; i < klass->field.count; ++i) {
680 if (field == &klass->fields [i])
681 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
684 g_assert_not_reached ();
689 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
693 //printf ("ENCODE: %d 0x%x.\n", value, value);
696 * Same encoding as the one used in the metadata, extended to handle values
697 * greater than 0x1fffffff.
699 if ((value >= 0) && (value <= 127))
701 else if ((value >= 0) && (value <= 16383)) {
702 p [0] = 0x80 | (value >> 8);
703 p [1] = value & 0xff;
705 } else if ((value >= 0) && (value <= 0x1fffffff)) {
706 p [0] = (value >> 24) | 0xc0;
707 p [1] = (value >> 16) & 0xff;
708 p [2] = (value >> 8) & 0xff;
709 p [3] = value & 0xff;
714 p [1] = (value >> 24) & 0xff;
715 p [2] = (value >> 16) & 0xff;
716 p [3] = (value >> 8) & 0xff;
717 p [4] = value & 0xff;
725 get_image_index (MonoAotCompile *cfg, MonoImage *image)
729 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
733 index = g_hash_table_size (cfg->image_hash);
734 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
735 g_ptr_array_add (cfg->image_table, image);
741 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
746 /* FIXME: Search referenced images as well */
747 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
748 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
753 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
754 return MONO_TOKEN_TYPE_SPEC | (i + 1);
760 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
765 * Encode a reference to KLASS. We use our home-grown encoding instead of the
766 * standard metadata encoding.
769 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
773 if (klass->generic_class) {
775 g_assert (klass->type_token);
777 /* Find a typespec for a class if possible */
778 token = find_typespec_for_class (acfg, klass);
780 encode_value (token, p, &p);
781 encode_value (get_image_index (acfg, acfg->image), p, &p);
783 MonoClass *gclass = klass->generic_class->container_class;
784 MonoGenericInst *inst = klass->generic_class->context.class_inst;
787 /* Encode it ourselves */
789 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
790 encode_value (MONO_TYPE_GENERICINST, p, &p);
791 encode_klass_ref (acfg, gclass, p, &p);
792 encode_value (inst->type_argc, p, &p);
793 for (i = 0; i < inst->type_argc; ++i)
794 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
796 } else if (klass->type_token) {
797 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
798 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
799 encode_value (get_image_index (acfg, klass->image), p, &p);
800 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
801 MonoGenericParam *param = klass->byval_arg.data.generic_param;
804 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
805 encode_value (klass->byval_arg.type, p, &p);
807 encode_value (param->num, p, &p);
809 g_assert (param->owner);
810 encode_value (param->owner->is_method, p, &p);
811 if (param->owner->is_method)
812 encode_method_ref (acfg, param->owner->owner.method, p, &p);
814 encode_klass_ref (acfg, param->owner->owner.klass, p, &p);
817 g_assert (klass->rank > 0);
818 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
819 encode_value (get_image_index (acfg, klass->image), p, &p);
820 encode_value (klass->rank, p, &p);
821 encode_klass_ref (acfg, klass->element_class, p, &p);
827 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
829 guint32 token = mono_get_field_token (field);
832 encode_klass_ref (cfg, field->parent, p, &p);
833 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
834 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
839 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
843 MonoGenericInst *inst;
845 /* Encode the context */
846 inst = context->class_inst;
847 encode_value (inst ? 1 : 0, p, &p);
849 encode_value (inst->type_argc, p, &p);
850 for (i = 0; i < inst->type_argc; ++i)
851 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
853 inst = context->method_inst;
854 encode_value (inst ? 1 : 0, p, &p);
856 encode_value (inst->type_argc, p, &p);
857 for (i = 0; i < inst->type_argc; ++i)
858 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
864 #define MAX_IMAGE_INDEX 250
867 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
869 guint32 image_index = get_image_index (acfg, method->klass->image);
870 guint32 token = method->token;
871 MonoJumpInfoToken *ji;
876 * The encoding for most methods is as follows:
877 * - image index encoded as a leb128
878 * - token index encoded as a leb128
879 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
880 * types of method encodings.
883 g_assert (image_index < MONO_AOT_METHODREF_MIN);
885 /* Mark methods which can't use aot trampolines because they need the further
886 * processing in mono_magic_trampoline () which requires a MonoMethod*.
888 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
889 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
890 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
893 * Some wrapper methods are shared using their signature, encode their
894 * stringified signature instead.
895 * FIXME: Optimize disk usage
898 if (method->wrapper_type) {
899 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
900 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
901 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
903 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
904 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
905 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
907 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
908 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
909 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
911 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
912 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
913 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
919 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
920 strcpy ((char*)p, name);
921 p += strlen (name) + 1;
923 } else if (method->wrapper_type) {
924 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
926 encode_value (method->wrapper_type, p, &p);
928 switch (method->wrapper_type) {
929 case MONO_WRAPPER_REMOTING_INVOKE:
930 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
931 case MONO_WRAPPER_XDOMAIN_INVOKE: {
934 m = mono_marshal_method_from_wrapper (method);
936 encode_method_ref (acfg, m, p, &p);
939 case MONO_WRAPPER_PROXY_ISINST:
940 case MONO_WRAPPER_LDFLD:
941 case MONO_WRAPPER_LDFLDA:
942 case MONO_WRAPPER_STFLD:
943 case MONO_WRAPPER_ISINST: {
944 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
945 encode_klass_ref (acfg, proxy_class, p, &p);
948 case MONO_WRAPPER_LDFLD_REMOTE:
949 case MONO_WRAPPER_STFLD_REMOTE:
951 case MONO_WRAPPER_ALLOC: {
952 int alloc_type = mono_gc_get_managed_allocator_type (method);
953 g_assert (alloc_type != -1);
954 encode_value (alloc_type, p, &p);
957 case MONO_WRAPPER_STELEMREF:
959 case MONO_WRAPPER_UNKNOWN:
960 if (strcmp (method->name, "FastMonitorEnter") == 0)
961 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
962 else if (strcmp (method->name, "FastMonitorExit") == 0)
963 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
965 g_assert_not_reached ();
967 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
968 case MONO_WRAPPER_SYNCHRONIZED: {
971 m = mono_marshal_method_from_wrapper (method);
973 encode_method_ref (acfg, m, p, &p);
977 g_assert_not_reached ();
979 } else if (mono_method_signature (method)->is_inflated) {
981 * This is a generic method, find the original token which referenced it and
983 * Obtain the token from information recorded by the JIT.
985 ji = g_hash_table_lookup (acfg->token_info_hash, method);
987 image_index = get_image_index (acfg, ji->image);
988 g_assert (image_index < MAX_IMAGE_INDEX);
991 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
992 encode_value (image_index, p, &p);
993 encode_value (token, p, &p);
995 MonoMethod *declaring;
996 MonoGenericContext *context = mono_method_get_context (method);
998 g_assert (method->is_inflated);
999 declaring = ((MonoMethodInflated*)method)->declaring;
1002 * This might be a non-generic method of a generic instance, which
1003 * doesn't have a token since the reference is generated by the JIT
1004 * like Nullable:Box/Unbox, or by generic sharing.
1007 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1008 /* Encode the klass */
1009 encode_klass_ref (acfg, method->klass, p, &p);
1010 /* Encode the method */
1011 image_index = get_image_index (acfg, method->klass->image);
1012 g_assert (image_index < MAX_IMAGE_INDEX);
1013 g_assert (declaring->token);
1014 token = declaring->token;
1015 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1016 encode_value (image_index, p, &p);
1017 encode_value (token, p, &p);
1018 encode_generic_context (acfg, context, p, &p);
1020 } else if (token == 0) {
1021 /* This might be a method of a constructed type like int[,].Set */
1022 /* Obtain the token from information recorded by the JIT */
1023 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1025 image_index = get_image_index (acfg, ji->image);
1026 g_assert (image_index < MAX_IMAGE_INDEX);
1029 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1030 encode_value (image_index, p, &p);
1031 encode_value (token, p, &p);
1034 g_assert (method->klass->rank);
1036 /* Encode directly */
1037 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1038 encode_klass_ref (acfg, method->klass, p, &p);
1039 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1040 encode_value (0, p, &p);
1041 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1042 encode_value (1, p, &p);
1043 else if (!strcmp (method->name, "Get"))
1044 encode_value (2, p, &p);
1045 else if (!strcmp (method->name, "Address"))
1046 encode_value (3, p, &p);
1047 else if (!strcmp (method->name, "Set"))
1048 encode_value (4, p, &p);
1050 g_assert_not_reached ();
1053 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1054 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1060 compare_patches (gconstpointer a, gconstpointer b)
1064 i = (*(MonoJumpInfo**)a)->ip.i;
1065 j = (*(MonoJumpInfo**)b)->ip.i;
1079 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1082 static inline gboolean
1083 is_plt_patch (MonoJumpInfo *patch_info)
1085 switch (patch_info->type) {
1086 case MONO_PATCH_INFO_METHOD:
1087 case MONO_PATCH_INFO_INTERNAL_METHOD:
1088 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1089 case MONO_PATCH_INFO_ICALL_ADDR:
1090 case MONO_PATCH_INFO_CLASS_INIT:
1091 case MONO_PATCH_INFO_RGCTX_FETCH:
1092 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1093 case MONO_PATCH_INFO_MONITOR_ENTER:
1094 case MONO_PATCH_INFO_MONITOR_EXIT:
1102 is_got_patch (MonoJumpInfoType patch_type)
1108 * is_shared_got_patch:
1110 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
1112 * Keep it in sync with the version in aot-runtime.c.
1114 static inline gboolean
1115 is_shared_got_patch (MonoJumpInfo *patch_info)
1117 switch (patch_info->type) {
1118 case MONO_PATCH_INFO_VTABLE:
1119 case MONO_PATCH_INFO_CLASS:
1120 case MONO_PATCH_INFO_IID:
1121 case MONO_PATCH_INFO_ADJUSTED_IID:
1122 case MONO_PATCH_INFO_FIELD:
1123 case MONO_PATCH_INFO_SFLDA:
1124 case MONO_PATCH_INFO_DECLSEC:
1125 case MONO_PATCH_INFO_LDTOKEN:
1126 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1127 case MONO_PATCH_INFO_RVA:
1128 case MONO_PATCH_INFO_METHODCONST:
1129 case MONO_PATCH_INFO_IMAGE:
1137 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1141 if (is_plt_patch (patch_info)) {
1142 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1144 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1146 * Allocate a separate PLT slot for each such patch, since some plt
1147 * entries will refer to the method itself, and some will refer to
1156 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1158 res = acfg->plt_offset;
1159 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1160 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1161 acfg->plt_offset ++;
1171 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1172 * JI could be found if it exists, otherwise allocates a new one.
1175 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1179 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1181 return got_offset - 1;
1183 got_offset = acfg->got_offset;
1184 acfg->got_offset ++;
1186 acfg->stats.got_slots ++;
1187 acfg->stats.got_slot_types [ji->type] ++;
1193 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1198 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1199 got_offset = get_got_offset (acfg, ji);
1200 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1201 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1202 g_ptr_array_add (acfg->shared_patches, copy);
1205 return get_got_offset (acfg, ji);
1208 /* Add a method to the list of methods which need to be emitted */
1210 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1213 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1214 g_ptr_array_add (acfg->methods, method);
1215 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1216 acfg->nmethods = acfg->methods->len + 1;
1221 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1223 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1231 add_method (MonoAotCompile *acfg, MonoMethod *method)
1235 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1239 index = acfg->method_index;
1240 add_method_with_index (acfg, method, index);
1242 /* FIXME: Fix quadratic behavior */
1243 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1245 acfg->method_index ++;
1251 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1255 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1258 add_method (acfg, method);
1259 g_ptr_array_add (acfg->extra_methods, method);
1263 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1265 MonoAotCompile *acfg = user_data;
1266 MonoJitICallInfo *callinfo = value;
1267 MonoMethod *wrapper;
1273 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1274 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1277 add_method (acfg, wrapper);
1281 get_runtime_invoke_sig (MonoMethodSignature *sig)
1283 MonoMethodBuilder *mb;
1286 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1287 m = mono_mb_create_method (mb, sig, 16);
1288 return mono_marshal_get_runtime_invoke (m);
1292 add_wrappers (MonoAotCompile *acfg)
1294 MonoMethod *method, *m;
1295 int i, j, nallocators;
1296 MonoMethodSignature *sig, *csig;
1300 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1301 * so there is only one wrapper of a given type, or inlining their contents into their
1306 * FIXME: This depends on the fact that different wrappers have different
1310 /* FIXME: Collect these automatically */
1312 /* Runtime invoke wrappers */
1314 /* void runtime-invoke () [.cctor] */
1315 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1316 csig->ret = &mono_defaults.void_class->byval_arg;
1317 add_method (acfg, get_runtime_invoke_sig (csig));
1319 /* void runtime-invoke () [Finalize] */
1320 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1322 csig->ret = &mono_defaults.void_class->byval_arg;
1323 add_method (acfg, get_runtime_invoke_sig (csig));
1325 /* void runtime-invoke (string) [exception ctor] */
1326 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1328 csig->ret = &mono_defaults.void_class->byval_arg;
1329 csig->params [0] = &mono_defaults.string_class->byval_arg;
1330 add_method (acfg, get_runtime_invoke_sig (csig));
1332 /* void runtime-invoke (string, string) [exception ctor] */
1333 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1335 csig->ret = &mono_defaults.void_class->byval_arg;
1336 csig->params [0] = &mono_defaults.string_class->byval_arg;
1337 csig->params [1] = &mono_defaults.string_class->byval_arg;
1338 add_method (acfg, get_runtime_invoke_sig (csig));
1340 /* string runtime-invoke () [Exception.ToString ()] */
1341 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1343 csig->ret = &mono_defaults.string_class->byval_arg;
1344 add_method (acfg, get_runtime_invoke_sig (csig));
1346 /* void runtime-invoke (string, Exception) [exception ctor] */
1347 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1349 csig->ret = &mono_defaults.void_class->byval_arg;
1350 csig->params [0] = &mono_defaults.string_class->byval_arg;
1351 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1352 add_method (acfg, get_runtime_invoke_sig (csig));
1354 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1355 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1357 csig->ret = &(mono_class_from_name (
1358 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1359 csig->params [0] = &mono_defaults.string_class->byval_arg;
1360 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1361 add_method (acfg, get_runtime_invoke_sig (csig));
1363 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1365 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1366 gboolean skip = FALSE;
1368 method = mono_get_method (acfg->image, token, NULL);
1370 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1371 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1372 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1375 if (method->is_generic || method->klass->generic_container)
1378 /* Skip methods which can not be handled by get_runtime_invoke () */
1379 sig = mono_method_signature (method);
1380 if ((sig->ret->type == MONO_TYPE_PTR) ||
1381 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1384 for (j = 0; j < sig->param_count; j++) {
1385 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1390 add_method (acfg, mono_marshal_get_runtime_invoke (method));
1393 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1394 MonoMethodDesc *desc;
1395 MonoMethod *orig_method;
1397 /* JIT icall wrappers */
1398 /* FIXME: locking */
1399 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1401 /* Managed Allocators */
1402 nallocators = mono_gc_get_managed_allocator_types ();
1403 for (i = 0; i < nallocators; ++i) {
1404 m = mono_gc_get_managed_allocator_by_type (i);
1406 add_method (acfg, m);
1410 add_method (acfg, mono_marshal_get_stelemref ());
1412 /* Monitor Enter/Exit */
1413 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1414 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1415 g_assert (orig_method);
1416 mono_method_desc_free (desc);
1417 method = mono_monitor_get_fast_path (orig_method);
1419 add_method (acfg, method);
1421 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1422 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1423 g_assert (orig_method);
1424 mono_method_desc_free (desc);
1425 method = mono_monitor_get_fast_path (orig_method);
1427 add_method (acfg, method);
1430 /* remoting-invoke wrappers */
1431 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1432 MonoMethodSignature *sig;
1434 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1435 method = mono_get_method (acfg->image, token, NULL);
1437 sig = mono_method_signature (method);
1439 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
1440 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
1441 m = mono_marshal_get_remoting_invoke_with_check (method);
1443 add_method (acfg, m);
1447 /* delegate-invoke wrappers */
1448 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1451 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1452 klass = mono_class_get (acfg->image, token);
1454 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1455 method = mono_get_delegate_invoke (klass);
1457 m = mono_marshal_get_delegate_invoke (method, NULL);
1459 add_method (acfg, m);
1461 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1462 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1464 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1465 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1469 /* Synchronized wrappers */
1470 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1471 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1472 method = mono_get_method (acfg->image, token, NULL);
1474 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1475 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1479 /* static rgctx wrappers */
1480 /* FIXME: Each wrapper belongs to a given instantiation of a generic method */
1481 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1482 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1483 method = mono_get_method (acfg->image, token, NULL);
1485 if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
1486 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
1487 mono_class_generic_sharing_enabled (method->klass) &&
1488 mono_method_is_generic_sharable_impl (method, FALSE)) {
1489 m = mono_marshal_get_static_rgctx_invoke (method);
1490 add_method (acfg, m);
1495 /* pinvoke wrappers */
1496 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1498 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1500 method = mono_get_method (acfg->image, token, NULL);
1502 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1503 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1504 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1510 has_type_vars (MonoClass *klass)
1512 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1515 return has_type_vars (klass->element_class);
1516 if (klass->generic_class) {
1517 MonoGenericContext *context = &klass->generic_class->context;
1518 if (context->class_inst) {
1521 for (i = 0; i < context->class_inst->type_argc; ++i)
1522 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1530 method_has_type_vars (MonoMethod *method)
1532 if (has_type_vars (method->klass))
1535 if (method->is_inflated) {
1536 MonoGenericContext *context = mono_method_get_context (method);
1537 if (context->method_inst) {
1540 for (i = 0; i < context->method_inst->type_argc; ++i)
1541 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1549 * add_generic_class:
1551 * Add all methods of a generic class.
1554 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1559 mono_class_init (klass);
1561 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1564 if (has_type_vars (klass))
1567 if (!klass->generic_class && !klass->rank)
1571 * Add rgctx wrappers for cctors since those are called by the runtime, so
1572 * there is no methodspec for them. This is needed even for shared classes,
1573 * since rgctx wrappers belong to inflated methods.
1575 method = mono_class_get_cctor (klass);
1576 if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
1577 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1580 while ((method = mono_class_get_methods (klass, &iter))) {
1581 if (mono_method_is_generic_sharable_impl (method, FALSE))
1585 if (method->is_generic)
1590 * FIXME: Instances which are referenced by these methods are not added,
1591 * for example Array.Resize<int> for List<int>.Add ().
1593 add_extra_method (acfg, method);
1598 * add_generic_instances:
1600 * Add instances referenced by the METHODSPEC/TYPESPEC table.
1603 add_generic_instances (MonoAotCompile *acfg)
1608 MonoGenericContext *context;
1610 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1611 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1612 method = mono_get_method (acfg->image, token, NULL);
1614 context = mono_method_get_context (method);
1615 if (context && ((context->class_inst && context->class_inst->is_open) ||
1616 (context->method_inst && context->method_inst->is_open)))
1619 if (method->klass->image != acfg->image)
1622 if (mono_method_is_generic_sharable_impl (method, FALSE))
1626 add_extra_method (acfg, method);
1629 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1632 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1634 klass = mono_class_get (acfg->image, token);
1638 add_generic_class (acfg, klass);
1643 * emit_and_reloc_code:
1645 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1646 * is true, calls are made through the GOT too. This is used for emitting trampolines
1647 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1648 * since trampolines are needed to make PTL work.
1651 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1653 int i, pindex, start_index, method_index;
1655 MonoJumpInfo *patch_info;
1656 MonoMethodHeader *header;
1657 gboolean skip, direct_call;
1659 char direct_call_target [128];
1662 header = mono_method_get_header (method);
1664 method_index = get_method_index (acfg, method);
1667 /* Collect and sort relocations */
1668 patches = g_ptr_array_new ();
1669 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1670 g_ptr_array_add (patches, patch_info);
1671 g_ptr_array_sort (patches, compare_patches);
1674 for (i = 0; i < code_len; i++) {
1676 for (pindex = start_index; pindex < patches->len; ++pindex) {
1677 patch_info = g_ptr_array_index (patches, pindex);
1678 if (patch_info->ip.i >= i)
1682 #ifdef MONO_ARCH_AOT_SUPPORTED
1684 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1685 start_index = pindex;
1687 switch (patch_info->type) {
1688 case MONO_PATCH_INFO_NONE:
1690 case MONO_PATCH_INFO_GOT_OFFSET: {
1691 guint32 offset = mono_arch_get_patch_offset (code + i);
1692 emit_bytes (acfg, code + i, offset);
1693 emit_symbol_diff (acfg, "got", ".", offset);
1695 i += offset + 4 - 1;
1700 if (!is_got_patch (patch_info->type))
1704 * If this patch is a call, try emitting a direct call instead of
1705 * through a PLT entry. This is possible if the called method is in
1706 * the same assembly and requires no initialization.
1708 direct_call = FALSE;
1709 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1710 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1712 gboolean direct_callable = TRUE;
1714 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1715 direct_callable = FALSE;
1716 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1717 // FIXME: Maybe call the wrapper directly ?
1718 direct_callable = FALSE;
1719 if (direct_callable) {
1720 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1722 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1723 patch_info->type = MONO_PATCH_INFO_NONE;
1724 acfg->stats.direct_calls ++;
1728 acfg->stats.all_calls ++;
1731 if (!got_only && !direct_call) {
1732 int plt_offset = get_plt_offset (acfg, patch_info);
1733 if (plt_offset != -1) {
1734 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1736 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1738 /* Nullify the patch */
1739 patch_info->type = MONO_PATCH_INFO_NONE;
1746 arch_emit_direct_call (acfg, direct_call_target, &call_size);
1751 got_slot = get_got_offset (acfg, patch_info);
1753 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1760 #endif /* MONO_ARCH_AOT_SUPPORTED */
1763 /* Find next patch */
1765 for (pindex = start_index; pindex < patches->len; ++pindex) {
1766 patch_info = g_ptr_array_index (patches, pindex);
1767 if (patch_info->ip.i >= i)
1771 /* Try to emit multiple bytes at once */
1772 if (pindex < patches->len && patch_info->ip.i > i) {
1773 emit_bytes (acfg, code + i, patch_info->ip.i - i);
1774 i = patch_info->ip.i - 1;
1776 emit_bytes (acfg, code + i, 1);
1783 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1789 int func_alignment = 16;
1790 MonoMethodHeader *header;
1792 method = cfg->orig_method;
1793 code = cfg->native_code;
1794 header = mono_method_get_header (method);
1796 method_index = get_method_index (acfg, method);
1798 /* Make the labels local */
1799 sprintf (symbol, ".Lm_%x", method_index);
1801 emit_alignment (acfg, func_alignment);
1802 emit_label (acfg, symbol);
1804 if (acfg->aot_opts.write_symbols && acfg->use_bin_writer) {
1806 /* Emit a local symbol into the symbol table */
1807 full_name = mono_method_full_name (method, TRUE);
1808 sprintf (symbol, ".Lme_%x", method_index);
1809 emit_local_symbol (acfg, full_name, symbol, TRUE);
1810 emit_label (acfg, full_name);
1814 if (cfg->verbose_level > 0)
1815 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
1817 acfg->stats.code_size += cfg->code_len;
1819 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
1821 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
1825 sprintf (symbol, ".Lme_%x", method_index);
1826 emit_label (acfg, symbol);
1832 * Encode PATCH_INFO into its disk representation.
1835 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
1839 switch (patch_info->type) {
1840 case MONO_PATCH_INFO_NONE:
1842 case MONO_PATCH_INFO_IMAGE:
1843 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
1845 case MONO_PATCH_INFO_METHOD_REL:
1846 encode_value ((gint)patch_info->data.offset, p, &p);
1848 case MONO_PATCH_INFO_SWITCH: {
1849 gpointer *table = (gpointer *)patch_info->data.table->table;
1852 encode_value (patch_info->data.table->table_size, p, &p);
1853 for (k = 0; k < patch_info->data.table->table_size; k++)
1854 encode_value ((int)(gssize)table [k], p, &p);
1857 case MONO_PATCH_INFO_METHODCONST:
1858 case MONO_PATCH_INFO_METHOD:
1859 case MONO_PATCH_INFO_METHOD_JUMP:
1860 case MONO_PATCH_INFO_ICALL_ADDR:
1861 case MONO_PATCH_INFO_METHOD_RGCTX:
1862 encode_method_ref (acfg, patch_info->data.method, p, &p);
1864 case MONO_PATCH_INFO_INTERNAL_METHOD:
1865 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
1866 guint32 len = strlen (patch_info->data.name);
1868 encode_value (len, p, &p);
1870 memcpy (p, patch_info->data.name, len);
1875 case MONO_PATCH_INFO_LDSTR: {
1876 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
1877 guint32 token = patch_info->data.token->token;
1878 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
1879 encode_value (image_index, p, &p);
1880 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
1883 case MONO_PATCH_INFO_RVA:
1884 case MONO_PATCH_INFO_DECLSEC:
1885 case MONO_PATCH_INFO_LDTOKEN:
1886 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
1887 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
1888 encode_value (patch_info->data.token->token, p, &p);
1889 encode_value (patch_info->data.token->has_context, p, &p);
1890 if (patch_info->data.token->has_context)
1891 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
1893 case MONO_PATCH_INFO_EXC_NAME: {
1894 MonoClass *ex_class;
1897 mono_class_from_name (mono_defaults.exception_class->image,
1898 "System", patch_info->data.target);
1899 g_assert (ex_class);
1900 encode_klass_ref (acfg, ex_class, p, &p);
1903 case MONO_PATCH_INFO_R4:
1904 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1906 case MONO_PATCH_INFO_R8:
1907 encode_value (*((guint32 *)patch_info->data.target), p, &p);
1908 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
1910 case MONO_PATCH_INFO_VTABLE:
1911 case MONO_PATCH_INFO_CLASS:
1912 case MONO_PATCH_INFO_IID:
1913 case MONO_PATCH_INFO_ADJUSTED_IID:
1914 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
1916 case MONO_PATCH_INFO_CLASS_INIT:
1917 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
1918 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
1920 case MONO_PATCH_INFO_FIELD:
1921 case MONO_PATCH_INFO_SFLDA:
1922 encode_field_info (acfg, patch_info->data.field, p, &p);
1924 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
1926 case MONO_PATCH_INFO_RGCTX_FETCH: {
1927 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
1929 encode_method_ref (acfg, entry->method, p, &p);
1930 encode_value (entry->in_mrgctx, p, &p);
1931 encode_value (entry->info_type, p, &p);
1932 encode_value (entry->data->type, p, &p);
1933 encode_patch (acfg, entry->data, p, &p);
1936 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1937 case MONO_PATCH_INFO_MONITOR_ENTER:
1938 case MONO_PATCH_INFO_MONITOR_EXIT:
1941 g_warning ("unable to handle jump info %d", patch_info->type);
1942 g_assert_not_reached ();
1949 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
1952 guint32 last_offset, j, pindex;
1953 MonoJumpInfo *patch_info;
1955 encode_value (n_patches, p, &p);
1958 encode_value (first_got_offset, p, &p);
1960 /* First encode the type+position table */
1963 for (pindex = 0; pindex < patches->len; ++pindex) {
1965 patch_info = g_ptr_array_index (patches, pindex);
1967 if (patch_info->type == MONO_PATCH_INFO_NONE)
1972 //printf ("T: %d O: %d.\n", patch_info->type, patch_info->ip.i);
1973 offset = patch_info->ip.i - last_offset;
1974 last_offset = patch_info->ip.i;
1976 /* Only the type is needed */
1977 *p = patch_info->type;
1981 /* Then encode the other info */
1982 for (pindex = 0; pindex < patches->len; ++pindex) {
1983 patch_info = g_ptr_array_index (patches, pindex);
1985 if (is_shared_got_patch (patch_info)) {
1986 guint32 offset = get_got_offset (acfg, patch_info);
1987 encode_value (offset, p, &p);
1989 encode_patch (acfg, patch_info, p, &p);
1997 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2001 int pindex, buf_size, n_patches;
2005 MonoJumpInfo *patch_info;
2006 MonoMethodHeader *header;
2007 guint32 method_index;
2009 guint32 first_got_offset;
2011 method = cfg->orig_method;
2012 code = cfg->native_code;
2013 header = mono_method_get_header (method);
2015 method_index = get_method_index (acfg, method);
2017 /* Make the labels local */
2018 sprintf (symbol, ".Lm_%x_p", method_index);
2020 /* Sort relocations */
2021 patches = g_ptr_array_new ();
2022 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2023 g_ptr_array_add (patches, patch_info);
2024 g_ptr_array_sort (patches, compare_patches);
2026 first_got_offset = acfg->cfgs [method_index]->got_offset;
2028 /**********************/
2029 /* Encode method info */
2030 /**********************/
2032 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2033 p = buf = g_malloc (buf_size);
2035 if (mono_class_get_cctor (method->klass))
2036 encode_klass_ref (acfg, method->klass, p, &p);
2038 /* Not needed when loading the method */
2039 encode_value (0, p, &p);
2042 if (cfg->opt & MONO_OPT_SHARED) {
2043 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2044 for (l = cfg->ldstr_list; l; l = l->next) {
2045 encode_value ((long)l->data, p, &p);
2049 /* Used only in shared mode */
2050 g_assert (!cfg->ldstr_list);
2053 for (pindex = 0; pindex < patches->len; ++pindex) {
2054 patch_info = g_ptr_array_index (patches, pindex);
2056 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2057 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2058 patch_info->type = MONO_PATCH_INFO_NONE;
2063 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2064 /* Stored in a GOT slot initialized at module load time */
2065 patch_info->type = MONO_PATCH_INFO_NONE;
2069 if (is_plt_patch (patch_info)) {
2070 /* Calls are made through the PLT */
2071 patch_info->type = MONO_PATCH_INFO_NONE;
2079 g_assert (cfg->has_got_slots);
2081 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2083 acfg->stats.info_size += p - buf;
2085 /* Emit method info */
2087 emit_label (acfg, symbol);
2089 g_assert (p - buf < buf_size);
2090 emit_bytes (acfg, buf, p - buf);
2095 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2098 int k, buf_size, method_index;
2099 guint32 debug_info_size;
2102 MonoMethodHeader *header;
2103 guint8 *p, *buf, *debug_info;
2104 MonoJitInfo *jinfo = cfg->jit_info;
2106 gboolean use_unwind_ops = FALSE;
2108 method = cfg->orig_method;
2109 code = cfg->native_code;
2110 header = mono_method_get_header (method);
2112 method_index = get_method_index (acfg, method);
2114 /* Make the labels local */
2115 sprintf (symbol, ".Le_%x_p", method_index);
2117 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2119 buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2120 p = buf = g_malloc (buf_size);
2122 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2123 use_unwind_ops = cfg->unwind_ops != NULL;
2126 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2128 encode_value (jinfo->code_size, p, &p);
2129 encode_value (flags, p, &p);
2131 if (use_unwind_ops) {
2132 guint32 encoded_len;
2136 * This is a duplicate of the data in the .debug_frame section, but that
2137 * section cannot be accessed using the dl interface.
2139 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2140 encode_value (encoded_len, p, &p);
2141 memcpy (p, encoded, encoded_len);
2145 encode_value (jinfo->used_regs, p, &p);
2148 /* Exception table */
2149 if (header->num_clauses) {
2150 for (k = 0; k < header->num_clauses; ++k) {
2151 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2153 encode_value (ei->exvar_offset, p, &p);
2155 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2156 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2158 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2159 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2160 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2164 if (jinfo->has_generic_jit_info) {
2165 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2167 encode_value (gi->has_this ? 1 : 0, p, &p);
2168 encode_value (gi->this_reg, p, &p);
2169 encode_value (gi->this_offset, p, &p);
2172 * Need to encode jinfo->method too, since it is not equal to 'method'
2173 * when using generic sharing.
2175 encode_method_ref (acfg, jinfo->method, p, &p);
2178 g_assert (debug_info_size < buf_size);
2180 encode_value (debug_info_size, p, &p);
2181 if (debug_info_size) {
2182 memcpy (p, debug_info, debug_info_size);
2183 p += debug_info_size;
2184 g_free (debug_info);
2187 acfg->stats.ex_info_size += p - buf;
2191 emit_label (acfg, symbol);
2193 g_assert (p - buf < buf_size);
2194 emit_bytes (acfg, buf, p - buf);
2199 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2201 MonoClass *klass = mono_class_get (acfg->image, token);
2205 gboolean no_special_static, cant_encode;
2206 gpointer iter = NULL;
2208 buf_size = 10240 + (klass->vtable_size * 16);
2209 p = buf = g_malloc (buf_size);
2213 mono_class_init (klass);
2215 mono_class_get_nested_types (klass, &iter);
2216 g_assert (klass->nested_classes_inited);
2218 mono_class_setup_vtable (klass);
2221 * Emit all the information which is required for creating vtables so
2222 * the runtime does not need to create the MonoMethod structures which
2223 * take up a lot of space.
2226 no_special_static = !mono_class_has_special_static_fields (klass);
2228 /* Check whenever we have enough info to encode the vtable */
2229 cant_encode = FALSE;
2230 for (i = 0; i < klass->vtable_size; ++i) {
2231 MonoMethod *cm = klass->vtable [i];
2233 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2237 if (klass->generic_container || cant_encode) {
2238 encode_value (-1, p, &p);
2240 encode_value (klass->vtable_size, p, &p);
2241 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);
2242 if (klass->has_cctor)
2243 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2244 if (klass->has_finalize)
2245 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2247 encode_value (klass->instance_size, p, &p);
2248 encode_value (mono_class_data_size (klass), p, &p);
2249 encode_value (klass->packing_size, p, &p);
2250 encode_value (klass->min_align, p, &p);
2252 for (i = 0; i < klass->vtable_size; ++i) {
2253 MonoMethod *cm = klass->vtable [i];
2256 encode_method_ref (acfg, cm, p, &p);
2258 encode_value (0, p, &p);
2262 acfg->stats.class_info_size += p - buf;
2265 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2266 emit_label (acfg, symbol);
2268 g_assert (p - buf < buf_size);
2269 emit_bytes (acfg, buf, p - buf);
2274 * Calls made from AOTed code are routed through a table of jumps similar to the
2275 * ELF PLT (Program Linkage Table). The differences are the following:
2276 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2277 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2278 * jumps. This means the jumps need to be patched when the address of the callee is
2279 * known. Initially the PLT entries jump to code which transfers control to the
2280 * AOT runtime through the first PLT entry.
2283 emit_plt (MonoAotCompile *acfg)
2289 sprintf (symbol, "plt");
2291 emit_section_change (acfg, ".text", 0);
2292 emit_global (acfg, symbol, TRUE);
2294 /* This section will be made read-write by the AOT loader */
2295 emit_alignment (acfg, PAGESIZE);
2297 emit_alignment (acfg, 16);
2299 emit_label (acfg, symbol);
2301 for (i = 0; i < acfg->plt_offset; ++i) {
2304 sprintf (label, ".Lp_%d", i);
2305 emit_label (acfg, label);
2308 * The first plt entry is used to transfer code to the AOT loader.
2310 arch_emit_plt_entry (acfg, i);
2313 sprintf (symbol, "plt_end");
2314 emit_global (acfg, symbol, TRUE);
2315 emit_label (acfg, symbol);
2318 static G_GNUC_UNUSED void
2319 emit_named_code (MonoAotCompile *acfg, const char *name, guint8 *code,
2320 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2324 MonoJumpInfo *patch_info;
2330 sprintf (symbol, "%s", name);
2332 emit_section_change (acfg, ".text", 0);
2333 emit_global (acfg, symbol, TRUE);
2334 emit_alignment (acfg, 16);
2335 emit_label (acfg, symbol);
2337 sprintf (symbol, ".Lnamed_%s", name);
2338 emit_label (acfg, symbol);
2341 * The code should access everything through the GOT, so we pass
2344 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2348 /* Sort relocations */
2349 patches = g_ptr_array_new ();
2350 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2351 g_ptr_array_add (patches, patch_info);
2352 g_ptr_array_sort (patches, compare_patches);
2354 buf_size = patches->len * 128 + 128;
2355 buf = g_malloc (buf_size);
2358 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2359 g_assert (p - buf < buf_size);
2361 sprintf (symbol, "%s_p", name);
2363 emit_section_change (acfg, ".text", 0);
2364 emit_global (acfg, symbol, FALSE);
2365 emit_label (acfg, symbol);
2367 emit_bytes (acfg, buf, p - buf);
2369 /* Emit debug info */
2373 sprintf (symbol, "%s", name);
2374 sprintf (symbol2, ".Lnamed_%s", name);
2376 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2381 * When running in aot-only mode, we can't create trampolines at runtime, so we create
2382 * a few, and save them in the AOT file. Normal trampolines embed their argument as a
2383 * literal inside the trampoline code, we can't do that here, so instead we embed an offset
2384 * which needs to be added to the trampoline address to get the address of the GOT slot
2385 * which contains the argument value.
2386 * The generated trampolines jump to the generic trampolines using another GOT slot, which
2387 * will be setup by the AOT loader to point to the generic trampoline code of the given
2391 emit_trampolines (MonoAotCompile *acfg)
2395 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2403 if (!acfg->aot_opts.full_aot)
2406 g_assert (acfg->image->assembly);
2408 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2409 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2410 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2412 * Emit the generic trampolines.
2414 * We could save some code by treating the generic trampolines as a wrapper
2415 * method, but that approach has its own complexities, so we choose the simpler
2418 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2419 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2421 /* Emit trampoline code */
2423 sprintf (symbol, "generic_trampoline_%d", tramp_type);
2425 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2428 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2429 emit_named_code (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2430 #if defined(__x86_64__) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2431 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2432 emit_named_code (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2433 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2434 emit_named_code (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2437 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2438 emit_named_code (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2440 /* Emit the exception related code pieces */
2441 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2442 emit_named_code (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2443 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2444 emit_named_code (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2445 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2446 emit_named_code (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2447 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2448 emit_named_code (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2449 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2450 emit_named_code (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2451 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2452 emit_named_code (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2454 #if defined(__x86_64__)
2455 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2456 emit_named_code (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2459 #if defined(__x86_64__) || defined(__arm__)
2460 for (i = 0; i < 128; ++i) {
2463 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2464 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2465 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2466 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2468 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2469 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2470 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2471 emit_named_code (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2477 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2481 /* Reserve some entries at the end of the GOT for our use */
2482 acfg->num_trampoline_got_entries = acfg->num_aot_trampolines * 2;
2484 sprintf (symbol, "trampolines");
2486 emit_section_change (acfg, ".text", 0);
2487 emit_global (acfg, symbol, TRUE);
2488 emit_alignment (acfg, 16);
2489 emit_label (acfg, symbol);
2491 for (i = 0; i < acfg->num_aot_trampolines; ++i) {
2494 offset = acfg->got_offset + (i * 2);
2496 arch_emit_specific_trampoline (acfg, offset, &tramp_size);
2497 if (!acfg->specific_trampoline_size) {
2498 g_assert (tramp_size);
2499 acfg->specific_trampoline_size = tramp_size;
2504 /* Unbox trampolines */
2506 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2508 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2510 char call_target [256];
2512 method = mono_get_method (acfg->image, token, NULL);
2514 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2515 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2518 sprintf (symbol, "unbox_trampoline_%d", i);
2520 emit_section_change (acfg, ".text", 0);
2521 emit_global (acfg, symbol, TRUE);
2522 emit_label (acfg, symbol);
2524 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2526 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2529 acfg->trampoline_got_offset_base = acfg->got_offset;
2531 acfg->got_offset += acfg->num_trampoline_got_entries;
2535 str_begins_with (const char *str1, const char *str2)
2537 int len = strlen (str2);
2538 return strncmp (str1, str2, len) == 0;
2542 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2544 gchar **args, **ptr;
2546 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2547 for (ptr = args; ptr && *ptr; ptr ++) {
2548 const char *arg = *ptr;
2550 if (str_begins_with (arg, "outfile=")) {
2551 opts->outfile = g_strdup (arg + strlen ("outfile="));
2552 } else if (str_begins_with (arg, "save-temps")) {
2553 opts->save_temps = TRUE;
2554 } else if (str_begins_with (arg, "keep-temps")) {
2555 opts->save_temps = TRUE;
2556 } else if (str_begins_with (arg, "write-symbols")) {
2557 opts->write_symbols = TRUE;
2558 } else if (str_begins_with (arg, "metadata-only")) {
2559 opts->metadata_only = TRUE;
2560 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2561 opts->bind_to_runtime_version = TRUE;
2562 } else if (str_begins_with (arg, "full")) {
2563 opts->full_aot = TRUE;
2565 * The no-dlsym option is only useful on the iphone, and even there,
2566 * do to other limitations of the dynamic linker, it doesn't seem to
2567 * work. So disable it for now so we don't have to support it.
2570 } else if (str_begins_with (arg, "no-dlsym")) {
2571 opts->no_dlsym = TRUE;
2573 } else if (str_begins_with (arg, "threads=")) {
2574 opts->nthreads = atoi (arg + strlen ("threads="));
2575 } else if (str_begins_with (arg, "static")) {
2576 opts->static_link = TRUE;
2577 opts->no_dlsym = TRUE;
2578 } else if (str_begins_with (arg, "asmonly")) {
2579 opts->asm_only = TRUE;
2580 } else if (str_begins_with (arg, "asmwriter")) {
2581 opts->asm_writer = TRUE;
2583 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2592 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2594 MonoMethod *method = (MonoMethod*)key;
2595 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2596 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2597 MonoAotCompile *acfg = user_data;
2599 new_ji->image = ji->image;
2600 new_ji->token = ji->token;
2601 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2605 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2607 if (klass->type_token)
2609 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2612 return can_encode_class (acfg, klass->element_class);
2617 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2619 switch (patch_info->type) {
2620 case MONO_PATCH_INFO_METHOD:
2621 case MONO_PATCH_INFO_METHODCONST: {
2622 MonoMethod *method = patch_info->data.method;
2624 if (method->wrapper_type) {
2625 switch (method->wrapper_type) {
2626 case MONO_WRAPPER_NONE:
2627 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2628 case MONO_WRAPPER_XDOMAIN_INVOKE:
2629 case MONO_WRAPPER_STFLD:
2630 case MONO_WRAPPER_LDFLD:
2631 case MONO_WRAPPER_LDFLDA:
2632 case MONO_WRAPPER_LDFLD_REMOTE:
2633 case MONO_WRAPPER_STFLD_REMOTE:
2634 case MONO_WRAPPER_STELEMREF:
2635 case MONO_WRAPPER_ISINST:
2636 case MONO_WRAPPER_PROXY_ISINST:
2637 case MONO_WRAPPER_ALLOC:
2638 case MONO_WRAPPER_REMOTING_INVOKE:
2639 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
2640 case MONO_WRAPPER_UNKNOWN:
2643 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2647 if (!method->token) {
2648 /* The method is part of a constructed type like Int[,].Set (). */
2649 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2650 if (method->klass->rank)
2658 case MONO_PATCH_INFO_VTABLE:
2659 case MONO_PATCH_INFO_CLASS_INIT:
2660 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2661 case MONO_PATCH_INFO_CLASS:
2662 case MONO_PATCH_INFO_IID:
2663 case MONO_PATCH_INFO_ADJUSTED_IID:
2664 if (!can_encode_class (acfg, patch_info->data.klass)) {
2665 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
2669 case MONO_PATCH_INFO_RGCTX_FETCH: {
2670 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2672 if (!can_encode_patch (acfg, entry->data))
2684 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
2689 * AOT compile a given method.
2690 * This function might be called by multiple threads, so it must be thread-safe.
2693 compile_method (MonoAotCompile *acfg, MonoMethod *method)
2696 MonoJumpInfo *patch_info;
2699 MonoMethod *wrapped;
2701 if (acfg->aot_opts.metadata_only)
2704 mono_acfg_lock (acfg);
2705 index = get_method_index (acfg, method);
2706 mono_acfg_unlock (acfg);
2708 /* fixme: maybe we can also precompile wrapper methods */
2709 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2710 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2711 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
2712 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
2716 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
2719 wrapped = mono_marshal_method_from_wrapper (method);
2720 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
2721 // FIXME: The wrapper should be generic too, but it is not
2724 InterlockedIncrement (&acfg->stats.mcount);
2727 if (method->is_generic || method->klass->generic_container) {
2728 InterlockedIncrement (&acfg->stats.genericcount);
2733 //acfg->aot_opts.print_skipped_methods = TRUE;
2735 if (acfg->aot_opts.full_aot)
2736 mono_use_imt = FALSE;
2739 * Since these methods are the only ones which are compiled with
2740 * AOT support, and they are not used by runtime startup/shutdown code,
2741 * the runtime will not see AOT methods during AOT compilation,so it
2742 * does not need to support them by creating a fake GOT etc.
2744 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
2745 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
2746 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
2747 InterlockedIncrement (&acfg->stats.genericcount);
2750 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
2751 /* Let the exception happen at runtime */
2755 if (cfg->disable_aot) {
2756 if (acfg->aot_opts.print_skipped_methods)
2757 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
2758 InterlockedIncrement (&acfg->stats.ocount);
2759 mono_destroy_compile (cfg);
2763 /* Nullify patches which need no aot processing */
2764 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2765 switch (patch_info->type) {
2766 case MONO_PATCH_INFO_LABEL:
2767 case MONO_PATCH_INFO_BB:
2768 patch_info->type = MONO_PATCH_INFO_NONE;
2775 /* Collect method->token associations from the cfg */
2776 mono_acfg_lock (acfg);
2777 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
2778 mono_acfg_unlock (acfg);
2781 * Check for absolute addresses.
2784 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2785 switch (patch_info->type) {
2786 case MONO_PATCH_INFO_ABS:
2787 /* unable to handle this */
2796 if (acfg->aot_opts.print_skipped_methods)
2797 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
2798 InterlockedIncrement (&acfg->stats.abscount);
2799 mono_destroy_compile (cfg);
2803 /* Lock for the rest of the code */
2804 mono_acfg_lock (acfg);
2807 * Check for methods/klasses we can't encode.
2810 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2811 if (!can_encode_patch (acfg, patch_info))
2816 if (acfg->aot_opts.print_skipped_methods)
2817 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
2818 acfg->stats.ocount++;
2819 mono_destroy_compile (cfg);
2820 mono_acfg_unlock (acfg);
2824 /* Adds generic instances referenced by this method */
2825 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2826 switch (patch_info->type) {
2827 case MONO_PATCH_INFO_METHOD: {
2828 MonoMethod *m = patch_info->data.method;
2829 if (m->is_inflated) {
2830 if (!(mono_class_generic_sharing_enabled (m->klass) &&
2831 mono_method_is_generic_sharable_impl (m, FALSE)) &&
2832 !method_has_type_vars (m)) {
2833 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
2834 if (acfg->aot_opts.full_aot)
2835 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
2837 add_extra_method (acfg, m);
2840 add_generic_class (acfg, m->klass);
2849 /* Determine whenever the method has GOT slots */
2850 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2851 switch (patch_info->type) {
2852 case MONO_PATCH_INFO_GOT_OFFSET:
2853 case MONO_PATCH_INFO_NONE:
2855 case MONO_PATCH_INFO_IMAGE:
2856 /* The assembly is stored in GOT slot 0 */
2857 if (patch_info->data.image != acfg->image)
2858 cfg->has_got_slots = TRUE;
2861 if (!is_plt_patch (patch_info))
2862 cfg->has_got_slots = TRUE;
2867 if (!cfg->has_got_slots)
2868 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
2870 /* Make a copy of the patch info which is in the mempool */
2872 MonoJumpInfo *patches = NULL, *patches_end = NULL;
2874 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2875 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2878 patches = new_patch_info;
2880 patches_end->next = new_patch_info;
2881 patches_end = new_patch_info;
2883 cfg->patch_info = patches;
2885 /* Make a copy of the unwind info */
2887 GSList *l, *unwind_ops;
2891 for (l = cfg->unwind_ops; l; l = l->next) {
2892 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
2893 memcpy (op, l->data, sizeof (MonoUnwindOp));
2894 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
2896 cfg->unwind_ops = g_slist_reverse (unwind_ops);
2898 /* Make a copy of the argument/local info */
2900 MonoInst **args, **locals;
2901 MonoMethodSignature *sig;
2902 MonoMethodHeader *header;
2905 sig = mono_method_signature (method);
2906 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
2907 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2908 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
2909 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
2913 header = mono_method_get_header (method);
2914 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
2915 for (i = 0; i < header->num_locals; ++i) {
2916 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
2917 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
2919 cfg->locals = locals;
2922 /* Free some fields used by cfg to conserve memory */
2923 mono_mempool_destroy (cfg->mempool);
2924 cfg->mempool = NULL;
2925 g_free (cfg->varinfo);
2926 cfg->varinfo = NULL;
2930 mono_regstate_free (cfg->rs);
2934 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
2936 while (index >= acfg->cfgs_size) {
2937 MonoCompile **new_cfgs;
2940 new_size = acfg->cfgs_size * 2;
2941 new_cfgs = g_new0 (MonoCompile*, new_size);
2942 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
2943 g_free (acfg->cfgs);
2944 acfg->cfgs = new_cfgs;
2945 acfg->cfgs_size = new_size;
2947 acfg->cfgs [index] = cfg;
2949 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
2951 if (cfg->orig_method->wrapper_type)
2952 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
2954 mono_acfg_unlock (acfg);
2956 InterlockedIncrement (&acfg->stats.ccount);
2960 compile_thread_main (gpointer *user_data)
2962 MonoDomain *domain = user_data [0];
2963 MonoAotCompile *acfg = user_data [1];
2964 GPtrArray *methods = user_data [2];
2967 mono_thread_attach (domain);
2969 for (i = 0; i < methods->len; ++i)
2970 compile_method (acfg, g_ptr_array_index (methods, i));
2974 load_profile_files (MonoAotCompile *acfg)
2978 int file_index, res, method_index, i;
2985 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);
2987 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
2992 infile = fopen (tmp, "r");
2995 printf ("Using profile data file '%s'\n", tmp);
3000 res = fscanf (infile, "%32s\n", ver);
3001 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3002 printf ("Profile file has wrong version or invalid.\n");
3008 res = fscanf (infile, "%d\n", &token);
3012 method_index = mono_metadata_token_index (token) - 1;
3014 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3015 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3020 /* Add missing methods */
3022 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3023 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3024 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3026 unordered = g_list_reverse (unordered);
3027 if (acfg->method_order)
3028 g_list_last (acfg->method_order)->next = unordered;
3030 acfg->method_order = unordered;
3036 * Collect all patches which have shared GOT entries and alloc entries for them. The
3037 * rest will get entries allocated during emit_code ().
3040 alloc_got_slots (MonoAotCompile *acfg)
3046 /* Slot 0 is reserved for the address of the current assembly */
3047 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3048 ji->type = MONO_PATCH_INFO_IMAGE;
3049 ji->data.image = acfg->image;
3051 get_shared_got_offset (acfg, ji);
3053 for (l = acfg->method_order; l != NULL; l = l->next) {
3054 i = GPOINTER_TO_UINT (l->data);
3056 if (acfg->cfgs [i]) {
3057 MonoCompile *cfg = acfg->cfgs [i];
3059 for (ji = cfg->patch_info; ji; ji = ji->next) {
3060 if (is_shared_got_patch (ji))
3061 get_shared_got_offset (acfg, ji);
3068 emit_code (MonoAotCompile *acfg)
3074 sprintf (symbol, "methods");
3075 emit_section_change (acfg, ".text", 0);
3076 emit_global (acfg, symbol, TRUE);
3077 emit_alignment (acfg, 8);
3078 emit_label (acfg, symbol);
3081 * Emit some padding so the local symbol for the first method doesn't have the
3082 * same address as 'methods'.
3084 emit_zero_bytes (acfg, 16);
3086 for (l = acfg->method_order; l != NULL; l = l->next) {
3087 i = GPOINTER_TO_UINT (l->data);
3090 emit_method_code (acfg, acfg->cfgs [i]);
3093 sprintf (symbol, "methods_end");
3094 emit_section_change (acfg, ".text", 0);
3095 emit_global (acfg, symbol, FALSE);
3096 emit_alignment (acfg, 8);
3097 emit_label (acfg, symbol);
3099 sprintf (symbol, "method_offsets");
3100 emit_section_change (acfg, ".text", 1);
3101 emit_global (acfg, symbol, FALSE);
3102 emit_alignment (acfg, 8);
3103 emit_label (acfg, symbol);
3105 for (i = 0; i < acfg->nmethods; ++i) {
3106 if (acfg->cfgs [i]) {
3107 sprintf (symbol, ".Lm_%x", i);
3108 emit_symbol_diff (acfg, symbol, "methods", 0);
3110 emit_int32 (acfg, 0xffffffff);
3117 emit_info (MonoAotCompile *acfg)
3123 /* Emit method info */
3124 sprintf (symbol, "method_info");
3125 emit_section_change (acfg, ".text", 1);
3126 emit_global (acfg, symbol, FALSE);
3127 emit_alignment (acfg, 8);
3128 emit_label (acfg, symbol);
3130 /* To reduce size of generated assembly code */
3131 sprintf (symbol, "mi");
3132 emit_label (acfg, symbol);
3134 for (l = acfg->method_order; l != NULL; l = l->next) {
3135 i = GPOINTER_TO_UINT (l->data);
3138 emit_method_info (acfg, acfg->cfgs [i]);
3141 sprintf (symbol, "method_info_offsets");
3142 emit_section_change (acfg, ".text", 1);
3143 emit_global (acfg, symbol, FALSE);
3144 emit_alignment (acfg, 8);
3145 emit_label (acfg, symbol);
3147 for (i = 0; i < acfg->nmethods; ++i) {
3148 if (acfg->cfgs [i]) {
3149 sprintf (symbol, ".Lm_%x_p", i);
3150 emit_symbol_diff (acfg, symbol, "mi", 0);
3152 emit_int32 (acfg, 0);
3159 * mono_aot_method_hash:
3161 * Return a hash code for methods which only depends on metadata.
3164 mono_aot_method_hash (MonoMethod *method)
3168 if (method->wrapper_type) {
3169 hash = g_str_hash (method->name);
3171 char *full_name = mono_method_full_name (method, TRUE);
3172 // FIXME: Improve this (changing this requires bumping MONO_AOT_FILE_VERSION)
3173 hash = g_str_hash (full_name);
3180 typedef struct HashEntry {
3181 guint32 key, value, index;
3182 struct HashEntry *next;
3186 * emit_extra_methods:
3188 * Emit methods which are not in the METHOD table, like wrappers.
3191 emit_extra_methods (MonoAotCompile *acfg)
3193 int i, table_size, buf_size;
3196 guint32 *info_offsets;
3199 HashEntry *entry, *new_entry;
3200 int nmethods, max_chain_length;
3203 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3205 buf_size = acfg->extra_methods->len * 256 + 256;
3206 p = buf = g_malloc (buf_size);
3208 /* Encode method info */
3210 /* So offsets are > 0 */
3213 for (i = 0; i < acfg->extra_methods->len; ++i) {
3214 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3215 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3221 info_offsets [i] = p - buf;
3223 if (method->wrapper_type) {
3226 // FIXME: Optimize disk usage
3227 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
3228 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3229 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
3231 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
3232 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3233 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
3235 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
3236 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3237 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
3239 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
3240 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3241 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
3244 name = mono_method_full_name (cfg->orig_method, TRUE);
3247 encode_value (1, p, &p);
3248 strcpy ((char*)p, name);
3249 p += strlen (name ) + 1;
3252 encode_value (0, p, &p);
3253 encode_method_ref (acfg, method, p, &p);
3256 g_assert ((p - buf) < buf_size);
3259 g_assert ((p - buf) < buf_size);
3261 /* Emit method info */
3262 sprintf (symbol, "extra_method_info");
3263 emit_section_change (acfg, ".text", 1);
3264 emit_global (acfg, symbol, FALSE);
3265 emit_alignment (acfg, 8);
3266 emit_label (acfg, symbol);
3268 emit_bytes (acfg, buf, p - buf);
3273 * Construct a chained hash table for mapping indexes in extra_method_info to
3276 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3277 table = g_ptr_array_sized_new (table_size);
3278 for (i = 0; i < table_size; ++i)
3279 g_ptr_array_add (table, NULL);
3280 chain_lengths = g_new0 (int, table_size);
3281 max_chain_length = 0;
3282 for (i = 0; i < acfg->extra_methods->len; ++i) {
3283 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3284 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3290 key = info_offsets [i];
3291 value = get_method_index (acfg, method);
3293 hash = mono_aot_method_hash (method) % table_size;
3295 chain_lengths [hash] ++;
3296 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3298 /* FIXME: Allocate from the mempool */
3299 new_entry = g_new0 (HashEntry, 1);
3300 new_entry->key = key;
3301 new_entry->value = value;
3303 entry = g_ptr_array_index (table, hash);
3304 if (entry == NULL) {
3305 new_entry->index = hash;
3306 g_ptr_array_index (table, hash) = new_entry;
3309 entry = entry->next;
3311 entry->next = new_entry;
3312 new_entry->index = table->len;
3313 g_ptr_array_add (table, new_entry);
3317 //printf ("MAX: %d\n", max_chain_length);
3319 /* Emit the table */
3320 sprintf (symbol, "extra_method_table");
3321 emit_section_change (acfg, ".text", 0);
3322 emit_global (acfg, symbol, FALSE);
3323 emit_alignment (acfg, 8);
3324 emit_label (acfg, symbol);
3326 g_assert (table_size < 65000);
3327 emit_int32 (acfg, table_size);
3328 g_assert (table->len < 65000);
3329 for (i = 0; i < table->len; ++i) {
3330 HashEntry *entry = g_ptr_array_index (table, i);
3332 if (entry == NULL) {
3333 emit_int32 (acfg, 0);
3334 emit_int32 (acfg, 0);
3335 emit_int32 (acfg, 0);
3337 g_assert (entry->key > 0);
3338 emit_int32 (acfg, entry->key);
3339 emit_int32 (acfg, entry->value);
3341 emit_int32 (acfg, entry->next->index);
3343 emit_int32 (acfg, 0);
3348 * Emit a table reverse mapping method indexes to their index in extra_method_info.
3349 * This is used by mono_aot_find_jit_info ().
3351 sprintf (symbol, "extra_method_info_offsets");
3352 emit_section_change (acfg, ".text", 0);
3353 emit_global (acfg, symbol, FALSE);
3354 emit_alignment (acfg, 8);
3355 emit_label (acfg, symbol);
3357 emit_int32 (acfg, acfg->extra_methods->len);
3358 for (i = 0; i < acfg->extra_methods->len; ++i) {
3359 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3361 emit_int32 (acfg, get_method_index (acfg, method));
3362 emit_int32 (acfg, info_offsets [i]);
3367 emit_method_order (MonoAotCompile *acfg)
3373 sprintf (symbol, "method_order");
3374 emit_section_change (acfg, ".text", 1);
3375 emit_global (acfg, symbol, FALSE);
3376 emit_alignment (acfg, 8);
3377 emit_label (acfg, symbol);
3379 /* First emit an index table */
3382 for (l = acfg->method_order; l != NULL; l = l->next) {
3383 i = GPOINTER_TO_UINT (l->data);
3385 if (acfg->cfgs [i]) {
3386 if ((index % 1024) == 0) {
3387 emit_int32 (acfg, i);
3395 emit_int32 (acfg, 0xffffff);
3397 /* Then emit the whole method order */
3398 for (l = acfg->method_order; l != NULL; l = l->next) {
3399 i = GPOINTER_TO_UINT (l->data);
3401 if (acfg->cfgs [i]) {
3402 emit_int32 (acfg, i);
3407 sprintf (symbol, "method_order_end");
3408 emit_section_change (acfg, ".text", 1);
3409 emit_global (acfg, symbol, FALSE);
3410 emit_label (acfg, symbol);
3414 emit_exception_info (MonoAotCompile *acfg)
3419 sprintf (symbol, "ex_info");
3420 emit_section_change (acfg, ".text", 1);
3421 emit_global (acfg, symbol, FALSE);
3422 emit_alignment (acfg, 8);
3423 emit_label (acfg, symbol);
3425 /* To reduce size of generated assembly */
3426 sprintf (symbol, "ex");
3427 emit_label (acfg, symbol);
3429 for (i = 0; i < acfg->nmethods; ++i) {
3431 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3434 sprintf (symbol, "ex_info_offsets");
3435 emit_section_change (acfg, ".text", 1);
3436 emit_global (acfg, symbol, FALSE);
3437 emit_alignment (acfg, 8);
3438 emit_label (acfg, symbol);
3440 for (i = 0; i < acfg->nmethods; ++i) {
3441 if (acfg->cfgs [i]) {
3442 sprintf (symbol, ".Le_%x_p", i);
3443 emit_symbol_diff (acfg, symbol, "ex", 0);
3445 emit_int32 (acfg, 0);
3452 emit_class_info (MonoAotCompile *acfg)
3457 sprintf (symbol, "class_info");
3458 emit_section_change (acfg, ".text", 1);
3459 emit_global (acfg, symbol, FALSE);
3460 emit_alignment (acfg, 8);
3461 emit_label (acfg, symbol);
3463 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3464 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3466 sprintf (symbol, "class_info_offsets");
3467 emit_section_change (acfg, ".text", 1);
3468 emit_global (acfg, symbol, FALSE);
3469 emit_alignment (acfg, 8);
3470 emit_label (acfg, symbol);
3472 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3473 sprintf (symbol, ".LK_I_%x", i);
3474 emit_symbol_diff (acfg, symbol, "class_info", 0);
3479 typedef struct ClassNameTableEntry {
3480 guint32 token, index;
3481 struct ClassNameTableEntry *next;
3482 } ClassNameTableEntry;
3485 emit_class_name_table (MonoAotCompile *acfg)
3488 guint32 token, hash;
3493 ClassNameTableEntry *entry, *new_entry;
3496 * Construct a chained hash table for mapping class names to typedef tokens.
3498 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
3499 table = g_ptr_array_sized_new (table_size);
3500 for (i = 0; i < table_size; ++i)
3501 g_ptr_array_add (table, NULL);
3502 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3503 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3504 klass = mono_class_get (acfg->image, token);
3505 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
3506 hash = g_str_hash (full_name) % table_size;
3509 /* FIXME: Allocate from the mempool */
3510 new_entry = g_new0 (ClassNameTableEntry, 1);
3511 new_entry->token = token;
3513 entry = g_ptr_array_index (table, hash);
3514 if (entry == NULL) {
3515 new_entry->index = hash;
3516 g_ptr_array_index (table, hash) = new_entry;
3519 entry = entry->next;
3521 entry->next = new_entry;
3522 new_entry->index = table->len;
3523 g_ptr_array_add (table, new_entry);
3527 /* Emit the table */
3528 sprintf (symbol, "class_name_table");
3529 emit_section_change (acfg, ".text", 0);
3530 emit_global (acfg, symbol, FALSE);
3531 emit_alignment (acfg, 8);
3532 emit_label (acfg, symbol);
3534 /* FIXME: Optimize memory usage */
3535 g_assert (table_size < 65000);
3536 emit_int16 (acfg, table_size);
3537 g_assert (table->len < 65000);
3538 for (i = 0; i < table->len; ++i) {
3539 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
3541 if (entry == NULL) {
3542 emit_int16 (acfg, 0);
3543 emit_int16 (acfg, 0);
3545 emit_int16 (acfg, mono_metadata_token_index (entry->token));
3547 emit_int16 (acfg, entry->next->index);
3549 emit_int16 (acfg, 0);
3555 emit_image_table (MonoAotCompile *acfg)
3561 * The image table is small but referenced in a lot of places.
3562 * So we emit it at once, and reference its elements by an index.
3565 sprintf (symbol, "mono_image_table");
3566 emit_section_change (acfg, ".text", 1);
3567 emit_global (acfg, symbol, FALSE);
3568 emit_alignment (acfg, 8);
3569 emit_label (acfg, symbol);
3571 emit_int32 (acfg, acfg->image_table->len);
3572 for (i = 0; i < acfg->image_table->len; i++) {
3573 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
3574 MonoAssemblyName *aname = &image->assembly->aname;
3576 /* FIXME: Support multi-module assemblies */
3577 g_assert (image->assembly->image == image);
3579 emit_string (acfg, image->assembly_name);
3580 emit_string (acfg, image->guid);
3581 emit_string (acfg, aname->culture ? aname->culture : "");
3582 emit_string (acfg, (const char*)aname->public_key_token);
3584 emit_alignment (acfg, 8);
3585 emit_int32 (acfg, aname->flags);
3586 emit_int32 (acfg, aname->major);
3587 emit_int32 (acfg, aname->minor);
3588 emit_int32 (acfg, aname->build);
3589 emit_int32 (acfg, aname->revision);
3594 emit_got_info (MonoAotCompile *acfg)
3597 int i, first_plt_got_patch, buf_size;
3599 guint32 *got_info_offsets;
3601 /* Add the patches needed by the PLT to the GOT */
3602 acfg->plt_got_offset_base = acfg->got_offset;
3603 first_plt_got_patch = acfg->shared_patches->len;
3604 for (i = 1; i < acfg->plt_offset; ++i) {
3605 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3607 g_ptr_array_add (acfg->shared_patches, patch_info);
3610 acfg->got_offset += acfg->plt_offset;
3614 * - optimize offsets table.
3615 * - reduce number of exported symbols.
3616 * - emit info for a klass only once.
3617 * - determine when a method uses a GOT slot which is guaranteed to be already
3619 * - clean up and document the code.
3620 * - use String.Empty in class libs.
3623 /* Encode info required to decode shared GOT entries */
3624 buf_size = acfg->shared_patches->len * 64;
3625 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
3626 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
3627 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
3628 for (i = 0; i < acfg->shared_patches->len; ++i) {
3629 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
3631 got_info_offsets [i] = p - buf;
3632 /* No need to encode the patch type for non-PLT patches */
3633 if (i >= first_plt_got_patch) {
3634 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
3635 encode_value (ji->type, p, &p);
3637 encode_patch (acfg, ji, p, &p);
3640 g_assert (p - buf <= buf_size);
3642 acfg->stats.got_info_size = p - buf;
3644 /* Emit got_info table */
3645 sprintf (symbol, "got_info");
3646 emit_section_change (acfg, ".text", 1);
3647 emit_global (acfg, symbol, FALSE);
3648 emit_alignment (acfg, 8);
3649 emit_label (acfg, symbol);
3651 emit_bytes (acfg, buf, p - buf);
3653 /* Emit got_info_offsets table */
3654 sprintf (symbol, "got_info_offsets");
3655 emit_section_change (acfg, ".text", 1);
3656 emit_global (acfg, symbol, FALSE);
3657 emit_alignment (acfg, 8);
3658 emit_label (acfg, symbol);
3660 for (i = 0; i < acfg->shared_patches->len; ++i)
3661 emit_int32 (acfg, got_info_offsets [i]);
3663 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
3667 emit_got (MonoAotCompile *acfg)
3671 /* Don't make GOT global so accesses to it don't need relocations */
3672 sprintf (symbol, "got");
3673 emit_section_change (acfg, ".bss", 0);
3674 emit_alignment (acfg, 8);
3675 emit_label (acfg, symbol);
3676 if (acfg->got_offset > 0)
3677 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3681 emit_globals (MonoAotCompile *acfg)
3686 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
3688 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
3690 opts_str = g_strdup_printf ("%d", acfg->opts);
3691 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
3694 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
3696 if (acfg->aot_opts.bind_to_runtime_version) {
3697 build_info = mono_get_runtime_build_info ();
3698 emit_string_symbol (acfg, "mono_runtime_version", build_info);
3699 g_free (build_info);
3701 emit_string_symbol (acfg, "mono_runtime_version", "");
3705 * Some platforms like the iphone have no working dlsym (). To work around this,
3706 * we create an ELF ctor function which will be invoked by dlopen, and which
3707 * will call a function in the AOT loader to register the symbols used by the
3709 * When static linking, we emit a global which will point to the symbol table.
3711 if (acfg->aot_opts.no_dlsym) {
3715 if (acfg->aot_opts.static_link)
3716 /* Emit a string holding the assembly name */
3717 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
3719 /* Emit the names */
3720 for (i = 0; i < acfg->globals->len; ++i) {
3721 char *name = g_ptr_array_index (acfg->globals, i);
3723 sprintf (symbol, "name_%d", i);
3724 emit_section_change (acfg, ".text", 1);
3725 emit_label (acfg, symbol);
3726 emit_string (acfg, name);
3729 /* Emit the globals table */
3730 sprintf (symbol, "globals");
3731 emit_section_change (acfg, ".data", 0);
3732 /* This is not a global, since it is accessed by the init function */
3733 emit_alignment (acfg, 8);
3734 emit_label (acfg, symbol);
3736 for (i = 0; i < acfg->globals->len; ++i) {
3737 char *name = g_ptr_array_index (acfg->globals, i);
3739 sprintf (symbol, "name_%d", i);
3740 emit_pointer (acfg, symbol);
3742 sprintf (symbol, "%s", name);
3743 emit_pointer (acfg, symbol);
3745 /* Null terminate the table */
3746 emit_pointer (acfg, NULL);
3747 emit_pointer (acfg, NULL);
3750 if (acfg->aot_opts.static_link) {
3754 * Emit a global symbol which can be passed by an embedding app to
3755 * mono_aot_register_module ().
3757 #if defined(__MACH__)
3758 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
3760 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
3763 /* Get rid of characters which cannot occur in symbols */
3765 for (p = symbol; *p; ++p) {
3766 if (!(isalnum (*p) || *p == '_'))
3769 acfg->static_linking_symbol = g_strdup (symbol);
3770 emit_global_inner (acfg, symbol, FALSE);
3771 emit_alignment (acfg, 8);
3772 emit_label (acfg, symbol);
3773 emit_pointer (acfg, "globals");
3775 sprintf (symbol, "init_%s", acfg->image->assembly->aname.name);
3776 emit_section_change (acfg, ".text", 1);
3777 emit_alignment (acfg, 8);
3778 emit_label (acfg, symbol);
3779 if (acfg->use_bin_writer)
3780 g_assert_not_reached ();
3782 fprintf (acfg->fp, "leaq globals(%%rip), %%rdi\n");
3783 fprintf (acfg->fp, "call mono_aot_register_globals@PLT\n");
3784 fprintf (acfg->fp, "ret\n");
3785 fprintf (acfg->fp, ".section .ctors,\"aw\",@progbits\n");
3786 emit_alignment (acfg, 8);
3787 emit_pointer (acfg, symbol);
3788 #elif defined(__arm__) && defined(__MACH__)
3790 fprintf (acfg->fp, ".text\n");
3791 fprintf (acfg->fp, ".align 3\n");
3793 fprintf (acfg->fp, "ldr r0, .L5\n");
3794 fprintf (acfg->fp, ".LPIC0:\n");
3795 fprintf (acfg->fp, "add r0, pc, r0\n");
3796 fprintf (acfg->fp, "ldr r0, [r0]\n");
3797 fprintf (acfg->fp, "b _mono_aot_register_globals@PLT\n");
3798 fprintf (acfg->fp, ".align 2\n");
3800 fprintf (acfg->fp, ".L5:\n");
3801 fprintf (acfg->fp, ".long globals_ptr-(.LPIC0+8)\n");
3803 fprintf (acfg->fp, ".data\n");
3804 fprintf (acfg->fp, ".align 2\n");
3805 fprintf (acfg->fp, "globals_ptr:\n");
3806 fprintf (acfg->fp, ".long globals\n");
3808 fprintf (acfg->fp, ".mod_init_func\n");
3809 fprintf (acfg->fp, ".align 2\n");
3810 fprintf (acfg->fp, ".long %s@target1\n", symbol);
3812 #elif defined(__arm__)
3814 * Taken from gcc generated code for:
3816 * void foo () { bar (&i); }
3817 * gcc --shared -fPIC -O2
3819 fprintf (acfg->fp, "ldr r3, .L5\n");
3820 fprintf (acfg->fp, "ldr r0, .L5+4\n");
3821 fprintf (acfg->fp, ".LPIC0:\n");
3822 fprintf (acfg->fp, "add r3, pc, r3\n");
3823 fprintf (acfg->fp, "add r0, r3, r0\n");
3824 fprintf (acfg->fp, "b mono_aot_register_globals(PLT)\n");
3826 fprintf (acfg->fp, ".L5:\n");
3827 fprintf (acfg->fp, ".word _GLOBAL_OFFSET_TABLE_-(.LPIC0+8)\n");
3828 fprintf (acfg->fp, ".word globals(GOTOFF)\n");
3830 fprintf (acfg->fp, ".section .init_array,\"aw\",%%init_array\n");
3831 fprintf (acfg->fp, ".align 2\n");
3832 fprintf (acfg->fp, ".word %s(target1)\n", symbol);
3834 g_assert_not_reached ();
3842 * Emit a structure containing all the information not stored elsewhere.
3845 emit_file_info (MonoAotCompile *acfg)
3849 sprintf (symbol, "mono_aot_file_info");
3850 emit_section_change (acfg, ".data", 0);
3851 emit_alignment (acfg, 8);
3852 emit_label (acfg, symbol);
3853 emit_global (acfg, symbol, FALSE);
3855 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
3856 emit_int32 (acfg, acfg->plt_got_offset_base);
3857 emit_int32 (acfg, acfg->trampoline_got_offset_base);
3858 emit_int32 (acfg, acfg->num_aot_trampolines);
3859 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
3860 emit_int32 (acfg, acfg->plt_offset);
3861 emit_int32 (acfg, acfg->specific_trampoline_size);
3862 emit_pointer (acfg, "got");
3865 /*****************************************/
3866 /* Emitting DWARF debug information */
3867 /*****************************************/
3870 emit_dwarf_info (MonoAotCompile *acfg)
3872 #ifdef EMIT_DWARF_INFO
3874 char symbol [128], symbol2 [128];
3876 /* DIEs for methods */
3877 for (i = 0; i < acfg->nmethods; ++i) {
3878 MonoCompile *cfg = acfg->cfgs [i];
3883 sprintf (symbol, ".Lm_%x", i);
3884 sprintf (symbol2, ".Lme_%x", i);
3886 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
3892 compile_asm (MonoAotCompile *acfg)
3894 char *command, *objfile;
3895 char *outfile_name, *tmp_outfile_name;
3897 #if defined(__x86_64__)
3898 #define AS_OPTIONS "--64"
3899 #elif defined(sparc) && SIZEOF_VOID_P == 8
3900 #define AS_OPTIONS "-xarch=v9"
3902 #define AS_OPTIONS ""
3905 if (acfg->aot_opts.asm_only) {
3906 printf ("Output file: '%s'.\n", acfg->tmpfname);
3907 if (acfg->aot_opts.static_link)
3908 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
3912 if (acfg->aot_opts.static_link) {
3913 if (acfg->aot_opts.outfile)
3914 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
3916 objfile = g_strdup_printf ("%s.o", acfg->image->name);
3918 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
3920 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
3921 printf ("Executing the native assembler: %s\n", command);
3922 if (system (command) != 0) {
3930 if (acfg->aot_opts.static_link) {
3931 printf ("Output file: '%s'.\n", objfile);
3932 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
3937 if (acfg->aot_opts.outfile)
3938 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
3940 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
3942 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
3945 command = g_strdup_printf ("ld -shared -G -o %s %s.o", outfile_name, acfg->tmpfname);
3946 #elif defined(__ppc__) && defined(__MACH__)
3947 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", outfile_name, acfg->tmpfname);
3948 #elif defined(PLATFORM_WIN32)
3949 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", outfile_name, acfg->tmpfname);
3951 if (acfg->aot_opts.no_dlsym) {
3953 * Need to link using gcc so our ctor function gets called.
3955 command = g_strdup_printf ("gcc -shared -o %s %s.o", outfile_name, acfg->tmpfname);
3957 command = g_strdup_printf ("ld -shared -o %s %s.o", outfile_name, acfg->tmpfname);
3960 printf ("Executing the native linker: %s\n", command);
3961 if (system (command) != 0) {
3962 g_free (tmp_outfile_name);
3963 g_free (outfile_name);
3971 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
3972 printf ("Stripping the binary: %s\n", com);
3976 rename (tmp_outfile_name, outfile_name);
3978 g_free (tmp_outfile_name);
3979 g_free (outfile_name);
3982 if (acfg->aot_opts.save_temps)
3983 printf ("Retained input file.\n");
3985 unlink (acfg->tmpfname);
3991 acfg_free (MonoAotCompile *acfg)
3995 img_writer_destroy (acfg->w);
3996 for (i = 0; i < acfg->nmethods; ++i)
3998 g_free (acfg->cfgs [i]);
3999 g_free (acfg->cfgs);
4000 g_free (acfg->static_linking_symbol);
4001 g_ptr_array_free (acfg->methods, TRUE);
4002 g_ptr_array_free (acfg->shared_patches, TRUE);
4003 g_ptr_array_free (acfg->image_table, TRUE);
4004 g_ptr_array_free (acfg->globals, TRUE);
4005 g_hash_table_destroy (acfg->method_indexes);
4006 g_hash_table_destroy (acfg->plt_offset_to_patch);
4007 g_hash_table_destroy (acfg->patch_to_plt_offset);
4008 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4009 g_hash_table_destroy (acfg->method_to_cfg);
4010 g_hash_table_destroy (acfg->token_info_hash);
4011 g_hash_table_destroy (acfg->image_hash);
4012 mono_mempool_destroy (acfg->mempool);
4017 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4019 MonoImage *image = ass->image;
4021 int i, res, methods_len;
4022 MonoAotCompile *acfg;
4023 char *outfile_name, *tmp_outfile_name;
4027 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4029 acfg = g_new0 (MonoAotCompile, 1);
4030 acfg->methods = g_ptr_array_new ();
4031 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4032 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4033 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4034 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4035 acfg->shared_patches = g_ptr_array_new ();
4036 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4037 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4038 acfg->image_hash = g_hash_table_new (NULL, NULL);
4039 acfg->image_table = g_ptr_array_new ();
4040 acfg->globals = g_ptr_array_new ();
4041 acfg->image = image;
4043 acfg->mempool = mono_mempool_new ();
4044 acfg->extra_methods = g_ptr_array_new ();
4045 InitializeCriticalSection (&acfg->mutex);
4047 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4048 acfg->aot_opts.write_symbols = TRUE;
4050 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4052 //acfg->aot_opts.print_skipped_methods = TRUE;
4055 if (acfg->aot_opts.full_aot)
4056 /* arch_emit_unbox_trampoline () etc only works with the asm writer */
4057 acfg->aot_opts.asm_writer = TRUE;
4060 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4061 if (acfg->aot_opts.full_aot) {
4062 printf ("--aot=full is not supported on this platform.\n");
4067 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4068 if (acfg->aot_opts.outfile)
4069 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4071 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4073 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4075 acfg->fp = fopen (tmp_outfile_name, "w");
4076 g_assert (acfg->fp);
4078 acfg->w = img_writer_create (acfg->fp, TRUE);
4079 acfg->use_bin_writer = TRUE;
4081 if (acfg->aot_opts.asm_only) {
4082 if (acfg->aot_opts.outfile)
4083 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4085 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4086 acfg->fp = fopen (acfg->tmpfname, "w+");
4088 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4089 acfg->fp = fdopen (i, "w+");
4091 g_assert (acfg->fp);
4093 acfg->w = img_writer_create (acfg->fp, FALSE);
4095 /* hush compiler warnings about these being possibly uninitialized */
4096 tmp_outfile_name = NULL;
4097 outfile_name = NULL;
4100 load_profile_files (acfg);
4102 img_writer_emit_start (acfg->w);
4104 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4106 acfg->num_aot_trampolines = acfg->aot_opts.full_aot ? 10240 : 0;
4108 acfg->method_index = 1;
4110 /* Collect methods */
4111 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4113 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4115 method = mono_get_method (acfg->image, token, NULL);
4118 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4122 /* Load all methods eagerly to skip the slower lazy loading code */
4123 mono_class_setup_methods (method->klass);
4125 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4126 /* Compile the wrapper instead */
4127 /* We do this here instead of add_wrappers () because it is easy to do it here */
4128 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4132 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4133 add_method_with_index (acfg, method, i);
4134 acfg->method_index ++;
4137 add_generic_instances (acfg);
4139 if (acfg->aot_opts.full_aot)
4140 add_wrappers (acfg);
4142 acfg->cfgs_size = acfg->methods->len + 32;
4143 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4145 /* PLT offset 0 is reserved for the PLT trampoline */
4146 acfg->plt_offset = 1;
4148 /* Compile methods */
4151 if (acfg->aot_opts.nthreads > 0) {
4156 gpointer *user_data;
4157 MonoMethod **methods;
4159 methods_len = acfg->methods->len;
4161 len = acfg->methods->len / acfg->aot_opts.nthreads;
4164 * Partition the list of methods into fragments, and hand it to threads to
4167 threads = g_ptr_array_new ();
4168 /* Make a copy since acfg->methods is modified by compile_method () */
4169 methods = g_new0 (MonoMethod*, methods_len);
4170 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4171 for (i = 0; i < methods_len; ++i)
4172 methods [i] = g_ptr_array_index (acfg->methods, i);
4174 while (i < methods_len) {
4175 frag = g_ptr_array_new ();
4176 for (j = 0; j < len; ++j) {
4177 if (i < methods_len) {
4178 g_ptr_array_add (frag, methods [i]);
4183 user_data = g_new0 (gpointer, 3);
4184 user_data [0] = mono_domain_get ();
4185 user_data [1] = acfg;
4186 user_data [2] = frag;
4188 handle = CreateThread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4189 g_ptr_array_add (threads, handle);
4193 for (i = 0; i < threads->len; ++i) {
4194 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4200 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4201 for (i = methods_len; i < acfg->methods->len; ++i) {
4202 /* This can new methods to acfg->methods */
4203 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4208 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4212 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4214 alloc_got_slots (acfg);
4220 emit_extra_methods (acfg);
4222 emit_method_order (acfg);
4224 emit_trampolines (acfg);
4226 emit_class_name_table (acfg);
4228 emit_got_info (acfg);
4230 emit_exception_info (acfg);
4232 emit_class_info (acfg);
4236 emit_image_table (acfg);
4240 emit_file_info (acfg);
4242 emit_globals (acfg);
4244 emit_dwarf_info (acfg);
4246 sprintf (symbol, "mem_end");
4247 emit_section_change (acfg, ".text", 1);
4248 emit_global (acfg, symbol, FALSE);
4249 emit_alignment (acfg, 8);
4250 emit_label (acfg, symbol);
4254 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4256 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)));
4259 res = img_writer_emit_writeout (acfg->w);
4264 if (acfg->use_bin_writer) {
4265 rename (tmp_outfile_name, outfile_name);
4267 res = compile_asm (acfg);
4274 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4276 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);
4277 if (acfg->stats.genericcount)
4278 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4279 if (acfg->stats.abscount)
4280 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4281 if (acfg->stats.lmfcount)
4282 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4283 if (acfg->stats.ocount)
4284 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4285 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);
4286 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4287 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);
4289 printf ("GOT slot distribution:\n");
4290 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4291 if (acfg->stats.got_slot_types [i])
4292 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4300 * Support for emitting debug info for JITted code.
4302 * This works as follows:
4303 * - the runtime writes out an xdb.s file containing DWARF debug info.
4304 * - the user calls a gdb macro
4305 * - the macro compiles and loads this shared library using add-symbol-file.
4307 * This is based on the xdebug functionality in the Kaffe Java VM.
4309 * We emit assembly code instead of using the ELF writer, so we can emit debug info
4310 * incrementally as each method is JITted, and the debugger doesn't have to call
4311 * into the runtime to emit the shared library, which would cause all kinds of
4312 * complications, like threading issues, and the fact that the ELF writer's
4313 * emit_writeout () function cannot be called more than once.
4316 /* The recommended gdb macro is: */
4319 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4320 add-symbol-file xdb.so 0
4324 static MonoDwarfWriter *xdebug_writer;
4325 static CRITICAL_SECTION xdebug_mutex;
4326 static FILE *xdebug_fp;
4328 #define mono_xdebug_lock(acfg) EnterCriticalSection (&xdebug_mutex)
4329 #define mono_xdebug_unlock(acfg) LeaveCriticalSection (&xdebug_mutex)
4332 mono_xdebug_init (void)
4337 InitializeCriticalSection (&xdebug_mutex);
4340 xdebug_fp = fopen ("xdb.s", "w");
4342 w = img_writer_create (xdebug_fp, FALSE);
4344 img_writer_emit_start (w);
4346 /* This file will contain the IL code for methods which don't have debug info */
4347 il_file = fopen ("xdb.il", "w");
4349 xdebug_writer = mono_dwarf_writer_create (w, il_file);
4351 /* Emit something so the file has a text segment */
4352 img_writer_emit_section_change (w, ".text", 0);
4353 img_writer_emit_string (w, "");
4355 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4359 * mono_save_xdebug_info:
4361 * Emit debugging info for METHOD into an assembly file which can be assembled
4362 * and loaded into gdb to provide debugging info for JITted code.
4365 mono_save_xdebug_info (MonoCompile *cfg)
4370 mono_xdebug_lock ();
4371 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 ()));
4373 mono_xdebug_unlock ();
4377 * mono_save_trampoline_xdebug_info:
4379 * Same as mono_save_xdebug_info, but for trampolines.
4382 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4387 mono_xdebug_lock ();
4388 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4390 mono_xdebug_unlock ();
4398 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4404 mono_xdebug_init (void)
4409 mono_save_xdebug_info (MonoCompile *cfg)
4414 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)