2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - optimize the trampolines, generate more code in the arch files.
13 * - make things more consistent with how elf works, for example, use ELF
15 * Remaining generics sharing work:
16 * - optimize the size of the data which is encoded.
17 * - optimize the runtime loading of data:
18 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
19 * which loads the debugging+exception handling info for the method. This is a
20 * huge waste of time and code, since the rgctx structure is currently empty.
21 * - every shared method has a MonoGenericJitInfo structure which is only really
22 * used for handling catch clauses with open types, not a very common use case.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
74 #define RODATA_SECT ".text"
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__MACH__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
88 #define SHARED_EXT ".so"
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
95 typedef struct MonoAotOptions {
98 gboolean write_symbols;
99 gboolean metadata_only;
100 gboolean bind_to_runtime_version;
103 gboolean static_link;
110 int nrgctx_trampolines;
111 int nimt_trampolines;
112 gboolean print_skipped_methods;
118 typedef struct MonoAotStats {
119 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
120 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
121 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
122 int got_slots, offsets_size;
123 int got_slot_types [MONO_PATCH_INFO_NONE];
124 int jit_time, gen_time, link_time;
127 typedef struct MonoAotCompile {
130 GHashTable *method_indexes;
131 GHashTable *method_depth;
134 GHashTable *patch_to_plt_entry;
135 GHashTable *plt_offset_to_entry;
136 GHashTable *patch_to_got_offset;
137 GHashTable **patch_to_got_offset_by_type;
138 GPtrArray *got_patches;
139 GHashTable *image_hash;
140 GHashTable *method_to_cfg;
141 GHashTable *token_info_hash;
142 GPtrArray *extra_methods;
143 GPtrArray *image_table;
146 guint32 *plt_got_info_offsets;
147 guint32 got_offset, plt_offset, plt_got_offset_base;
148 guint32 final_got_size;
149 /* Number of GOT entries reserved for trampolines */
150 guint32 num_trampoline_got_entries;
152 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
153 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
154 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
156 MonoAotOptions aot_opts;
159 MonoMemPool *mempool;
162 char *static_linking_symbol;
163 CRITICAL_SECTION mutex;
164 gboolean use_bin_writer;
166 MonoDwarfWriter *dwarf;
170 GHashTable *unwind_info_offsets;
171 GPtrArray *unwind_ops;
172 guint32 unwind_info_offset;
173 char *got_symbol_base;
176 GHashTable *method_label_hash;
177 const char *temp_prefix;
178 const char *llvm_label_prefix;
179 guint32 label_generator;
181 MonoAotFileFlags flags;
182 MonoDynamicStream blob;
183 MonoClass **typespec_classes;
192 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
193 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
195 /* This points to the current acfg in LLVM mode */
196 static MonoAotCompile *llvm_acfg;
198 #ifdef HAVE_ARRAY_ELEM_INIT
199 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
200 #define MSGSTRFIELD1(line) str##line
201 static const struct msgstr_t {
202 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
203 #include "patch-info.h"
206 #define PATCH_INFO(a,b) b,
207 #include "patch-info.h"
210 static const gint16 opidx [] = {
211 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
212 #include "patch-info.h"
216 static G_GNUC_UNUSED const char*
217 get_patch_name (int info)
219 return (const char*)&opstr + opidx [info];
223 #define PATCH_INFO(a,b) b,
224 static const char* const
225 patch_types [MONO_PATCH_INFO_NUM + 1] = {
226 #include "patch-info.h"
230 static G_GNUC_UNUSED const char*
231 get_patch_name (int info)
233 return patch_types [info];
238 /* Wrappers around the image writer functions */
241 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
243 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
247 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
249 img_writer_emit_push_section (acfg->w, section_name, subsection);
253 emit_pop_section (MonoAotCompile *acfg)
255 img_writer_emit_pop_section (acfg->w);
259 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
261 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
265 emit_label (MonoAotCompile *acfg, const char *name)
267 img_writer_emit_label (acfg->w, name);
271 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
273 img_writer_emit_bytes (acfg->w, buf, size);
277 emit_string (MonoAotCompile *acfg, const char *value)
279 img_writer_emit_string (acfg->w, value);
283 emit_line (MonoAotCompile *acfg)
285 img_writer_emit_line (acfg->w);
289 emit_alignment (MonoAotCompile *acfg, int size)
291 img_writer_emit_alignment (acfg->w, size);
295 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
297 img_writer_emit_pointer_unaligned (acfg->w, target);
301 emit_pointer (MonoAotCompile *acfg, const char *target)
303 img_writer_emit_pointer (acfg->w, target);
307 emit_int16 (MonoAotCompile *acfg, int value)
309 img_writer_emit_int16 (acfg->w, value);
313 emit_int32 (MonoAotCompile *acfg, int value)
315 img_writer_emit_int32 (acfg->w, value);
319 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
321 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
325 emit_zero_bytes (MonoAotCompile *acfg, int num)
327 img_writer_emit_zero_bytes (acfg->w, num);
331 emit_byte (MonoAotCompile *acfg, guint8 val)
333 img_writer_emit_byte (acfg->w, val);
336 #ifdef __native_client_codegen__
338 emit_nacl_call_alignment (MonoAotCompile *acfg)
340 img_writer_emit_nacl_call_alignment (acfg->w);
344 static G_GNUC_UNUSED void
345 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
347 img_writer_emit_global (acfg->w, name, func);
351 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
353 if (acfg->aot_opts.no_dlsym) {
354 g_ptr_array_add (acfg->globals, g_strdup (name));
355 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
357 img_writer_emit_global (acfg->w, name, func);
362 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
364 img_writer_emit_symbol_size (acfg->w, name, end_label);
368 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
370 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
371 emit_global (acfg, name, FALSE);
372 img_writer_emit_label (acfg->w, name);
373 img_writer_emit_string (acfg->w, value);
376 static G_GNUC_UNUSED void
377 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
380 guint8 b = value & 0x7f;
382 if (value != 0) /* more bytes to come */
388 static G_GNUC_UNUSED void
389 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
392 gboolean negative = (value < 0);
399 /* the following is unnecessary if the
400 * implementation of >>= uses an arithmetic rather
401 * than logical shift for a signed left operand
405 value |= - ((gint64)1 <<(size - 7));
406 /* sign bit of byte is second high order bit (0x40) */
407 if ((value == 0 && !(byte & 0x40)) ||
408 (value == -1 && (byte & 0x40)))
412 emit_byte (acfg, byte);
416 static G_GNUC_UNUSED void
417 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
422 guint8 b = value & 0x7f;
424 if (value != 0) /* more bytes to come */
432 static G_GNUC_UNUSED void
433 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
436 gboolean negative = (value < 0);
444 /* the following is unnecessary if the
445 * implementation of >>= uses an arithmetic rather
446 * than logical shift for a signed left operand
450 value |= - (1 <<(size - 7));
451 /* sign bit of byte is second high order bit (0x40) */
452 if ((value == 0 && !(byte & 0x40)) ||
453 (value == -1 && (byte & 0x40)))
463 /* ARCHITECTURE SPECIFIC CODE */
465 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
466 #define EMIT_DWARF_INFO 1
469 #if defined(TARGET_ARM)
470 #define AOT_FUNC_ALIGNMENT 4
472 #define AOT_FUNC_ALIGNMENT 16
474 #if defined(TARGET_X86) && defined(__native_client_codegen__)
475 #undef AOT_FUNC_ALIGNMENT
476 #define AOT_FUNC_ALIGNMENT 32
479 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
480 #define PPC_LD_OP "ld"
481 #define PPC_LDX_OP "ldx"
483 #define PPC_LD_OP "lwz"
484 #define PPC_LDX_OP "lwzx"
490 #define LLVM_LABEL_PREFIX "_"
492 #define LLVM_LABEL_PREFIX ""
497 #define LLC_TARGET_ARGS "-march=arm -mattr=+v6 -mtriple=arm-apple-darwin"
499 //#define LLC_TARGET_ARGS "-march=arm -mtriple=arm-linux-gnueabi -soft-float"
501 #define LLC_TARGET_ARGS ""
505 * arch_emit_direct_call:
507 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
511 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
513 #if defined(TARGET_X86) || defined(TARGET_AMD64)
514 /* Need to make sure this is exactly 5 bytes long */
515 emit_byte (acfg, '\xe8');
516 emit_symbol_diff (acfg, target, ".", -4);
518 #elif defined(TARGET_ARM)
519 if (acfg->use_bin_writer) {
526 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
527 emit_bytes (acfg, buf, 4);
529 img_writer_emit_unset_mode (acfg->w);
530 fprintf (acfg->fp, "bl %s\n", target);
533 #elif defined(TARGET_POWERPC)
534 if (acfg->use_bin_writer) {
535 g_assert_not_reached ();
537 img_writer_emit_unset_mode (acfg->w);
538 fprintf (acfg->fp, "bl %s\n", target);
542 g_assert_not_reached ();
548 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
550 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
551 * in in the 2. slot of every GOT, and require every method to place the GOT
552 * address in r30, even when it doesn't access the GOT otherwise. This way,
553 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
558 * PPC64 uses function descriptors which greatly complicate all code, since
559 * these are used very inconsistently in the runtime. Some functions like
560 * mono_compile_method () return ftn descriptors, while others like the
561 * trampoline creation functions do not.
562 * We assume that all GOT slots contain function descriptors, and create
563 * descriptors in aot-runtime.c when needed.
564 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
565 * from function descriptors, we could do the same, but it would require
566 * rewriting all the ppc/aot code to handle function descriptors properly.
567 * So instead, we use the same approach as on PPC32.
568 * This is a horrible mess, but fixing it would probably lead to an even bigger
574 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
577 #ifdef MONO_ARCH_AOT_SUPPORTED
579 * arch_emit_got_offset:
581 * The memory pointed to by CODE should hold native code for computing the GOT
582 * address. Emit this code while patching it with the offset between code and
583 * the GOT. CODE_SIZE is set to the number of bytes emitted.
586 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
588 #if defined(TARGET_POWERPC64)
589 g_assert (!acfg->use_bin_writer);
590 img_writer_emit_unset_mode (acfg->w);
592 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
593 * unsupported relocations. So we store the got address into the .Lgot_addr
594 * symbol which is in the text segment, compute its address, and load it.
596 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
597 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
598 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
599 fprintf (acfg->fp, "add 30, 30, 0\n");
600 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
601 acfg->label_generator ++;
603 #elif defined(TARGET_POWERPC)
604 g_assert (!acfg->use_bin_writer);
605 img_writer_emit_unset_mode (acfg->w);
606 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
607 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
608 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
609 acfg->label_generator ++;
612 guint32 offset = mono_arch_get_patch_offset (code);
613 emit_bytes (acfg, code, offset);
614 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
616 *code_size = offset + 4;
621 * arch_emit_got_access:
623 * The memory pointed to by CODE should hold native code for loading a GOT
624 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
625 * CODE_SIZE is set to the number of bytes emitted.
628 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
630 /* Emit beginning of instruction */
631 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
633 /* Emit the offset */
635 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
636 *code_size = mono_arch_get_patch_offset (code) + 4;
637 #elif defined(TARGET_X86)
638 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
639 *code_size = mono_arch_get_patch_offset (code) + 4;
640 #elif defined(TARGET_ARM)
641 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
642 *code_size = mono_arch_get_patch_offset (code) + 4;
643 #elif defined(TARGET_POWERPC)
649 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
650 g_assert (code - buf == 8);
651 emit_bytes (acfg, buf, code - buf);
652 *code_size = code - buf;
655 g_assert_not_reached ();
662 * arch_emit_plt_entry:
664 * Emit code for the PLT entry with index INDEX.
667 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
669 #if defined(TARGET_X86)
670 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
672 #ifdef __native_client_codegen__
673 const guint8 kSizeOfNaClJmp = 11;
674 guint8 bytes[kSizeOfNaClJmp];
675 guint8 *pbytes = &bytes[0];
677 x86_jump_membase32 (pbytes, X86_EBX, offset);
678 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
679 /* four bytes of data, used by mono_arch_patch_plt_entry */
680 /* For Native Client, make this work with data embedded in push. */
681 emit_byte (acfg, 0x68); /* hide data in a push */
682 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
683 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
685 /* jmp *<offset>(%ebx) */
686 emit_byte (acfg, 0xff);
687 emit_byte (acfg, 0xa3);
688 emit_int32 (acfg, offset);
689 /* Used by mono_aot_get_plt_info_offset */
690 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
691 #endif /* __native_client_codegen__ */
692 #elif defined(TARGET_AMD64)
694 * We can't emit jumps because they are 32 bits only so they can't be patched.
695 * So we make indirect calls through GOT entries which are patched by the AOT
696 * loader to point to .Lpd entries.
698 /* jmpq *<offset>(%rip) */
699 emit_byte (acfg, '\xff');
700 emit_byte (acfg, '\x25');
701 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
702 /* Used by mono_aot_get_plt_info_offset */
703 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
704 #elif defined(TARGET_ARM)
709 * - optimize OP_AOTCONST implementation
710 * - optimize the PLT entries
711 * - optimize SWITCH AOT implementation
714 if (acfg->use_bin_writer && FALSE) {
715 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
716 /* We only emit 1 relocation since we implement it ourselves anyway */
717 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
718 /* FIXME: A 2 instruction encoding is sufficient in most cases */
719 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
720 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
721 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
722 emit_bytes (acfg, buf, code - buf);
723 /* Used by mono_aot_get_plt_info_offset */
724 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
726 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
727 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
728 emit_bytes (acfg, buf, code - buf);
729 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
730 /* Used by mono_aot_get_plt_info_offset */
731 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
734 * The plt_got_info_offset is computed automatically by
735 * mono_aot_get_plt_info_offset (), so no need to save it here.
737 #elif defined(TARGET_POWERPC)
738 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
740 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
741 g_assert (!acfg->use_bin_writer);
742 img_writer_emit_unset_mode (acfg->w);
743 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
744 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
745 fprintf (acfg->fp, "add 11, 11, 30\n");
746 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
747 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
748 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
749 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
751 fprintf (acfg->fp, "mtctr 11\n");
752 fprintf (acfg->fp, "bctr\n");
753 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
755 g_assert_not_reached ();
760 * arch_emit_specific_trampoline:
762 * Emit code for a specific trampoline. OFFSET is the offset of the first of
763 * two GOT slots which contain the generic trampoline address and the trampoline
764 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
767 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
770 * The trampolines created here are variations of the specific
771 * trampolines created in mono_arch_create_specific_trampoline (). The
773 * - the generic trampoline address is taken from a got slot.
774 * - the offset of the got slot where the trampoline argument is stored
775 * is embedded in the instruction stream, and the generic trampoline
776 * can load the argument by loading the offset, adding it to the
777 * address of the trampoline to get the address of the got slot, and
778 * loading the argument from there.
779 * - all the trampolines should be of the same length.
781 #if defined(TARGET_AMD64)
782 /* This should be exactly 16 bytes long */
784 /* call *<offset>(%rip) */
785 emit_byte (acfg, '\x41');
786 emit_byte (acfg, '\xff');
787 emit_byte (acfg, '\x15');
788 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
789 /* This should be relative to the start of the trampoline */
790 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
791 emit_zero_bytes (acfg, 5);
792 #elif defined(TARGET_ARM)
796 /* This should be exactly 20 bytes long */
799 ARM_PUSH (code, 0x5fff);
800 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
801 /* Load the value from the GOT */
802 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
804 ARM_BLX_REG (code, ARMREG_R1);
806 g_assert (code - buf == 16);
809 emit_bytes (acfg, buf, code - buf);
811 * Only one offset is needed, since the second one would be equal to the
814 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
815 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
816 #elif defined(TARGET_POWERPC)
823 g_assert (!acfg->use_bin_writer);
826 * PPC has no ip relative addressing, so we need to compute the address
827 * of the mscorlib got. That is slow and complex, so instead, we store it
828 * in the second got slot of every aot image. The caller already computed
829 * the address of its got and placed it into r30.
831 img_writer_emit_unset_mode (acfg->w);
832 /* Load mscorlib got address */
833 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
834 /* Load generic trampoline address */
835 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
836 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
837 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
838 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
839 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
841 fprintf (acfg->fp, "mtctr 11\n");
842 /* Load trampoline argument */
843 /* On ppc, we pass it normally to the generic trampoline */
844 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
845 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
846 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
847 /* Branch to generic trampoline */
848 fprintf (acfg->fp, "bctr\n");
850 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
851 *tramp_size = 10 * 4;
855 #elif defined(TARGET_X86)
859 /* Similar to the PPC code above */
861 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
863 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
864 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
865 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
869 /* Load mscorlib got address */
870 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
871 /* Push trampoline argument */
872 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
873 /* Load generic trampoline address */
874 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
875 /* Branch to generic trampoline */
876 x86_jump_reg (code, X86_ECX);
878 #ifdef __native_client_codegen__
880 /* emit nops to next 32 byte alignment */
881 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
882 while (code < (buf + a)) x86_nop(code);
885 emit_bytes (acfg, buf, code - buf);
887 *tramp_size = NACL_SIZE(17, kNaClAlignment);
888 g_assert (code - buf == *tramp_size);
890 g_assert_not_reached ();
895 * arch_emit_unbox_trampoline:
897 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
898 * CALL_TARGET is the symbol pointing to the native code of METHOD.
901 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, const char *call_target)
903 #if defined(TARGET_AMD64)
908 this_reg = mono_arch_get_this_arg_reg (NULL);
910 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
912 emit_bytes (acfg, buf, code - buf);
914 emit_byte (acfg, '\xe9');
915 emit_symbol_diff (acfg, call_target, ".", -4);
916 #elif defined(TARGET_X86)
923 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
925 emit_bytes (acfg, buf, code - buf);
928 emit_byte (acfg, '\xe9');
929 emit_symbol_diff (acfg, call_target, ".", -4);
930 #elif defined(TARGET_ARM)
936 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
938 emit_bytes (acfg, buf, code - buf);
940 if (acfg->use_bin_writer) {
947 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
948 emit_bytes (acfg, buf, 4);
950 fprintf (acfg->fp, "\n\tb %s\n", call_target);
952 #elif defined(TARGET_POWERPC)
955 g_assert (!acfg->use_bin_writer);
957 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
958 fprintf (acfg->fp, "\n\tb %s\n", call_target);
960 g_assert_not_reached ();
965 * arch_emit_static_rgctx_trampoline:
967 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
968 * two GOT slots which contain the rgctx argument, and the method to jump to.
969 * TRAMP_SIZE is set to the size of the emitted trampoline.
970 * These kinds of trampolines cannot be enumerated statically, since there could
971 * be one trampoline per method instantiation, so we emit the same code for all
972 * trampolines, and parameterize them using two GOT slots.
975 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
977 #if defined(TARGET_AMD64)
978 /* This should be exactly 13 bytes long */
981 /* mov <OFFSET>(%rip), %r10 */
982 emit_byte (acfg, '\x4d');
983 emit_byte (acfg, '\x8b');
984 emit_byte (acfg, '\x15');
985 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
987 /* jmp *<offset>(%rip) */
988 emit_byte (acfg, '\xff');
989 emit_byte (acfg, '\x25');
990 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
991 #elif defined(TARGET_ARM)
995 /* This should be exactly 24 bytes long */
998 /* Load rgctx value */
999 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1000 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1001 /* Load branch addr + branch */
1002 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1003 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1005 g_assert (code - buf == 16);
1008 emit_bytes (acfg, buf, code - buf);
1009 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1010 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1011 #elif defined(TARGET_POWERPC)
1018 g_assert (!acfg->use_bin_writer);
1021 * PPC has no ip relative addressing, so we need to compute the address
1022 * of the mscorlib got. That is slow and complex, so instead, we store it
1023 * in the second got slot of every aot image. The caller already computed
1024 * the address of its got and placed it into r30.
1026 img_writer_emit_unset_mode (acfg->w);
1027 /* Load mscorlib got address */
1028 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1030 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1031 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1032 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1033 /* Load target address */
1034 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1035 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1036 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1037 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1038 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1039 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1041 fprintf (acfg->fp, "mtctr 11\n");
1042 /* Branch to the target address */
1043 fprintf (acfg->fp, "bctr\n");
1045 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1046 *tramp_size = 11 * 4;
1048 *tramp_size = 9 * 4;
1051 #elif defined(TARGET_X86)
1055 /* Similar to the PPC code above */
1057 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1060 /* Load mscorlib got address */
1061 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1063 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1064 /* Branch to the target address */
1065 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1067 #ifdef __native_client_codegen__
1069 /* emit nops to next 32 byte alignment */
1070 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1071 while (code < (buf + a)) x86_nop(code);
1075 emit_bytes (acfg, buf, code - buf);
1077 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1078 g_assert (code - buf == *tramp_size);
1080 g_assert_not_reached ();
1085 * arch_emit_imt_thunk:
1087 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1088 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1089 * key is the IMT key, and ptr holds the address of a memory location holding
1090 * the address to branch to if the IMT arg matches the key. The array is
1091 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1093 * TRAMP_SIZE is set to the size of the emitted trampoline.
1096 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1098 #if defined(TARGET_AMD64)
1102 code = buf = g_malloc (256);
1104 /* FIXME: Optimize this, i.e. use binary search etc. */
1105 /* Maybe move the body into a separate function (slower, but much smaller) */
1107 /* R11 is a free register */
1110 amd64_alu_membase_imm (code, X86_CMP, AMD64_R11, 0, 0);
1112 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1115 amd64_alu_membase_reg (code, X86_CMP, AMD64_R11, 0, MONO_ARCH_IMT_REG);
1117 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
1120 amd64_alu_reg_imm (code, X86_ADD, AMD64_R11, 2 * sizeof (gpointer));
1121 amd64_jump_code (code, labels [0]);
1124 mono_amd64_patch (labels [2], code);
1125 amd64_mov_reg_membase (code, AMD64_R11, AMD64_R11, sizeof (gpointer), 8);
1126 amd64_jump_membase (code, AMD64_R11, 0);
1130 mono_amd64_patch (labels [1], code);
1131 x86_breakpoint (code);
1133 amd64_mov_reg_membase (code, AMD64_R11, AMD64_RIP, 12345678, 8);
1135 /* mov <OFFSET>(%rip), %r11 */
1136 emit_byte (acfg, '\x4d');
1137 emit_byte (acfg, '\x8b');
1138 emit_byte (acfg, '\x1d');
1139 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1141 emit_bytes (acfg, buf, code - buf);
1143 *tramp_size = code - buf + 7;
1144 #elif defined(TARGET_X86)
1146 #ifdef __native_client_codegen__
1151 #ifdef __native_client_codegen__
1152 buf_alloc = g_malloc (256 + kNaClAlignment);
1153 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1155 code = buf = g_malloc (256);
1158 /* Allocate a temporary stack slot */
1159 x86_push_reg (code, X86_EAX);
1161 x86_push_reg (code, X86_EAX);
1163 /* Load mscorlib got address */
1164 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1166 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1169 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1171 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1174 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1176 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1179 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1180 x86_jump_code (code, labels [0]);
1183 mono_x86_patch (labels [2], code);
1184 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1185 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1186 /* Save the target address to the temporary stack location */
1187 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1189 x86_pop_reg (code, X86_EAX);
1190 /* Jump to the target address */
1195 mono_x86_patch (labels [1], code);
1196 x86_breakpoint (code);
1198 #ifdef __native_client_codegen__
1200 /* emit nops to next 32 byte alignment */
1201 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1202 while (code < (buf + a)) x86_nop(code);
1205 emit_bytes (acfg, buf, code - buf);
1207 *tramp_size = code - buf;
1208 #elif defined(TARGET_ARM)
1210 guint8 *code, *code2, *labels [16];
1214 /* The IMT method is in v5 */
1216 /* Need at least two free registers, plus a slot for storing the pc */
1217 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1219 /* Load the parameter from the GOT */
1220 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1221 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1224 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1225 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1227 ARM_B_COND (code, ARMCOND_EQ, 0);
1229 /* End-of-loop check */
1230 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1232 ARM_B_COND (code, ARMCOND_EQ, 0);
1235 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1238 arm_patch (labels [4], labels [1]);
1241 arm_patch (labels [2], code);
1242 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1243 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1244 /* Save it to the third stack slot */
1245 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1246 /* Restore the registers and branch */
1247 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1250 arm_patch (labels [3], code);
1255 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1257 emit_bytes (acfg, buf, code - buf);
1258 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1260 *tramp_size = code - buf + 4;
1261 #elif defined(TARGET_POWERPC)
1263 guint8 *code, *labels [16];
1267 /* Load the mscorlib got address */
1268 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1269 /* Load the parameter from the GOT */
1270 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1271 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1273 /* Load and check key */
1275 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1276 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1278 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1280 /* End-of-loop check */
1281 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1283 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1286 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1289 mono_ppc_patch (labels [4], labels [1]);
1292 mono_ppc_patch (labels [2], code);
1293 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1294 /* r11 now contains the value of the vtable slot */
1295 /* this is not a function descriptor on ppc64 */
1296 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1297 ppc_mtctr (code, ppc_r11);
1298 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1301 mono_ppc_patch (labels [3], code);
1305 *tramp_size = code - buf;
1307 emit_bytes (acfg, buf, code - buf);
1309 g_assert_not_reached ();
1314 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1316 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1317 /* Based on code generated by gcc */
1318 img_writer_emit_unset_mode (acfg->w);
1321 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1322 ".section .ctors,\"aw\",@progbits\n"
1326 ".section .opd,\"aw\"\n"
1329 ".long .%s,.TOC.@tocbase32\n"
1332 ".type .%s,@function\n"
1334 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1336 ".section .ctors,\"aw\",@progbits\n"
1340 ".section .opd,\"aw\"\n"
1343 ".long .%1$s,.TOC.@tocbase32\n"
1344 ".size %1$s,.-%1$s\n"
1346 ".type .%1$s,@function\n"
1348 ".%1$s:\n", symbol);
1359 "lis 3, .Lglobals@h\n"
1360 "ori 3, 3, .Lglobals@l\n"
1361 "bl .mono_aot_register_module\n"
1369 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1371 ".size .%s,.-.%s\n", symbol, symbol);
1374 ".size .%1$s,.-.%1$s\n", symbol);
1380 /* END OF ARCH SPECIFIC CODE */
1383 mono_get_field_token (MonoClassField *field)
1385 MonoClass *klass = field->parent;
1388 for (i = 0; i < klass->field.count; ++i) {
1389 if (field == &klass->fields [i])
1390 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1393 g_assert_not_reached ();
1398 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1402 //printf ("ENCODE: %d 0x%x.\n", value, value);
1405 * Same encoding as the one used in the metadata, extended to handle values
1406 * greater than 0x1fffffff.
1408 if ((value >= 0) && (value <= 127))
1410 else if ((value >= 0) && (value <= 16383)) {
1411 p [0] = 0x80 | (value >> 8);
1412 p [1] = value & 0xff;
1414 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1415 p [0] = (value >> 24) | 0xc0;
1416 p [1] = (value >> 16) & 0xff;
1417 p [2] = (value >> 8) & 0xff;
1418 p [3] = value & 0xff;
1423 p [1] = (value >> 24) & 0xff;
1424 p [2] = (value >> 16) & 0xff;
1425 p [3] = (value >> 8) & 0xff;
1426 p [4] = value & 0xff;
1434 stream_init (MonoDynamicStream *sh)
1437 sh->alloc_size = 4096;
1438 sh->data = g_malloc (4096);
1440 /* So offsets are > 0 */
1445 make_room_in_stream (MonoDynamicStream *stream, int size)
1447 if (size <= stream->alloc_size)
1450 while (stream->alloc_size <= size) {
1451 if (stream->alloc_size < 4096)
1452 stream->alloc_size = 4096;
1454 stream->alloc_size *= 2;
1457 stream->data = g_realloc (stream->data, stream->alloc_size);
1461 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1465 make_room_in_stream (stream, stream->index + len);
1466 memcpy (stream->data + stream->index, data, len);
1467 idx = stream->index;
1468 stream->index += len;
1475 * Add data to the binary blob inside the aot image. Returns the offset inside the
1476 * blob where the data was stored.
1479 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1481 if (acfg->blob.alloc_size == 0)
1482 stream_init (&acfg->blob);
1484 return add_stream_data (&acfg->blob, (char*)data, data_len);
1488 * emit_offset_table:
1490 * Emit a table of increasing offsets in a compact form using differential encoding.
1491 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1492 * group size, the more compact the table becomes, but the slower it becomes to compute
1493 * a given entry. Returns the size of the table.
1496 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1498 gint32 current_offset;
1499 int i, buf_size, ngroups, index_entry_size;
1501 guint32 *index_offsets;
1503 ngroups = (noffsets + (group_size - 1)) / group_size;
1505 index_offsets = g_new0 (guint32, ngroups);
1507 buf_size = noffsets * 4;
1508 p = buf = g_malloc0 (buf_size);
1511 for (i = 0; i < noffsets; ++i) {
1512 //printf ("D: %d -> %d\n", i, offsets [i]);
1513 if ((i % group_size) == 0) {
1514 index_offsets [i / group_size] = p - buf;
1515 /* Emit the full value for these entries */
1516 encode_value (offsets [i], p, &p);
1518 /* The offsets are allowed to be non-increasing */
1519 //g_assert (offsets [i] >= current_offset);
1520 encode_value (offsets [i] - current_offset, p, &p);
1522 current_offset = offsets [i];
1525 if (ngroups && index_offsets [ngroups - 1] < 65000)
1526 index_entry_size = 2;
1528 index_entry_size = 4;
1530 /* Emit the header */
1531 emit_int32 (acfg, noffsets);
1532 emit_int32 (acfg, group_size);
1533 emit_int32 (acfg, ngroups);
1534 emit_int32 (acfg, index_entry_size);
1536 /* Emit the index */
1537 for (i = 0; i < ngroups; ++i) {
1538 if (index_entry_size == 2)
1539 emit_int16 (acfg, index_offsets [i]);
1541 emit_int32 (acfg, index_offsets [i]);
1545 emit_bytes (acfg, buf, p - buf);
1547 return (int)(p - buf) + (ngroups * 4);
1551 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1555 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1559 index = g_hash_table_size (cfg->image_hash);
1560 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1561 g_ptr_array_add (cfg->image_table, image);
1567 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1570 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1572 /* FIXME: Search referenced images as well */
1573 if (!acfg->typespec_classes) {
1574 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1575 for (i = 0; i < len; ++i) {
1576 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1579 for (i = 0; i < len; ++i) {
1580 if (acfg->typespec_classes [i] == klass)
1585 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1591 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1596 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1597 * standard metadata encoding.
1600 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1604 if (klass->generic_class) {
1606 g_assert (klass->type_token);
1608 /* Find a typespec for a class if possible */
1609 token = find_typespec_for_class (acfg, klass);
1611 encode_value (token, p, &p);
1612 encode_value (get_image_index (acfg, acfg->image), p, &p);
1614 MonoClass *gclass = klass->generic_class->container_class;
1615 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1618 /* Encode it ourselves */
1620 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1621 encode_value (MONO_TYPE_GENERICINST, p, &p);
1622 encode_klass_ref (acfg, gclass, p, &p);
1623 encode_value (inst->type_argc, p, &p);
1624 for (i = 0; i < inst->type_argc; ++i)
1625 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1627 } else if (klass->type_token) {
1628 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1629 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1630 encode_value (get_image_index (acfg, klass->image), p, &p);
1631 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1632 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1633 g_assert (container);
1636 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1637 encode_value (klass->byval_arg.type, p, &p);
1639 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1641 encode_value (container->is_method, p, &p);
1642 if (container->is_method)
1643 encode_method_ref (acfg, container->owner.method, p, &p);
1645 encode_klass_ref (acfg, container->owner.klass, p, &p);
1648 g_assert (klass->rank > 0);
1649 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1650 encode_value (get_image_index (acfg, klass->image), p, &p);
1651 encode_value (klass->rank, p, &p);
1652 encode_klass_ref (acfg, klass->element_class, p, &p);
1658 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1660 guint32 token = mono_get_field_token (field);
1663 encode_klass_ref (cfg, field->parent, p, &p);
1664 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1665 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1670 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1674 MonoGenericInst *inst;
1676 /* Encode the context */
1677 inst = context->class_inst;
1678 encode_value (inst ? 1 : 0, p, &p);
1680 encode_value (inst->type_argc, p, &p);
1681 for (i = 0; i < inst->type_argc; ++i)
1682 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1684 inst = context->method_inst;
1685 encode_value (inst ? 1 : 0, p, &p);
1687 encode_value (inst->type_argc, p, &p);
1688 for (i = 0; i < inst->type_argc; ++i)
1689 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1695 #define MAX_IMAGE_INDEX 250
1698 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1700 guint32 image_index = get_image_index (acfg, method->klass->image);
1701 guint32 token = method->token;
1702 MonoJumpInfoToken *ji;
1707 * The encoding for most methods is as follows:
1708 * - image index encoded as a leb128
1709 * - token index encoded as a leb128
1710 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1711 * types of method encodings.
1714 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1716 /* Mark methods which can't use aot trampolines because they need the further
1717 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1719 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1720 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1721 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1724 * Some wrapper methods are shared using their signature, encode their
1725 * stringified signature instead.
1726 * FIXME: Optimize disk usage
1729 if (method->wrapper_type) {
1730 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1731 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1732 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1733 name = mono_aot_wrapper_name (method);
1734 } else if (mono_marshal_method_from_wrapper (method) != method) {
1735 /* Direct wrapper, encode it normally */
1737 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1740 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1741 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1742 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1744 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1745 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1746 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1748 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1749 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1750 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1756 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1757 strcpy ((char*)p, name);
1758 p += strlen (name) + 1;
1760 } else if (method->wrapper_type) {
1761 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1763 encode_value (method->wrapper_type, p, &p);
1765 switch (method->wrapper_type) {
1766 case MONO_WRAPPER_REMOTING_INVOKE:
1767 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1768 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1771 m = mono_marshal_method_from_wrapper (method);
1773 encode_method_ref (acfg, m, p, &p);
1776 case MONO_WRAPPER_PROXY_ISINST:
1777 case MONO_WRAPPER_LDFLD:
1778 case MONO_WRAPPER_LDFLDA:
1779 case MONO_WRAPPER_STFLD:
1780 case MONO_WRAPPER_ISINST: {
1781 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1782 encode_klass_ref (acfg, proxy_class, p, &p);
1785 case MONO_WRAPPER_LDFLD_REMOTE:
1786 case MONO_WRAPPER_STFLD_REMOTE:
1788 case MONO_WRAPPER_ALLOC: {
1789 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1791 /* The GC name is saved once in MonoAotFileInfo */
1792 g_assert (info->alloc_type != -1);
1793 encode_value (info->alloc_type, p, &p);
1796 case MONO_WRAPPER_WRITE_BARRIER:
1798 case MONO_WRAPPER_STELEMREF: {
1799 MonoClass *klass = mono_marshal_get_wrapper_info (method);
1801 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
1805 case MONO_WRAPPER_UNKNOWN:
1806 if (strcmp (method->name, "FastMonitorEnter") == 0)
1807 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1808 else if (strcmp (method->name, "FastMonitorExit") == 0)
1809 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1811 g_assert_not_reached ();
1813 case MONO_WRAPPER_SYNCHRONIZED:
1814 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1815 case MONO_WRAPPER_RUNTIME_INVOKE: {
1818 m = mono_marshal_method_from_wrapper (method);
1820 g_assert (m != method);
1821 encode_method_ref (acfg, m, p, &p);
1824 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1825 if (!strcmp (method->name, "ElementAddr")) {
1826 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1829 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1830 encode_value (info->rank, p, &p);
1831 encode_value (info->elem_size, p, &p);
1833 g_assert_not_reached ();
1837 g_assert_not_reached ();
1839 } else if (mono_method_signature (method)->is_inflated) {
1841 * This is a generic method, find the original token which referenced it and
1843 * Obtain the token from information recorded by the JIT.
1845 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1847 image_index = get_image_index (acfg, ji->image);
1848 g_assert (image_index < MAX_IMAGE_INDEX);
1851 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1852 encode_value (image_index, p, &p);
1853 encode_value (token, p, &p);
1855 MonoMethod *declaring;
1856 MonoGenericContext *context = mono_method_get_context (method);
1858 g_assert (method->is_inflated);
1859 declaring = ((MonoMethodInflated*)method)->declaring;
1862 * This might be a non-generic method of a generic instance, which
1863 * doesn't have a token since the reference is generated by the JIT
1864 * like Nullable:Box/Unbox, or by generic sharing.
1867 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1868 /* Encode the klass */
1869 encode_klass_ref (acfg, method->klass, p, &p);
1870 /* Encode the method */
1871 image_index = get_image_index (acfg, method->klass->image);
1872 g_assert (image_index < MAX_IMAGE_INDEX);
1873 g_assert (declaring->token);
1874 token = declaring->token;
1875 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1876 encode_value (image_index, p, &p);
1877 encode_value (token, p, &p);
1878 encode_generic_context (acfg, context, p, &p);
1880 } else if (token == 0) {
1881 /* This might be a method of a constructed type like int[,].Set */
1882 /* Obtain the token from information recorded by the JIT */
1883 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1885 image_index = get_image_index (acfg, ji->image);
1886 g_assert (image_index < MAX_IMAGE_INDEX);
1889 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1890 encode_value (image_index, p, &p);
1891 encode_value (token, p, &p);
1894 g_assert (method->klass->rank);
1896 /* Encode directly */
1897 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1898 encode_klass_ref (acfg, method->klass, p, &p);
1899 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1900 encode_value (0, p, &p);
1901 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1902 encode_value (1, p, &p);
1903 else if (!strcmp (method->name, "Get"))
1904 encode_value (2, p, &p);
1905 else if (!strcmp (method->name, "Address"))
1906 encode_value (3, p, &p);
1907 else if (!strcmp (method->name, "Set"))
1908 encode_value (4, p, &p);
1910 g_assert_not_reached ();
1913 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1914 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1920 compare_patches (gconstpointer a, gconstpointer b)
1924 i = (*(MonoJumpInfo**)a)->ip.i;
1925 j = (*(MonoJumpInfo**)b)->ip.i;
1936 static G_GNUC_UNUSED char*
1937 patch_to_string (MonoJumpInfo *patch_info)
1941 str = g_string_new ("");
1943 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
1945 switch (patch_info->type) {
1946 case MONO_PATCH_INFO_VTABLE:
1947 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
1952 g_string_append_printf (str, ")");
1953 return g_string_free (str, FALSE);
1959 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1962 static inline gboolean
1963 is_plt_patch (MonoJumpInfo *patch_info)
1965 switch (patch_info->type) {
1966 case MONO_PATCH_INFO_METHOD:
1967 case MONO_PATCH_INFO_INTERNAL_METHOD:
1968 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1969 case MONO_PATCH_INFO_ICALL_ADDR:
1970 case MONO_PATCH_INFO_CLASS_INIT:
1971 case MONO_PATCH_INFO_RGCTX_FETCH:
1972 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1973 case MONO_PATCH_INFO_MONITOR_ENTER:
1974 case MONO_PATCH_INFO_MONITOR_EXIT:
1975 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1985 * Return the symbol identifying the plt entry PLT_OFFSET.
1988 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
1992 * The Apple linker reorganizes object files, so it doesn't like branches to local
1993 * labels, since those have no relocations.
1995 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
1997 return g_strdup_printf ("%s%sp_%d", acfg->llvm_label_prefix, acfg->temp_prefix, plt_offset);
2004 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2006 static MonoPltEntry*
2007 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2011 if (!is_plt_patch (patch_info))
2014 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2016 // FIXME: This breaks the calculation of final_got_size
2017 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2019 * Allocate a separate PLT slot for each such patch, since some plt
2020 * entries will refer to the method itself, and some will refer to the
2027 MonoJumpInfo *new_ji;
2029 g_assert (!acfg->final_got_size);
2031 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2033 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2034 res->plt_offset = acfg->plt_offset;
2036 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2038 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2040 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2042 acfg->plt_offset ++;
2051 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2052 * JI could be found if it exists, otherwise allocates a new one.
2055 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2059 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2061 return got_offset - 1;
2063 got_offset = acfg->got_offset;
2064 acfg->got_offset ++;
2066 if (acfg->final_got_size)
2067 g_assert (got_offset < acfg->final_got_size);
2069 acfg->stats.got_slots ++;
2070 acfg->stats.got_slot_types [ji->type] ++;
2072 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2073 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2074 g_ptr_array_add (acfg->got_patches, ji);
2079 /* Add a method to the list of methods which need to be emitted */
2081 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2084 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2085 g_ptr_array_add (acfg->methods, method);
2086 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2087 acfg->nmethods = acfg->methods->len + 1;
2090 if (method->wrapper_type || extra)
2091 g_ptr_array_add (acfg->extra_methods, method);
2095 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2097 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2105 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2109 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2113 index = acfg->method_index;
2114 add_method_with_index (acfg, method, index, extra);
2116 /* FIXME: Fix quadratic behavior */
2117 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2119 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2121 acfg->method_index ++;
2127 add_method (MonoAotCompile *acfg, MonoMethod *method)
2129 return add_method_full (acfg, method, FALSE, 0);
2133 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2135 add_method_full (acfg, method, TRUE, 0);
2139 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2141 add_method_full (acfg, method, TRUE, depth);
2145 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2147 MonoAotCompile *acfg = user_data;
2148 MonoJitICallInfo *callinfo = value;
2149 MonoMethod *wrapper;
2155 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2156 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2159 add_method (acfg, wrapper);
2163 get_runtime_invoke_sig (MonoMethodSignature *sig)
2165 MonoMethodBuilder *mb;
2168 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2169 m = mono_mb_create_method (mb, sig, 16);
2170 return mono_marshal_get_runtime_invoke (m, FALSE);
2174 can_marshal_struct (MonoClass *klass)
2176 MonoClassField *field;
2177 gboolean can_marshal = TRUE;
2178 gpointer iter = NULL;
2180 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2183 /* Only allow a few field types to avoid asserts in the marshalling code */
2184 while ((field = mono_class_get_fields (klass, &iter))) {
2185 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2188 switch (field->type->type) {
2193 case MONO_TYPE_BOOLEAN:
2196 case MONO_TYPE_CHAR:
2204 case MONO_TYPE_STRING:
2206 case MONO_TYPE_VALUETYPE:
2207 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2208 can_marshal = FALSE;
2211 can_marshal = FALSE;
2217 /* Its hard to compute whenever these can be marshalled or not */
2218 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2225 add_wrappers (MonoAotCompile *acfg)
2227 MonoMethod *method, *m;
2229 MonoMethodSignature *sig, *csig;
2233 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2234 * so there is only one wrapper of a given type, or inlining their contents into their
2239 * FIXME: This depends on the fact that different wrappers have different
2243 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2245 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2246 gboolean skip = FALSE;
2248 method = mono_get_method (acfg->image, token, NULL);
2250 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2251 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2252 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2255 if (method->is_generic || method->klass->generic_container)
2258 /* Skip methods which can not be handled by get_runtime_invoke () */
2259 sig = mono_method_signature (method);
2260 if ((sig->ret->type == MONO_TYPE_PTR) ||
2261 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2264 for (j = 0; j < sig->param_count; j++) {
2265 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2269 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2270 if (!method->klass->contextbound) {
2271 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2272 gboolean has_nullable = FALSE;
2274 for (j = 0; j < sig->param_count; j++) {
2275 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2276 has_nullable = TRUE;
2279 if (info && !has_nullable) {
2280 /* Supported by the dynamic runtime-invoke wrapper */
2288 //printf ("%s\n", mono_method_full_name (method, TRUE));
2289 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2293 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2294 #ifdef MONO_ARCH_HAVE_TLS_GET
2295 MonoMethodDesc *desc;
2296 MonoMethod *orig_method;
2300 /* Runtime invoke wrappers */
2302 /* void runtime-invoke () [.cctor] */
2303 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2304 csig->ret = &mono_defaults.void_class->byval_arg;
2305 add_method (acfg, get_runtime_invoke_sig (csig));
2307 /* void runtime-invoke () [Finalize] */
2308 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2310 csig->ret = &mono_defaults.void_class->byval_arg;
2311 add_method (acfg, get_runtime_invoke_sig (csig));
2313 /* void runtime-invoke (string) [exception ctor] */
2314 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2316 csig->ret = &mono_defaults.void_class->byval_arg;
2317 csig->params [0] = &mono_defaults.string_class->byval_arg;
2318 add_method (acfg, get_runtime_invoke_sig (csig));
2320 /* void runtime-invoke (string, string) [exception ctor] */
2321 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2323 csig->ret = &mono_defaults.void_class->byval_arg;
2324 csig->params [0] = &mono_defaults.string_class->byval_arg;
2325 csig->params [1] = &mono_defaults.string_class->byval_arg;
2326 add_method (acfg, get_runtime_invoke_sig (csig));
2328 /* string runtime-invoke () [Exception.ToString ()] */
2329 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2331 csig->ret = &mono_defaults.string_class->byval_arg;
2332 add_method (acfg, get_runtime_invoke_sig (csig));
2334 /* void runtime-invoke (string, Exception) [exception ctor] */
2335 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2337 csig->ret = &mono_defaults.void_class->byval_arg;
2338 csig->params [0] = &mono_defaults.string_class->byval_arg;
2339 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2340 add_method (acfg, get_runtime_invoke_sig (csig));
2342 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2343 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2345 csig->ret = &(mono_class_from_name (
2346 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2347 csig->params [0] = &mono_defaults.string_class->byval_arg;
2348 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2349 add_method (acfg, get_runtime_invoke_sig (csig));
2351 /* runtime-invoke used by finalizers */
2352 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2354 /* This is used by mono_runtime_capture_context () */
2355 method = mono_get_context_capture_method ();
2357 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2359 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2360 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2363 /* JIT icall wrappers */
2364 /* FIXME: locking */
2365 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2368 add_method (acfg, mono_marshal_get_stelemref ());
2370 #ifdef MONO_ARCH_HAVE_TLS_GET
2371 /* Managed Allocators */
2372 nallocators = mono_gc_get_managed_allocator_types ();
2373 for (i = 0; i < nallocators; ++i) {
2374 m = mono_gc_get_managed_allocator_by_type (i);
2376 add_method (acfg, m);
2379 /* Monitor Enter/Exit */
2380 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2381 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2382 g_assert (orig_method);
2383 mono_method_desc_free (desc);
2384 method = mono_monitor_get_fast_path (orig_method);
2386 add_method (acfg, method);
2388 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2389 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2390 g_assert (orig_method);
2391 mono_method_desc_free (desc);
2392 method = mono_monitor_get_fast_path (orig_method);
2394 add_method (acfg, method);
2397 /* Stelemref wrappers */
2398 /* There is only a constant number of these, iterating over all types should handle them all */
2399 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2402 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2403 klass = mono_class_get (acfg->image, token);
2405 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2410 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2411 * we use the original method instead at runtime.
2412 * Since full-aot doesn't support remoting, this is not a problem.
2415 /* remoting-invoke wrappers */
2416 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2417 MonoMethodSignature *sig;
2419 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2420 method = mono_get_method (acfg->image, token, NULL);
2422 sig = mono_method_signature (method);
2424 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2425 m = mono_marshal_get_remoting_invoke_with_check (method);
2427 add_method (acfg, m);
2432 /* delegate-invoke wrappers */
2433 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2436 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2437 klass = mono_class_get (acfg->image, token);
2439 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2440 method = mono_get_delegate_invoke (klass);
2442 m = mono_marshal_get_delegate_invoke (method, NULL);
2444 add_method (acfg, m);
2446 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2447 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2449 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2450 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2454 /* Synchronized wrappers */
2455 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2456 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2457 method = mono_get_method (acfg->image, token, NULL);
2459 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2460 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2463 /* pinvoke wrappers */
2464 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2466 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2468 method = mono_get_method (acfg->image, token, NULL);
2470 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2471 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2472 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2476 /* native-to-managed wrappers */
2477 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2479 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2480 MonoCustomAttrInfo *cattr;
2483 method = mono_get_method (acfg->image, token, NULL);
2486 * Only generate native-to-managed wrappers for methods which have an
2487 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2488 * name to avoid defining a new assembly to contain it.
2490 cattr = mono_custom_attrs_from_method (method);
2493 for (j = 0; j < cattr->num_attrs; ++j)
2494 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2496 if (j < cattr->num_attrs) {
2497 MonoCustomAttrEntry *e = &cattr->attrs [j];
2498 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2499 const char *p = (const char*)e->data;
2505 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2507 g_assert (sig->param_count == 1);
2508 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2511 * Decode the cattr manually since we can't create objects
2512 * during aot compilation.
2518 /* From load_cattr_value () in reflection.c */
2519 slen = mono_metadata_decode_value (p, &p);
2520 n = g_memdup (p, slen + 1);
2522 t = mono_reflection_type_from_name (n, acfg->image);
2526 klass = mono_class_from_mono_type (t);
2527 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2529 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2533 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2534 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2535 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2539 /* StructureToPtr/PtrToStructure wrappers */
2540 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2543 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2544 klass = mono_class_get (acfg->image, token);
2546 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2547 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2548 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2554 has_type_vars (MonoClass *klass)
2556 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2559 return has_type_vars (klass->element_class);
2560 if (klass->generic_class) {
2561 MonoGenericContext *context = &klass->generic_class->context;
2562 if (context->class_inst) {
2565 for (i = 0; i < context->class_inst->type_argc; ++i)
2566 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2574 method_has_type_vars (MonoMethod *method)
2576 if (has_type_vars (method->klass))
2579 if (method->is_inflated) {
2580 MonoGenericContext *context = mono_method_get_context (method);
2581 if (context->method_inst) {
2584 for (i = 0; i < context->method_inst->type_argc; ++i)
2585 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2592 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2595 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2597 add_generic_class_with_depth (acfg, klass, 0);
2601 * add_generic_class:
2603 * Add all methods of a generic class.
2606 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2611 mono_class_init (klass);
2613 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2616 if (has_type_vars (klass))
2619 if (!klass->generic_class && !klass->rank)
2623 while ((method = mono_class_get_methods (klass, &iter))) {
2624 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2628 if (method->is_generic)
2633 * FIXME: Instances which are referenced by these methods are not added,
2634 * for example Array.Resize<int> for List<int>.Add ().
2636 add_extra_method_with_depth (acfg, method, depth);
2639 if (klass->delegate) {
2640 method = mono_get_delegate_invoke (klass);
2642 method = mono_marshal_get_delegate_invoke (method, NULL);
2644 add_method (acfg, method);
2648 * For ICollection<T>, add instances of the helper methods
2649 * in Array, since a T[] could be cast to ICollection<T>.
2651 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2652 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2653 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2654 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2658 if (!strcmp (klass->name, "IEnumerator`1"))
2659 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2661 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2663 /* Add the T[]/InternalEnumerator class */
2664 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2668 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2669 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2673 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2674 add_generic_class (acfg, nclass);
2678 while ((method = mono_class_get_methods (array_class, &iter))) {
2679 if (strstr (method->name, name_prefix)) {
2680 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2681 add_extra_method_with_depth (acfg, m, depth);
2685 g_free (name_prefix);
2688 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2689 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2690 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2691 MonoClass *icomparable, *gcomparer;
2692 MonoGenericContext ctx;
2693 MonoType *args [16];
2695 memset (&ctx, 0, sizeof (ctx));
2697 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2698 g_assert (icomparable);
2699 args [0] = &tclass->byval_arg;
2700 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2702 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2703 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2704 g_assert (gcomparer);
2705 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2709 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2710 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2711 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2712 MonoClass *iface, *gcomparer;
2713 MonoGenericContext ctx;
2714 MonoType *args [16];
2716 memset (&ctx, 0, sizeof (ctx));
2718 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2720 args [0] = &tclass->byval_arg;
2721 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2723 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2724 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2725 g_assert (gcomparer);
2726 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2732 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2735 MonoGenericContext ctx;
2736 MonoType *args [16];
2738 memset (&ctx, 0, sizeof (ctx));
2740 for (i = 0; i < ninsts; ++i) {
2741 args [0] = insts [i];
2742 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2743 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2748 * add_generic_instances:
2750 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2753 add_generic_instances (MonoAotCompile *acfg)
2758 MonoMethodHeader *header;
2759 MonoMethodSignature *sig;
2760 MonoGenericContext *context;
2762 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2763 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2764 method = mono_get_method (acfg->image, token, NULL);
2766 if (method->klass->image != acfg->image)
2769 context = mono_method_get_context (method);
2771 if (context && ((context->class_inst && context->class_inst->is_open)))
2775 * For open methods, create an instantiation which can be passed to the JIT.
2776 * FIXME: Handle class_inst as well.
2778 if (context && context->method_inst && context->method_inst->is_open) {
2779 MonoGenericContext shared_context;
2780 MonoGenericInst *inst;
2781 MonoType **type_argv;
2783 MonoMethod *declaring_method;
2784 gboolean supported = TRUE;
2786 /* Check that the context doesn't contain open constructed types */
2787 if (context->class_inst) {
2788 inst = context->class_inst;
2789 for (i = 0; i < inst->type_argc; ++i) {
2790 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2792 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2796 if (context->method_inst) {
2797 inst = context->method_inst;
2798 for (i = 0; i < inst->type_argc; ++i) {
2799 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2801 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2809 memset (&shared_context, 0, sizeof (MonoGenericContext));
2811 inst = context->class_inst;
2813 type_argv = g_new0 (MonoType*, inst->type_argc);
2814 for (i = 0; i < inst->type_argc; ++i) {
2815 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2816 type_argv [i] = &mono_defaults.object_class->byval_arg;
2818 type_argv [i] = inst->type_argv [i];
2821 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2825 inst = context->method_inst;
2827 type_argv = g_new0 (MonoType*, inst->type_argc);
2828 for (i = 0; i < inst->type_argc; ++i) {
2829 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2830 type_argv [i] = &mono_defaults.object_class->byval_arg;
2832 type_argv [i] = inst->type_argv [i];
2835 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2839 if (method->is_generic || method->klass->generic_container)
2840 declaring_method = method;
2842 declaring_method = mono_method_get_declaring_generic_method (method);
2844 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
2848 * If the method is fully sharable, it was already added in place of its
2849 * generic definition.
2851 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2855 * FIXME: Partially shared methods are not shared here, so we end up with
2856 * many identical methods.
2858 add_extra_method (acfg, method);
2861 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2864 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2866 klass = mono_class_get (acfg->image, token);
2867 if (!klass || klass->rank)
2870 add_generic_class (acfg, klass);
2873 /* Add types of args/locals */
2874 for (i = 0; i < acfg->methods->len; ++i) {
2877 method = g_ptr_array_index (acfg->methods, i);
2879 sig = mono_method_signature (method);
2882 for (j = 0; j < sig->param_count; ++j)
2883 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2884 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2887 header = mono_method_get_header (method);
2890 for (j = 0; j < header->num_locals; ++j)
2891 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2892 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2896 if (acfg->image == mono_defaults.corlib) {
2898 MonoType *insts [256];
2901 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2902 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2903 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2904 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2905 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2906 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2907 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2908 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2909 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2910 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2911 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2912 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2914 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2915 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2917 add_instances_of (acfg, klass, insts, ninsts);
2918 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2920 add_instances_of (acfg, klass, insts, ninsts);
2922 /* Add instances of the array generic interfaces for primitive types */
2923 /* This will add instances of the InternalArray_ helper methods in Array too */
2924 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2926 add_instances_of (acfg, klass, insts, ninsts);
2927 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2929 add_instances_of (acfg, klass, insts, ninsts);
2930 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2932 add_instances_of (acfg, klass, insts, ninsts);
2935 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2936 * used for all instances of GetGenericValueImpl by the AOT runtime.
2939 MonoGenericContext ctx;
2940 MonoType *args [16];
2941 MonoMethod *get_method;
2942 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2944 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2947 memset (&ctx, 0, sizeof (ctx));
2948 args [0] = &mono_defaults.object_class->byval_arg;
2949 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2950 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2957 * is_direct_callable:
2959 * Return whenever the method identified by JI is directly callable without
2960 * going through the PLT.
2963 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2965 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2966 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2968 gboolean direct_callable = TRUE;
2970 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2971 direct_callable = FALSE;
2972 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2973 // FIXME: Maybe call the wrapper directly ?
2974 direct_callable = FALSE;
2976 if (direct_callable)
2985 * emit_and_reloc_code:
2987 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2988 * is true, calls are made through the GOT too. This is used for emitting trampolines
2989 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2990 * since trampolines are needed to make PTL work.
2993 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2995 int i, pindex, start_index, method_index;
2997 MonoJumpInfo *patch_info;
2998 MonoMethodHeader *header;
2999 gboolean skip, direct_call;
3001 char direct_call_target [128];
3004 header = mono_method_get_header (method);
3006 method_index = get_method_index (acfg, method);
3009 /* Collect and sort relocations */
3010 patches = g_ptr_array_new ();
3011 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3012 g_ptr_array_add (patches, patch_info);
3013 g_ptr_array_sort (patches, compare_patches);
3016 for (i = 0; i < code_len; i++) {
3018 for (pindex = start_index; pindex < patches->len; ++pindex) {
3019 patch_info = g_ptr_array_index (patches, pindex);
3020 if (patch_info->ip.i >= i)
3024 #ifdef MONO_ARCH_AOT_SUPPORTED
3026 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3027 start_index = pindex;
3029 switch (patch_info->type) {
3030 case MONO_PATCH_INFO_NONE:
3032 case MONO_PATCH_INFO_GOT_OFFSET: {
3035 arch_emit_got_offset (acfg, code + i, &code_size);
3038 patch_info->type = MONO_PATCH_INFO_NONE;
3043 * If this patch is a call, try emitting a direct call instead of
3044 * through a PLT entry. This is possible if the called method is in
3045 * the same assembly and requires no initialization.
3047 direct_call = FALSE;
3048 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3049 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3050 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3051 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3053 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3054 patch_info->type = MONO_PATCH_INFO_NONE;
3055 acfg->stats.direct_calls ++;
3058 acfg->stats.all_calls ++;
3061 if (!got_only && !direct_call) {
3062 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3064 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3066 sprintf (direct_call_target, "%s", plt_entry->symbol);
3068 /* Nullify the patch */
3069 patch_info->type = MONO_PATCH_INFO_NONE;
3076 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3081 got_slot = get_got_offset (acfg, patch_info);
3083 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3090 #endif /* MONO_ARCH_AOT_SUPPORTED */
3093 /* Find next patch */
3095 for (pindex = start_index; pindex < patches->len; ++pindex) {
3096 patch_info = g_ptr_array_index (patches, pindex);
3097 if (patch_info->ip.i >= i)
3101 /* Try to emit multiple bytes at once */
3102 if (pindex < patches->len && patch_info->ip.i > i) {
3103 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3104 i = patch_info->ip.i - 1;
3106 emit_bytes (acfg, code + i, 1);
3115 * Modify SYMBOL so it only includes characters permissible in symbols.
3118 sanitize_symbol (char *symbol)
3120 int i, len = strlen (symbol);
3122 for (i = 0; i < len; ++i)
3123 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3128 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3130 char *name1, *name2, *cached;
3131 int i, j, len, count;
3133 name1 = mono_method_full_name (method, TRUE);
3134 len = strlen (name1);
3135 name2 = malloc (strlen (prefix) + len + 16);
3136 memcpy (name2, prefix, strlen (prefix));
3137 j = strlen (prefix);
3138 for (i = 0; i < len; ++i) {
3139 if (isalnum (name1 [i])) {
3140 name2 [j ++] = name1 [i];
3141 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3143 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3146 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3155 while (g_hash_table_lookup (cache, name2)) {
3156 sprintf (name2 + j, "_%d", count);
3160 cached = g_strdup (name2);
3161 g_hash_table_insert (cache, cached, cached);
3167 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3172 char *debug_sym = NULL;
3174 int func_alignment = AOT_FUNC_ALIGNMENT;
3175 MonoMethodHeader *header;
3177 method = cfg->orig_method;
3178 code = cfg->native_code;
3179 header = cfg->header;
3181 method_index = get_method_index (acfg, method);
3183 /* Make the labels local */
3184 sprintf (symbol, "%s", cfg->asm_symbol);
3186 emit_section_change (acfg, ".text", 0);
3187 emit_alignment (acfg, func_alignment);
3188 emit_label (acfg, symbol);
3190 if (acfg->aot_opts.write_symbols) {
3192 * Write a C style symbol for every method, this has two uses:
3193 * - it works on platforms where the dwarf debugging info is not
3195 * - it allows the setting of breakpoints of aot-ed methods.
3197 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3199 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3200 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3201 emit_label (acfg, debug_sym);
3204 if (cfg->verbose_level > 0)
3205 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3207 acfg->stats.code_size += cfg->code_len;
3209 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3211 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3215 if (acfg->aot_opts.write_symbols) {
3216 emit_symbol_size (acfg, debug_sym, ".");
3220 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3221 emit_label (acfg, symbol);
3227 * Encode PATCH_INFO into its disk representation.
3230 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3234 switch (patch_info->type) {
3235 case MONO_PATCH_INFO_NONE:
3237 case MONO_PATCH_INFO_IMAGE:
3238 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3240 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3241 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3243 case MONO_PATCH_INFO_METHOD_REL:
3244 encode_value ((gint)patch_info->data.offset, p, &p);
3246 case MONO_PATCH_INFO_SWITCH: {
3247 gpointer *table = (gpointer *)patch_info->data.table->table;
3250 encode_value (patch_info->data.table->table_size, p, &p);
3251 for (k = 0; k < patch_info->data.table->table_size; k++)
3252 encode_value ((int)(gssize)table [k], p, &p);
3255 case MONO_PATCH_INFO_METHODCONST:
3256 case MONO_PATCH_INFO_METHOD:
3257 case MONO_PATCH_INFO_METHOD_JUMP:
3258 case MONO_PATCH_INFO_ICALL_ADDR:
3259 case MONO_PATCH_INFO_METHOD_RGCTX:
3260 encode_method_ref (acfg, patch_info->data.method, p, &p);
3262 case MONO_PATCH_INFO_INTERNAL_METHOD:
3263 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3264 guint32 len = strlen (patch_info->data.name);
3266 encode_value (len, p, &p);
3268 memcpy (p, patch_info->data.name, len);
3273 case MONO_PATCH_INFO_LDSTR: {
3274 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3275 guint32 token = patch_info->data.token->token;
3276 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3277 encode_value (image_index, p, &p);
3278 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3281 case MONO_PATCH_INFO_RVA:
3282 case MONO_PATCH_INFO_DECLSEC:
3283 case MONO_PATCH_INFO_LDTOKEN:
3284 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3285 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3286 encode_value (patch_info->data.token->token, p, &p);
3287 encode_value (patch_info->data.token->has_context, p, &p);
3288 if (patch_info->data.token->has_context)
3289 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3291 case MONO_PATCH_INFO_EXC_NAME: {
3292 MonoClass *ex_class;
3295 mono_class_from_name (mono_defaults.exception_class->image,
3296 "System", patch_info->data.target);
3297 g_assert (ex_class);
3298 encode_klass_ref (acfg, ex_class, p, &p);
3301 case MONO_PATCH_INFO_R4:
3302 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3304 case MONO_PATCH_INFO_R8:
3305 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3306 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3308 case MONO_PATCH_INFO_VTABLE:
3309 case MONO_PATCH_INFO_CLASS:
3310 case MONO_PATCH_INFO_IID:
3311 case MONO_PATCH_INFO_ADJUSTED_IID:
3312 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3314 case MONO_PATCH_INFO_CLASS_INIT:
3315 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3316 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3318 case MONO_PATCH_INFO_FIELD:
3319 case MONO_PATCH_INFO_SFLDA:
3320 encode_field_info (acfg, patch_info->data.field, p, &p);
3322 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3324 case MONO_PATCH_INFO_RGCTX_FETCH: {
3325 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3327 encode_method_ref (acfg, entry->method, p, &p);
3328 encode_value (entry->in_mrgctx, p, &p);
3329 encode_value (entry->info_type, p, &p);
3330 encode_value (entry->data->type, p, &p);
3331 encode_patch (acfg, entry->data, p, &p);
3334 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3335 case MONO_PATCH_INFO_MONITOR_ENTER:
3336 case MONO_PATCH_INFO_MONITOR_EXIT:
3337 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3339 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3340 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3341 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3344 g_warning ("unable to handle jump info %d", patch_info->type);
3345 g_assert_not_reached ();
3352 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3355 guint32 pindex, offset;
3356 MonoJumpInfo *patch_info;
3358 encode_value (n_patches, p, &p);
3360 for (pindex = 0; pindex < patches->len; ++pindex) {
3361 patch_info = g_ptr_array_index (patches, pindex);
3363 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3367 offset = get_got_offset (acfg, patch_info);
3368 encode_value (offset, p, &p);
3375 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3379 int pindex, buf_size, n_patches;
3382 MonoJumpInfo *patch_info;
3383 MonoMethodHeader *header;
3384 guint32 method_index;
3386 guint32 first_got_offset;
3388 method = cfg->orig_method;
3389 code = cfg->native_code;
3390 header = mono_method_get_header (method);
3392 method_index = get_method_index (acfg, method);
3394 /* Sort relocations */
3395 patches = g_ptr_array_new ();
3396 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3397 g_ptr_array_add (patches, patch_info);
3398 g_ptr_array_sort (patches, compare_patches);
3400 first_got_offset = acfg->cfgs [method_index]->got_offset;
3402 /**********************/
3403 /* Encode method info */
3404 /**********************/
3406 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3407 p = buf = g_malloc (buf_size);
3409 if (mono_class_get_cctor (method->klass))
3410 encode_klass_ref (acfg, method->klass, p, &p);
3412 /* Not needed when loading the method */
3413 encode_value (0, p, &p);
3416 if (cfg->opt & MONO_OPT_SHARED) {
3417 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3418 for (l = cfg->ldstr_list; l; l = l->next) {
3419 encode_value ((long)l->data, p, &p);
3423 /* Used only in shared mode */
3424 g_assert (!cfg->ldstr_list);
3427 for (pindex = 0; pindex < patches->len; ++pindex) {
3428 patch_info = g_ptr_array_index (patches, pindex);
3430 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3431 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3432 patch_info->type = MONO_PATCH_INFO_NONE;
3437 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3438 /* Stored in a GOT slot initialized at module load time */
3439 patch_info->type = MONO_PATCH_INFO_NONE;
3443 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3444 /* Stored in a GOT slot initialized at module load time */
3445 patch_info->type = MONO_PATCH_INFO_NONE;
3449 if (is_plt_patch (patch_info)) {
3450 /* Calls are made through the PLT */
3451 patch_info->type = MONO_PATCH_INFO_NONE;
3459 g_assert (cfg->has_got_slots);
3461 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3463 acfg->stats.info_size += p - buf;
3465 g_assert (p - buf < buf_size);
3467 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3472 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3474 guint32 cache_index;
3477 /* Reuse the unwind module to canonize and store unwind info entries */
3478 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3480 /* Use +/- 1 to distinguish 0s from missing entries */
3481 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3489 * It would be easier to use assembler symbols, but the caller needs an
3492 offset = acfg->unwind_info_offset;
3493 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3494 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3497 encode_value (encoded_len, p, &p);
3499 acfg->unwind_info_offset += encoded_len + (p - buf);
3505 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3508 int i, k, buf_size, method_index;
3509 guint32 debug_info_size;
3511 MonoMethodHeader *header;
3512 guint8 *p, *buf, *debug_info;
3513 MonoJitInfo *jinfo = cfg->jit_info;
3515 gboolean use_unwind_ops = FALSE;
3516 MonoSeqPointInfo *seq_points;
3518 method = cfg->orig_method;
3519 code = cfg->native_code;
3520 header = cfg->header;
3522 method_index = get_method_index (acfg, method);
3524 if (!acfg->aot_opts.nodebug) {
3525 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3528 debug_info_size = 0;
3531 seq_points = cfg->seq_point_info;
3533 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3534 p = buf = g_malloc (buf_size);
3536 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3537 use_unwind_ops = cfg->unwind_ops != NULL;
3540 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0);
3542 encode_value (flags, p, &p);
3544 if (use_unwind_ops) {
3545 guint32 encoded_len;
3549 * This is a duplicate of the data in the .debug_frame section, but that
3550 * section cannot be accessed using the dl interface.
3552 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3553 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3556 encode_value (jinfo->used_regs, p, &p);
3559 /*Encode the number of holes before the number of clauses to make decoding easier*/
3560 if (jinfo->has_try_block_holes) {
3561 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3562 encode_value (table->num_holes, p, &p);
3565 /* Exception table */
3566 if (cfg->compile_llvm) {
3568 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3569 * since the information is only available to llc. Instead, we let llc save the data
3570 * into the LSDA, and read it from there at runtime.
3572 /* The assembly might be CIL stripped so emit the data ourselves */
3573 if (header->num_clauses)
3574 encode_value (header->num_clauses, p, &p);
3576 for (k = 0; k < header->num_clauses; ++k) {
3577 MonoExceptionClause *clause;
3579 clause = &header->clauses [k];
3581 encode_value (clause->flags, p, &p);
3582 if (clause->data.catch_class) {
3583 encode_value (1, p, &p);
3584 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3586 encode_value (0, p, &p);
3589 /* Emit a list of nesting clauses */
3590 for (i = 0; i < header->num_clauses; ++i) {
3592 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3594 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3596 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3597 encode_value (i, p, &p);
3599 encode_value (-1, p, &p);
3602 if (jinfo->num_clauses)
3603 encode_value (jinfo->num_clauses, p, &p);
3605 for (k = 0; k < jinfo->num_clauses; ++k) {
3606 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3608 encode_value (ei->flags, p, &p);
3609 encode_value (ei->exvar_offset, p, &p);
3611 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3612 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3614 if (ei->data.catch_class) {
3615 encode_value (1, p, &p);
3616 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3618 encode_value (0, p, &p);
3622 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3623 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3624 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3628 if (jinfo->has_generic_jit_info) {
3629 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3631 if (!cfg->compile_llvm) {
3632 encode_value (gi->has_this ? 1 : 0, p, &p);
3633 encode_value (gi->this_reg, p, &p);
3634 encode_value (gi->this_offset, p, &p);
3638 * Need to encode jinfo->method too, since it is not equal to 'method'
3639 * when using generic sharing.
3641 encode_method_ref (acfg, jinfo->method, p, &p);
3644 if (jinfo->has_try_block_holes) {
3645 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3646 for (i = 0; i < table->num_holes; ++i) {
3647 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3648 encode_value (hole->clause, p, &p);
3649 encode_value (hole->length, p, &p);
3650 encode_value (hole->offset, p, &p);
3655 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3657 encode_value (seq_points->len, p, &p);
3658 last_il_offset = last_native_offset = 0;
3659 for (i = 0; i < seq_points->len; ++i) {
3660 SeqPoint *sp = &seq_points->seq_points [i];
3661 il_offset = sp->il_offset;
3662 native_offset = sp->native_offset;
3663 encode_value (il_offset - last_il_offset, p, &p);
3664 encode_value (native_offset - last_native_offset, p, &p);
3665 last_il_offset = il_offset;
3666 last_native_offset = native_offset;
3668 encode_value (sp->next_len, p, &p);
3669 for (j = 0; j < sp->next_len; ++j)
3670 encode_value (sp->next [j], p, &p);
3675 g_assert (debug_info_size < buf_size);
3677 encode_value (debug_info_size, p, &p);
3678 if (debug_info_size) {
3679 memcpy (p, debug_info, debug_info_size);
3680 p += debug_info_size;
3681 g_free (debug_info);
3684 acfg->stats.ex_info_size += p - buf;
3686 g_assert (p - buf < buf_size);
3689 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3694 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3696 MonoClass *klass = mono_class_get (acfg->image, token);
3698 int i, buf_size, res;
3699 gboolean no_special_static, cant_encode;
3700 gpointer iter = NULL;
3705 p = buf = g_malloc (buf_size);
3707 /* Mark as unusable */
3708 encode_value (-1, p, &p);
3710 res = add_to_blob (acfg, buf, p - buf);
3716 buf_size = 10240 + (klass->vtable_size * 16);
3717 p = buf = g_malloc (buf_size);
3721 mono_class_init (klass);
3723 mono_class_get_nested_types (klass, &iter);
3724 g_assert (klass->nested_classes_inited);
3726 mono_class_setup_vtable (klass);
3729 * Emit all the information which is required for creating vtables so
3730 * the runtime does not need to create the MonoMethod structures which
3731 * take up a lot of space.
3734 no_special_static = !mono_class_has_special_static_fields (klass);
3736 /* Check whenever we have enough info to encode the vtable */
3737 cant_encode = FALSE;
3738 for (i = 0; i < klass->vtable_size; ++i) {
3739 MonoMethod *cm = klass->vtable [i];
3741 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3745 if (klass->generic_container || cant_encode) {
3746 encode_value (-1, p, &p);
3748 encode_value (klass->vtable_size, p, &p);
3749 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
3750 if (klass->has_cctor)
3751 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3752 if (klass->has_finalize)
3753 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3755 encode_value (klass->instance_size, p, &p);
3756 encode_value (mono_class_data_size (klass), p, &p);
3757 encode_value (klass->packing_size, p, &p);
3758 encode_value (klass->min_align, p, &p);
3760 for (i = 0; i < klass->vtable_size; ++i) {
3761 MonoMethod *cm = klass->vtable [i];
3764 encode_method_ref (acfg, cm, p, &p);
3766 encode_value (0, p, &p);
3770 acfg->stats.class_info_size += p - buf;
3772 g_assert (p - buf < buf_size);
3773 res = add_to_blob (acfg, buf, p - buf);
3780 * Calls made from AOTed code are routed through a table of jumps similar to the
3781 * ELF PLT (Program Linkage Table). The differences are the following:
3782 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3783 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3784 * jumps. This means the jumps need to be patched when the address of the callee is
3785 * known. Initially the PLT entries jump to code which transfers control to the
3786 * AOT runtime through the first PLT entry.
3789 emit_plt (MonoAotCompile *acfg)
3795 cache = g_hash_table_new (g_str_hash, g_str_equal);
3798 sprintf (symbol, "plt");
3800 emit_section_change (acfg, ".text", 0);
3801 emit_global (acfg, symbol, TRUE);
3802 emit_alignment (acfg, 16);
3803 emit_label (acfg, symbol);
3804 emit_label (acfg, acfg->plt_symbol);
3806 for (i = 0; i < acfg->plt_offset; ++i) {
3808 char *debug_sym = NULL;
3809 MonoPltEntry *plt_entry = NULL;
3814 * The first plt entry is used to transfer code to the AOT loader.
3816 arch_emit_plt_entry (acfg, i);
3820 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3822 sprintf (label, "%s", plt_entry->symbol);
3826 * If the target is directly callable, alias the plt symbol to point to
3828 * FIXME: Use this to simplify emit_and_reloc_code ().
3829 * FIXME: Avoid the got slot.
3830 * FIXME: Add support to the binary writer.
3832 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3833 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3834 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3839 emit_label (acfg, label);
3841 if (acfg->aot_opts.write_symbols) {
3843 case MONO_PATCH_INFO_METHOD:
3844 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3846 case MONO_PATCH_INFO_INTERNAL_METHOD:
3847 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3849 case MONO_PATCH_INFO_CLASS_INIT:
3850 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3851 sanitize_symbol (debug_sym);
3853 case MONO_PATCH_INFO_RGCTX_FETCH:
3854 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3856 case MONO_PATCH_INFO_ICALL_ADDR: {
3857 char *s = get_debug_sym (ji->data.method, "", cache);
3859 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3863 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3864 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3866 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3867 debug_sym = g_strdup_printf ("plt__generic_class_init");
3874 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3875 emit_label (acfg, debug_sym);
3879 arch_emit_plt_entry (acfg, i);
3882 emit_symbol_size (acfg, debug_sym, ".");
3887 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3889 sprintf (symbol, "plt_end");
3890 emit_global (acfg, symbol, TRUE);
3891 emit_label (acfg, symbol);
3893 g_hash_table_destroy (cache);
3896 static G_GNUC_UNUSED void
3897 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
3899 char start_symbol [256];
3901 guint32 buf_size, info_offset;
3902 MonoJumpInfo *patch_info;
3913 code_size = info->code_size;
3915 unwind_ops = info->unwind_ops;
3917 #ifdef __native_client_codegen__
3918 mono_nacl_fix_patches (code, ji);
3923 sprintf (start_symbol, "%s", name);
3925 emit_section_change (acfg, ".text", 0);
3926 emit_global (acfg, start_symbol, TRUE);
3927 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
3928 emit_label (acfg, start_symbol);
3930 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3931 emit_label (acfg, symbol);
3934 * The code should access everything through the GOT, so we pass
3937 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3939 emit_symbol_size (acfg, start_symbol, ".");
3943 /* Sort relocations */
3944 patches = g_ptr_array_new ();
3945 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3946 if (patch_info->type != MONO_PATCH_INFO_NONE)
3947 g_ptr_array_add (patches, patch_info);
3948 g_ptr_array_sort (patches, compare_patches);
3950 buf_size = patches->len * 128 + 128;
3951 buf = g_malloc (buf_size);
3954 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3955 g_assert (p - buf < buf_size);
3957 sprintf (symbol, "%s_p", name);
3959 info_offset = add_to_blob (acfg, buf, p - buf);
3961 emit_section_change (acfg, RODATA_SECT, 0);
3962 emit_global (acfg, symbol, FALSE);
3963 emit_label (acfg, symbol);
3965 emit_int32 (acfg, info_offset);
3967 /* Emit debug info */
3971 sprintf (symbol, "%s", name);
3972 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3975 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3980 emit_trampolines (MonoAotCompile *acfg)
3983 int i, tramp_got_offset;
3984 MonoAotTrampoline ntype;
3985 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3990 if (!acfg->aot_opts.full_aot)
3993 g_assert (acfg->image->assembly);
3995 /* Currently, we emit most trampolines into the mscorlib AOT image. */
3996 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3997 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3998 MonoTrampInfo *info;
4001 * Emit the generic trampolines.
4003 * We could save some code by treating the generic trampolines as a wrapper
4004 * method, but that approach has its own complexities, so we choose the simpler
4007 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4008 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4009 emit_trampoline (acfg, acfg->got_offset, info);
4012 mono_arch_get_nullified_class_init_trampoline (&info);
4013 emit_trampoline (acfg, acfg->got_offset, info);
4014 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4015 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4016 emit_trampoline (acfg, acfg->got_offset, info);
4017 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4018 emit_trampoline (acfg, acfg->got_offset, info);
4021 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4022 emit_trampoline (acfg, acfg->got_offset, info);
4024 /* Emit the exception related code pieces */
4025 code = mono_arch_get_restore_context (&info, TRUE);
4026 emit_trampoline (acfg, acfg->got_offset, info);
4027 code = mono_arch_get_call_filter (&info, TRUE);
4028 emit_trampoline (acfg, acfg->got_offset, info);
4029 code = mono_arch_get_throw_exception (&info, TRUE);
4030 emit_trampoline (acfg, acfg->got_offset, info);
4031 code = mono_arch_get_rethrow_exception (&info, TRUE);
4032 emit_trampoline (acfg, acfg->got_offset, info);
4033 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4034 emit_trampoline (acfg, acfg->got_offset, info);
4036 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4038 GSList *l = mono_arch_get_trampolines (TRUE);
4041 MonoTrampInfo *info = l->data;
4043 emit_trampoline (acfg, acfg->got_offset, info);
4049 for (i = 0; i < 128; ++i) {
4052 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4053 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4054 emit_trampoline (acfg, acfg->got_offset, info);
4056 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4057 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4058 emit_trampoline (acfg, acfg->got_offset, info);
4064 /* delegate_invoke_impl trampolines */
4065 l = mono_arch_get_delegate_invoke_impls ();
4067 MonoTrampInfo *info = l->data;
4069 emit_trampoline (acfg, acfg->got_offset, info);
4074 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4076 /* Emit trampolines which are numerous */
4079 * These include the following:
4080 * - specific trampolines
4081 * - static rgctx invoke trampolines
4083 * These trampolines have the same code, they are parameterized by GOT
4085 * They are defined in this file, in the arch_... routines instead of
4086 * in tramp-<ARCH>.c, since it is easier to do it this way.
4090 * When running in aot-only mode, we can't create specific trampolines at
4091 * runtime, so we create a few, and save them in the AOT file.
4092 * Normal trampolines embed their argument as a literal inside the
4093 * trampoline code, we can't do that here, so instead we embed an offset
4094 * which needs to be added to the trampoline address to get the address of
4095 * the GOT slot which contains the argument value.
4096 * The generated trampolines jump to the generic trampolines using another
4097 * GOT slot, which will be setup by the AOT loader to point to the
4098 * generic trampoline code of the given type.
4102 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4106 emit_section_change (acfg, ".text", 0);
4108 tramp_got_offset = acfg->got_offset;
4110 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4112 case MONO_AOT_TRAMP_SPECIFIC:
4113 sprintf (symbol, "specific_trampolines");
4115 case MONO_AOT_TRAMP_STATIC_RGCTX:
4116 sprintf (symbol, "static_rgctx_trampolines");
4118 case MONO_AOT_TRAMP_IMT_THUNK:
4119 sprintf (symbol, "imt_thunks");
4122 g_assert_not_reached ();
4125 emit_global (acfg, symbol, TRUE);
4126 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4127 emit_label (acfg, symbol);
4129 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4131 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4135 case MONO_AOT_TRAMP_SPECIFIC:
4136 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4137 tramp_got_offset += 2;
4139 case MONO_AOT_TRAMP_STATIC_RGCTX:
4140 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4141 tramp_got_offset += 2;
4143 case MONO_AOT_TRAMP_IMT_THUNK:
4144 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4145 tramp_got_offset += 1;
4148 g_assert_not_reached ();
4150 #ifdef __native_client_codegen__
4151 /* align to avoid 32-byte boundary crossings */
4152 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4155 if (!acfg->trampoline_size [ntype]) {
4156 g_assert (tramp_size);
4157 acfg->trampoline_size [ntype] = tramp_size;
4162 /* Reserve some entries at the end of the GOT for our use */
4163 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4166 acfg->got_offset += acfg->num_trampoline_got_entries;
4170 str_begins_with (const char *str1, const char *str2)
4172 int len = strlen (str2);
4173 return strncmp (str1, str2, len) == 0;
4177 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4179 gchar **args, **ptr;
4181 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4182 for (ptr = args; ptr && *ptr; ptr ++) {
4183 const char *arg = *ptr;
4185 if (str_begins_with (arg, "outfile=")) {
4186 opts->outfile = g_strdup (arg + strlen ("outfile="));
4187 } else if (str_begins_with (arg, "save-temps")) {
4188 opts->save_temps = TRUE;
4189 } else if (str_begins_with (arg, "keep-temps")) {
4190 opts->save_temps = TRUE;
4191 } else if (str_begins_with (arg, "write-symbols")) {
4192 opts->write_symbols = TRUE;
4193 } else if (str_begins_with (arg, "metadata-only")) {
4194 opts->metadata_only = TRUE;
4195 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4196 opts->bind_to_runtime_version = TRUE;
4197 } else if (str_begins_with (arg, "full")) {
4198 opts->full_aot = TRUE;
4199 } else if (str_begins_with (arg, "threads=")) {
4200 opts->nthreads = atoi (arg + strlen ("threads="));
4201 } else if (str_begins_with (arg, "static")) {
4202 opts->static_link = TRUE;
4203 opts->no_dlsym = TRUE;
4204 } else if (str_begins_with (arg, "asmonly")) {
4205 opts->asm_only = TRUE;
4206 } else if (str_begins_with (arg, "asmwriter")) {
4207 opts->asm_writer = TRUE;
4208 } else if (str_begins_with (arg, "nodebug")) {
4209 opts->nodebug = TRUE;
4210 } else if (str_begins_with (arg, "ntrampolines=")) {
4211 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4212 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4213 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4214 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4215 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4216 } else if (str_begins_with (arg, "autoreg")) {
4217 opts->autoreg = TRUE;
4218 } else if (str_begins_with (arg, "tool-prefix=")) {
4219 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4220 } else if (str_begins_with (arg, "soft-debug")) {
4221 opts->soft_debug = TRUE;
4222 } else if (str_begins_with (arg, "print-skipped")) {
4223 opts->print_skipped_methods = TRUE;
4224 } else if (str_begins_with (arg, "stats")) {
4227 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4236 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4238 MonoMethod *method = (MonoMethod*)key;
4239 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4240 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4241 MonoAotCompile *acfg = user_data;
4243 new_ji->image = ji->image;
4244 new_ji->token = ji->token;
4245 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4249 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4251 if (klass->type_token)
4253 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4256 return can_encode_class (acfg, klass->element_class);
4261 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4263 switch (patch_info->type) {
4264 case MONO_PATCH_INFO_METHOD:
4265 case MONO_PATCH_INFO_METHODCONST: {
4266 MonoMethod *method = patch_info->data.method;
4268 if (method->wrapper_type) {
4269 switch (method->wrapper_type) {
4270 case MONO_WRAPPER_NONE:
4271 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4272 case MONO_WRAPPER_XDOMAIN_INVOKE:
4273 case MONO_WRAPPER_STFLD:
4274 case MONO_WRAPPER_LDFLD:
4275 case MONO_WRAPPER_LDFLDA:
4276 case MONO_WRAPPER_LDFLD_REMOTE:
4277 case MONO_WRAPPER_STFLD_REMOTE:
4278 case MONO_WRAPPER_STELEMREF:
4279 case MONO_WRAPPER_ISINST:
4280 case MONO_WRAPPER_PROXY_ISINST:
4281 case MONO_WRAPPER_ALLOC:
4282 case MONO_WRAPPER_REMOTING_INVOKE:
4283 case MONO_WRAPPER_UNKNOWN:
4284 case MONO_WRAPPER_WRITE_BARRIER:
4286 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4287 if (!strcmp (method->name, "ElementAddr"))
4292 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4296 if (!method->token) {
4297 /* The method is part of a constructed type like Int[,].Set (). */
4298 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4299 if (method->klass->rank)
4307 case MONO_PATCH_INFO_VTABLE:
4308 case MONO_PATCH_INFO_CLASS_INIT:
4309 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4310 case MONO_PATCH_INFO_CLASS:
4311 case MONO_PATCH_INFO_IID:
4312 case MONO_PATCH_INFO_ADJUSTED_IID:
4313 if (!can_encode_class (acfg, patch_info->data.klass)) {
4314 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4318 case MONO_PATCH_INFO_RGCTX_FETCH: {
4319 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4321 if (!can_encode_patch (acfg, entry->data))
4333 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
4338 * AOT compile a given method.
4339 * This function might be called by multiple threads, so it must be thread-safe.
4342 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4345 MonoJumpInfo *patch_info;
4348 MonoMethod *wrapped;
4350 if (acfg->aot_opts.metadata_only)
4353 mono_acfg_lock (acfg);
4354 index = get_method_index (acfg, method);
4355 mono_acfg_unlock (acfg);
4357 /* fixme: maybe we can also precompile wrapper methods */
4358 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4359 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4360 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4361 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4365 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4368 wrapped = mono_marshal_method_from_wrapper (method);
4369 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4370 // FIXME: The wrapper should be generic too, but it is not
4373 InterlockedIncrement (&acfg->stats.mcount);
4376 if (method->is_generic || method->klass->generic_container) {
4377 InterlockedIncrement (&acfg->stats.genericcount);
4382 //acfg->aot_opts.print_skipped_methods = TRUE;
4385 * Since these methods are the only ones which are compiled with
4386 * AOT support, and they are not used by runtime startup/shutdown code,
4387 * the runtime will not see AOT methods during AOT compilation,so it
4388 * does not need to support them by creating a fake GOT etc.
4390 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4391 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4392 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4393 InterlockedIncrement (&acfg->stats.genericcount);
4396 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4397 /* Let the exception happen at runtime */
4401 if (cfg->disable_aot) {
4402 if (acfg->aot_opts.print_skipped_methods)
4403 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4404 InterlockedIncrement (&acfg->stats.ocount);
4405 mono_destroy_compile (cfg);
4409 /* Nullify patches which need no aot processing */
4410 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4411 switch (patch_info->type) {
4412 case MONO_PATCH_INFO_LABEL:
4413 case MONO_PATCH_INFO_BB:
4414 patch_info->type = MONO_PATCH_INFO_NONE;
4421 /* Collect method->token associations from the cfg */
4422 mono_acfg_lock (acfg);
4423 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4424 mono_acfg_unlock (acfg);
4427 * Check for absolute addresses.
4430 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4431 switch (patch_info->type) {
4432 case MONO_PATCH_INFO_ABS:
4433 /* unable to handle this */
4442 if (acfg->aot_opts.print_skipped_methods)
4443 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4444 InterlockedIncrement (&acfg->stats.abscount);
4445 mono_destroy_compile (cfg);
4449 /* Lock for the rest of the code */
4450 mono_acfg_lock (acfg);
4453 * Check for methods/klasses we can't encode.
4456 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4457 if (!can_encode_patch (acfg, patch_info))
4462 if (acfg->aot_opts.print_skipped_methods)
4463 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4464 acfg->stats.ocount++;
4465 mono_destroy_compile (cfg);
4466 mono_acfg_unlock (acfg);
4470 /* Adds generic instances referenced by this method */
4472 * The depth is used to avoid infinite loops when generic virtual recursion is
4475 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4477 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4478 switch (patch_info->type) {
4479 case MONO_PATCH_INFO_METHOD: {
4480 MonoMethod *m = patch_info->data.method;
4481 if (m->is_inflated) {
4482 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4483 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4484 !method_has_type_vars (m)) {
4485 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4486 if (acfg->aot_opts.full_aot)
4487 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4489 add_extra_method_with_depth (acfg, m, depth + 1);
4492 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4494 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4495 add_extra_method_with_depth (acfg, m, depth + 1);
4498 case MONO_PATCH_INFO_VTABLE: {
4499 MonoClass *klass = patch_info->data.klass;
4501 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4502 add_generic_class_with_depth (acfg, klass, depth + 5);
4511 /* Determine whenever the method has GOT slots */
4512 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4513 switch (patch_info->type) {
4514 case MONO_PATCH_INFO_GOT_OFFSET:
4515 case MONO_PATCH_INFO_NONE:
4516 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4518 case MONO_PATCH_INFO_IMAGE:
4519 /* The assembly is stored in GOT slot 0 */
4520 if (patch_info->data.image != acfg->image)
4521 cfg->has_got_slots = TRUE;
4524 if (!is_plt_patch (patch_info))
4525 cfg->has_got_slots = TRUE;
4530 if (!cfg->has_got_slots)
4531 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4534 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4536 /* Make a copy of the patch info which is in the mempool */
4538 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4540 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4541 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4544 patches = new_patch_info;
4546 patches_end->next = new_patch_info;
4547 patches_end = new_patch_info;
4549 cfg->patch_info = patches;
4551 /* Make a copy of the unwind info */
4553 GSList *l, *unwind_ops;
4557 for (l = cfg->unwind_ops; l; l = l->next) {
4558 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4559 memcpy (op, l->data, sizeof (MonoUnwindOp));
4560 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4562 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4564 /* Make a copy of the argument/local info */
4566 MonoInst **args, **locals;
4567 MonoMethodSignature *sig;
4568 MonoMethodHeader *header;
4571 sig = mono_method_signature (method);
4572 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4573 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4574 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4575 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4579 header = mono_method_get_header (method);
4580 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4581 for (i = 0; i < header->num_locals; ++i) {
4582 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4583 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4585 cfg->locals = locals;
4588 /* Free some fields used by cfg to conserve memory */
4589 mono_mempool_destroy (cfg->mempool);
4590 cfg->mempool = NULL;
4591 g_free (cfg->varinfo);
4592 cfg->varinfo = NULL;
4596 mono_regstate_free (cfg->rs);
4600 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4602 while (index >= acfg->cfgs_size) {
4603 MonoCompile **new_cfgs;
4606 new_size = acfg->cfgs_size * 2;
4607 new_cfgs = g_new0 (MonoCompile*, new_size);
4608 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4609 g_free (acfg->cfgs);
4610 acfg->cfgs = new_cfgs;
4611 acfg->cfgs_size = new_size;
4613 acfg->cfgs [index] = cfg;
4615 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4618 if (cfg->orig_method->wrapper_type)
4619 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4622 mono_acfg_unlock (acfg);
4624 InterlockedIncrement (&acfg->stats.ccount);
4628 compile_thread_main (gpointer *user_data)
4630 MonoDomain *domain = user_data [0];
4631 MonoAotCompile *acfg = user_data [1];
4632 GPtrArray *methods = user_data [2];
4635 mono_thread_attach (domain);
4637 for (i = 0; i < methods->len; ++i)
4638 compile_method (acfg, g_ptr_array_index (methods, i));
4642 load_profile_files (MonoAotCompile *acfg)
4646 int file_index, res, method_index, i;
4653 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4655 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4660 infile = fopen (tmp, "r");
4663 printf ("Using profile data file '%s'\n", tmp);
4668 res = fscanf (infile, "%32s\n", ver);
4669 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4670 printf ("Profile file has wrong version or invalid.\n");
4677 MonoMethodDesc *desc;
4680 if (fgets (name, 1023, infile) == NULL)
4683 /* Kill the newline */
4684 if (strlen (name) > 0)
4685 name [strlen (name) - 1] = '\0';
4687 desc = mono_method_desc_new (name, TRUE);
4689 method = mono_method_desc_search_in_image (desc, acfg->image);
4691 if (method && mono_method_get_token (method)) {
4692 token = mono_method_get_token (method);
4693 method_index = mono_metadata_token_index (token) - 1;
4695 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4696 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4699 //printf ("No method found matching '%s'.\n", name);
4705 /* Add missing methods */
4707 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4708 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4709 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4711 unordered = g_list_reverse (unordered);
4712 if (acfg->method_order)
4713 g_list_last (acfg->method_order)->next = unordered;
4715 acfg->method_order = unordered;
4718 /* Used by the LLVM backend */
4720 mono_aot_get_got_offset (MonoJumpInfo *ji)
4722 return get_got_offset (llvm_acfg, ji);
4726 mono_aot_get_method_name (MonoCompile *cfg)
4728 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4730 return g_strdup_printf ("m_%x", method_index);
4734 mono_aot_get_method_debug_name (MonoCompile *cfg)
4736 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4740 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4742 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4743 MonoPltEntry *plt_entry;
4746 ji->data.target = data;
4748 if (!can_encode_patch (llvm_acfg, ji))
4751 plt_entry = get_plt_entry (llvm_acfg, ji);
4753 return g_strdup_printf (plt_entry->symbol);
4757 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4761 mono_acfg_lock (llvm_acfg);
4762 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4763 mono_acfg_unlock (llvm_acfg);
4773 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4777 emit_llvm_file (MonoAotCompile *acfg)
4779 char *command, *opts;
4781 MonoJumpInfo *patch_info;
4782 const char *llc_extra_args;
4785 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4789 /* Compute the final size of the got */
4790 for (i = 0; i < acfg->nmethods; ++i) {
4791 if (acfg->cfgs [i]) {
4792 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4793 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4794 if (!is_plt_patch (patch_info))
4795 get_got_offset (acfg, patch_info);
4797 get_plt_entry (acfg, patch_info);
4803 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4805 if (acfg->aot_opts.full_aot) {
4809 * Need to add the got entries used by the trampolines.
4810 * This is only a conservative approximation.
4812 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4813 /* For the generic + rgctx trampolines */
4814 acfg->final_got_size += 200;
4815 /* For the specific trampolines */
4816 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4817 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4822 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4825 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4826 * a lot of time, and doesn't seem to save much space.
4827 * The following optimizations cannot be enabled:
4829 * - 'jump-threading' changes our blockaddress references to int constants.
4830 * The opt list below was produced by taking the output of:
4831 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4832 * then removing tailcallelim + the global opts, and adding a second gvn.
4834 opts = g_strdup ("-instcombine -simplifycfg");
4835 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
4837 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4838 printf ("Executing opt: %s\n", command);
4839 if (system (command) != 0) {
4845 #if !LLVM_CHECK_VERSION(2, 8)
4846 /* LLVM 2.8 removed the -f flag ??? */
4847 llc_extra_args = "-f";
4849 llc_extra_args = "";
4851 command = g_strdup_printf ("llc %s %s -relocation-model=pic -unwind-tables -o %s temp.opt.bc", LLC_TARGET_ARGS, llc_extra_args, acfg->tmpfname);
4853 printf ("Executing llc: %s\n", command);
4855 if (system (command) != 0) {
4862 emit_code (MonoAotCompile *acfg)
4866 char end_symbol [256];
4869 #if defined(TARGET_POWERPC64)
4870 sprintf (symbol, ".Lgot_addr");
4871 emit_section_change (acfg, ".text", 0);
4872 emit_alignment (acfg, 8);
4873 emit_label (acfg, symbol);
4874 emit_pointer (acfg, acfg->got_symbol);
4878 * This global symbol is used to compute the address of each method using the
4879 * code_offsets array. It is also used to compute the memory ranges occupied by
4880 * AOT code, so it must be equal to the address of the first emitted method.
4882 sprintf (symbol, "methods");
4883 emit_section_change (acfg, ".text", 0);
4884 emit_global (acfg, symbol, TRUE);
4885 emit_alignment (acfg, 8);
4887 for (i = 0; i < acfg->nmethods; ++i) {
4888 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
4889 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
4893 if (i == acfg->nmethods)
4894 /* No LLVM compiled methods */
4895 emit_label (acfg, symbol);
4897 emit_label (acfg, symbol);
4901 * Emit some padding so the local symbol for the first method doesn't have the
4902 * same address as 'methods'.
4904 emit_zero_bytes (acfg, 16);
4906 for (l = acfg->method_order; l != NULL; l = l->next) {
4910 i = GPOINTER_TO_UINT (l->data);
4912 cfg = acfg->cfgs [i];
4917 method = cfg->orig_method;
4919 /* Emit unbox trampoline */
4920 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
4921 char call_target [256];
4923 if (!method->wrapper_type && !method->is_inflated) {
4924 g_assert (method->token);
4925 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
4927 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
4930 emit_section_change (acfg, ".text", 0);
4931 #ifdef __native_client_codegen__
4932 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4934 emit_global (acfg, symbol, TRUE);
4935 emit_label (acfg, symbol);
4937 sprintf (call_target, "%s", cfg->asm_symbol);
4939 arch_emit_unbox_trampoline (acfg, cfg->orig_method, call_target);
4942 if (cfg->compile_llvm)
4943 acfg->stats.llvm_count ++;
4945 emit_method_code (acfg, cfg);
4948 sprintf (symbol, "methods_end");
4949 emit_section_change (acfg, ".text", 0);
4950 emit_global (acfg, symbol, FALSE);
4951 emit_alignment (acfg, 8);
4952 emit_label (acfg, symbol);
4954 sprintf (symbol, "code_offsets");
4955 emit_section_change (acfg, RODATA_SECT, 1);
4956 emit_global (acfg, symbol, FALSE);
4957 emit_alignment (acfg, 8);
4958 emit_label (acfg, symbol);
4960 acfg->stats.offsets_size += acfg->nmethods * 4;
4962 sprintf (end_symbol, "methods");
4963 for (i = 0; i < acfg->nmethods; ++i) {
4964 if (acfg->cfgs [i]) {
4965 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
4967 emit_int32 (acfg, 0xffffffff);
4974 emit_info (MonoAotCompile *acfg)
4981 offsets = g_new0 (gint32, acfg->nmethods);
4983 for (l = acfg->method_order; l != NULL; l = l->next) {
4984 i = GPOINTER_TO_UINT (l->data);
4986 if (acfg->cfgs [i]) {
4987 emit_method_info (acfg, acfg->cfgs [i]);
4988 offsets [i] = acfg->cfgs [i]->method_info_offset;
4994 sprintf (symbol, "method_info_offsets");
4995 emit_section_change (acfg, RODATA_SECT, 1);
4996 emit_global (acfg, symbol, FALSE);
4997 emit_alignment (acfg, 8);
4998 emit_label (acfg, symbol);
5000 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5005 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5007 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5008 #define mix(a,b,c) { \
5009 a -= c; a ^= rot(c, 4); c += b; \
5010 b -= a; b ^= rot(a, 6); a += c; \
5011 c -= b; c ^= rot(b, 8); b += a; \
5012 a -= c; a ^= rot(c,16); c += b; \
5013 b -= a; b ^= rot(a,19); a += c; \
5014 c -= b; c ^= rot(b, 4); b += a; \
5016 #define final(a,b,c) { \
5017 c ^= b; c -= rot(b,14); \
5018 a ^= c; a -= rot(c,11); \
5019 b ^= a; b -= rot(a,25); \
5020 c ^= b; c -= rot(b,16); \
5021 a ^= c; a -= rot(c,4); \
5022 b ^= a; b -= rot(a,14); \
5023 c ^= b; c -= rot(b,24); \
5027 mono_aot_type_hash (MonoType *t1)
5029 guint hash = t1->type;
5031 hash |= t1->byref << 6; /* do not collide with t1->type values */
5033 case MONO_TYPE_VALUETYPE:
5034 case MONO_TYPE_CLASS:
5035 case MONO_TYPE_SZARRAY:
5036 /* check if the distribution is good enough */
5037 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5039 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5040 case MONO_TYPE_ARRAY:
5041 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5042 case MONO_TYPE_GENERICINST:
5043 return ((hash << 5) - hash) ^ 0;
5049 * mono_aot_method_hash:
5051 * Return a hash code for methods which only depends on metadata.
5054 mono_aot_method_hash (MonoMethod *method)
5056 MonoMethodSignature *sig;
5060 guint32 *hashes_start, *hashes;
5062 MonoGenericInst *ginst = NULL;
5064 /* Similar to the hash in mono_method_get_imt_slot () */
5066 sig = mono_method_signature (method);
5068 if (method->is_inflated)
5069 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5071 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5072 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5073 hashes = hashes_start;
5075 /* Some wrappers are assigned to random classes */
5076 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5077 klass = method->klass;
5079 klass = mono_defaults.object_class;
5081 if (!method->wrapper_type) {
5082 char *full_name = mono_type_full_name (&klass->byval_arg);
5084 hashes [0] = mono_metadata_str_hash (full_name);
5088 hashes [0] = mono_metadata_str_hash (klass->name);
5089 hashes [1] = mono_metadata_str_hash (klass->name_space);
5091 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5092 /* The method name includes a stringified pointer */
5095 hashes [2] = mono_metadata_str_hash (method->name);
5096 hashes [3] = method->wrapper_type;
5097 hashes [4] = mono_aot_type_hash (sig->ret);
5099 for (i = 0; i < sig->param_count; i++) {
5100 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5103 for (i = 0; i < ginst->type_argc; ++i)
5104 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5106 g_assert (hindex == hashes_count);
5108 /* Setup internal state */
5109 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5111 /* Handle most of the hashes */
5112 while (hashes_count > 3) {
5121 /* Handle the last 3 hashes (all the case statements fall through) */
5122 switch (hashes_count) {
5123 case 3 : c += hashes [2];
5124 case 2 : b += hashes [1];
5125 case 1 : a += hashes [0];
5127 case 0: /* nothing left to add */
5131 free (hashes_start);
5140 * mono_aot_wrapper_name:
5142 * Return a string which uniqely identifies the given wrapper method.
5145 mono_aot_wrapper_name (MonoMethod *method)
5147 char *name, *tmpsig, *klass_desc;
5149 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5151 switch (method->wrapper_type) {
5152 case MONO_WRAPPER_RUNTIME_INVOKE:
5153 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5154 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5156 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5159 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5160 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5161 g_free (klass_desc);
5171 * mono_aot_get_array_helper_from_wrapper;
5173 * Get the helper method in Array called by an array wrapper method.
5176 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5180 MonoGenericContext ctx;
5181 MonoType *args [16];
5182 char *mname, *iname, *s, *s2, *helper_name = NULL;
5184 prefix = "System.Collections.Generic";
5185 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5186 s2 = strstr (s, "`1.");
5192 //printf ("X: %s %s\n", iname, mname);
5194 if (!strcmp (iname, "IList"))
5195 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5197 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5198 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5200 g_free (helper_name);
5203 if (m->is_generic) {
5204 memset (&ctx, 0, sizeof (ctx));
5205 args [0] = &method->klass->element_class->byval_arg;
5206 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5207 m = mono_class_inflate_generic_method (m, &ctx);
5213 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5215 typedef struct HashEntry {
5216 guint32 key, value, index;
5217 struct HashEntry *next;
5221 * emit_extra_methods:
5223 * Emit methods which are not in the METHOD table, like wrappers.
5226 emit_extra_methods (MonoAotCompile *acfg)
5228 int i, table_size, buf_size;
5231 guint32 *info_offsets;
5234 HashEntry *entry, *new_entry;
5235 int nmethods, max_chain_length;
5238 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5240 /* Emit method info */
5242 for (i = 0; i < acfg->extra_methods->len; ++i) {
5243 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5244 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5251 p = buf = g_malloc (buf_size);
5255 method = cfg->method_to_register;
5258 if (method->wrapper_type) {
5260 * We encode some wrappers using their name, since encoding them
5261 * directly would be difficult. This also avoids creating the wrapper
5262 * methods at runtime, since they are not needed anyway.
5264 switch (method->wrapper_type) {
5265 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5266 case MONO_WRAPPER_SYNCHRONIZED:
5267 /* encode_method_ref () can handle these */
5269 case MONO_WRAPPER_RUNTIME_INVOKE:
5270 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5271 /* Direct wrapper, encode normally */
5275 name = mono_aot_wrapper_name (method);
5281 encode_value (1, p, &p);
5282 encode_value (method->wrapper_type, p, &p);
5283 strcpy ((char*)p, name);
5284 p += strlen (name ) + 1;
5287 encode_value (0, p, &p);
5288 encode_method_ref (acfg, method, p, &p);
5291 g_assert ((p - buf) < buf_size);
5293 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5298 * Construct a chained hash table for mapping indexes in extra_method_info to
5301 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5302 table = g_ptr_array_sized_new (table_size);
5303 for (i = 0; i < table_size; ++i)
5304 g_ptr_array_add (table, NULL);
5305 chain_lengths = g_new0 (int, table_size);
5306 max_chain_length = 0;
5307 for (i = 0; i < acfg->extra_methods->len; ++i) {
5308 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5309 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5315 key = info_offsets [i];
5316 value = get_method_index (acfg, method);
5318 hash = mono_aot_method_hash (method) % table_size;
5320 chain_lengths [hash] ++;
5321 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5323 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5324 new_entry->key = key;
5325 new_entry->value = value;
5327 entry = g_ptr_array_index (table, hash);
5328 if (entry == NULL) {
5329 new_entry->index = hash;
5330 g_ptr_array_index (table, hash) = new_entry;
5333 entry = entry->next;
5335 entry->next = new_entry;
5336 new_entry->index = table->len;
5337 g_ptr_array_add (table, new_entry);
5341 //printf ("MAX: %d\n", max_chain_length);
5343 /* Emit the table */
5344 sprintf (symbol, "extra_method_table");
5345 emit_section_change (acfg, RODATA_SECT, 0);
5346 emit_global (acfg, symbol, FALSE);
5347 emit_alignment (acfg, 8);
5348 emit_label (acfg, symbol);
5350 emit_int32 (acfg, table_size);
5351 for (i = 0; i < table->len; ++i) {
5352 HashEntry *entry = g_ptr_array_index (table, i);
5354 if (entry == NULL) {
5355 emit_int32 (acfg, 0);
5356 emit_int32 (acfg, 0);
5357 emit_int32 (acfg, 0);
5359 //g_assert (entry->key > 0);
5360 emit_int32 (acfg, entry->key);
5361 emit_int32 (acfg, entry->value);
5363 emit_int32 (acfg, entry->next->index);
5365 emit_int32 (acfg, 0);
5370 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5371 * This is used by mono_aot_find_jit_info ().
5373 sprintf (symbol, "extra_method_info_offsets");
5374 emit_section_change (acfg, RODATA_SECT, 0);
5375 emit_global (acfg, symbol, FALSE);
5376 emit_alignment (acfg, 8);
5377 emit_label (acfg, symbol);
5379 emit_int32 (acfg, acfg->extra_methods->len);
5380 for (i = 0; i < acfg->extra_methods->len; ++i) {
5381 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5383 emit_int32 (acfg, get_method_index (acfg, method));
5384 emit_int32 (acfg, info_offsets [i]);
5389 emit_exception_info (MonoAotCompile *acfg)
5395 offsets = g_new0 (gint32, acfg->nmethods);
5396 for (i = 0; i < acfg->nmethods; ++i) {
5397 if (acfg->cfgs [i]) {
5398 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5399 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5405 sprintf (symbol, "ex_info_offsets");
5406 emit_section_change (acfg, RODATA_SECT, 1);
5407 emit_global (acfg, symbol, FALSE);
5408 emit_alignment (acfg, 8);
5409 emit_label (acfg, symbol);
5411 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5416 emit_unwind_info (MonoAotCompile *acfg)
5422 * The unwind info contains a lot of duplicates so we emit each unique
5423 * entry once, and only store the offset from the start of the table in the
5427 sprintf (symbol, "unwind_info");
5428 emit_section_change (acfg, RODATA_SECT, 1);
5429 emit_alignment (acfg, 8);
5430 emit_label (acfg, symbol);
5431 emit_global (acfg, symbol, FALSE);
5433 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5434 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5435 guint8 *unwind_info;
5436 guint32 unwind_info_len;
5440 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5443 encode_value (unwind_info_len, p, &p);
5444 emit_bytes (acfg, buf, p - buf);
5445 emit_bytes (acfg, unwind_info, unwind_info_len);
5447 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5452 emit_class_info (MonoAotCompile *acfg)
5458 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5459 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5460 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5462 sprintf (symbol, "class_info_offsets");
5463 emit_section_change (acfg, RODATA_SECT, 1);
5464 emit_global (acfg, symbol, FALSE);
5465 emit_alignment (acfg, 8);
5466 emit_label (acfg, symbol);
5468 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5472 typedef struct ClassNameTableEntry {
5473 guint32 token, index;
5474 struct ClassNameTableEntry *next;
5475 } ClassNameTableEntry;
5478 emit_class_name_table (MonoAotCompile *acfg)
5481 guint32 token, hash;
5486 ClassNameTableEntry *entry, *new_entry;
5489 * Construct a chained hash table for mapping class names to typedef tokens.
5491 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5492 table = g_ptr_array_sized_new (table_size);
5493 for (i = 0; i < table_size; ++i)
5494 g_ptr_array_add (table, NULL);
5495 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5496 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5497 klass = mono_class_get (acfg->image, token);
5500 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5501 hash = mono_metadata_str_hash (full_name) % table_size;
5504 /* FIXME: Allocate from the mempool */
5505 new_entry = g_new0 (ClassNameTableEntry, 1);
5506 new_entry->token = token;
5508 entry = g_ptr_array_index (table, hash);
5509 if (entry == NULL) {
5510 new_entry->index = hash;
5511 g_ptr_array_index (table, hash) = new_entry;
5514 entry = entry->next;
5516 entry->next = new_entry;
5517 new_entry->index = table->len;
5518 g_ptr_array_add (table, new_entry);
5522 /* Emit the table */
5523 sprintf (symbol, "class_name_table");
5524 emit_section_change (acfg, RODATA_SECT, 0);
5525 emit_global (acfg, symbol, FALSE);
5526 emit_alignment (acfg, 8);
5527 emit_label (acfg, symbol);
5529 /* FIXME: Optimize memory usage */
5530 g_assert (table_size < 65000);
5531 emit_int16 (acfg, table_size);
5532 g_assert (table->len < 65000);
5533 for (i = 0; i < table->len; ++i) {
5534 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5536 if (entry == NULL) {
5537 emit_int16 (acfg, 0);
5538 emit_int16 (acfg, 0);
5540 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5542 emit_int16 (acfg, entry->next->index);
5544 emit_int16 (acfg, 0);
5550 emit_image_table (MonoAotCompile *acfg)
5556 * The image table is small but referenced in a lot of places.
5557 * So we emit it at once, and reference its elements by an index.
5560 sprintf (symbol, "mono_image_table");
5561 emit_section_change (acfg, RODATA_SECT, 1);
5562 emit_global (acfg, symbol, FALSE);
5563 emit_alignment (acfg, 8);
5564 emit_label (acfg, symbol);
5566 emit_int32 (acfg, acfg->image_table->len);
5567 for (i = 0; i < acfg->image_table->len; i++) {
5568 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5569 MonoAssemblyName *aname = &image->assembly->aname;
5571 /* FIXME: Support multi-module assemblies */
5572 g_assert (image->assembly->image == image);
5574 emit_string (acfg, image->assembly_name);
5575 emit_string (acfg, image->guid);
5576 emit_string (acfg, aname->culture ? aname->culture : "");
5577 emit_string (acfg, (const char*)aname->public_key_token);
5579 emit_alignment (acfg, 8);
5580 emit_int32 (acfg, aname->flags);
5581 emit_int32 (acfg, aname->major);
5582 emit_int32 (acfg, aname->minor);
5583 emit_int32 (acfg, aname->build);
5584 emit_int32 (acfg, aname->revision);
5589 emit_got_info (MonoAotCompile *acfg)
5592 int i, first_plt_got_patch, buf_size;
5594 guint32 *got_info_offsets;
5596 /* Add the patches needed by the PLT to the GOT */
5597 acfg->plt_got_offset_base = acfg->got_offset;
5598 first_plt_got_patch = acfg->got_patches->len;
5599 for (i = 1; i < acfg->plt_offset; ++i) {
5600 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5602 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5605 acfg->got_offset += acfg->plt_offset;
5609 * - optimize offsets table.
5610 * - reduce number of exported symbols.
5611 * - emit info for a klass only once.
5612 * - determine when a method uses a GOT slot which is guaranteed to be already
5614 * - clean up and document the code.
5615 * - use String.Empty in class libs.
5618 /* Encode info required to decode shared GOT entries */
5619 buf_size = acfg->got_patches->len * 128;
5620 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5621 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5622 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5624 if (acfg->plt_offset)
5625 acfg->plt_got_info_offsets [0] = 0;
5626 for (i = 0; i < acfg->got_patches->len; ++i) {
5627 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5631 encode_value (ji->type, p, &p);
5632 encode_patch (acfg, ji, p, &p);
5634 g_assert (p - buf <= buf_size);
5635 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5637 if (i >= first_plt_got_patch)
5638 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5639 acfg->stats.got_info_size += p - buf;
5642 /* Emit got_info_offsets table */
5643 sprintf (symbol, "got_info_offsets");
5644 emit_section_change (acfg, RODATA_SECT, 1);
5645 emit_global (acfg, symbol, FALSE);
5646 emit_alignment (acfg, 8);
5647 emit_label (acfg, symbol);
5649 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5650 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5654 emit_got (MonoAotCompile *acfg)
5659 /* Don't make GOT global so accesses to it don't need relocations */
5660 sprintf (symbol, "%s", acfg->got_symbol);
5661 emit_section_change (acfg, ".bss", 0);
5662 emit_alignment (acfg, 8);
5663 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5664 emit_label (acfg, symbol);
5665 if (acfg->got_offset > 0)
5666 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5668 sprintf (symbol, "got_end");
5669 emit_label (acfg, symbol);
5672 sprintf (symbol, "mono_aot_got_addr");
5673 emit_section_change (acfg, ".data", 0);
5674 emit_global (acfg, symbol, FALSE);
5675 emit_alignment (acfg, 8);
5676 emit_label (acfg, symbol);
5677 emit_pointer (acfg, acfg->got_symbol);
5680 typedef struct GlobalsTableEntry {
5681 guint32 value, index;
5682 struct GlobalsTableEntry *next;
5683 } GlobalsTableEntry;
5686 emit_globals_table (MonoAotCompile *acfg)
5692 GlobalsTableEntry *entry, *new_entry;
5695 * Construct a chained hash table for mapping global names to their index in
5696 * the globals table.
5698 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5699 table = g_ptr_array_sized_new (table_size);
5700 for (i = 0; i < table_size; ++i)
5701 g_ptr_array_add (table, NULL);
5702 for (i = 0; i < acfg->globals->len; ++i) {
5703 char *name = g_ptr_array_index (acfg->globals, i);
5705 hash = mono_metadata_str_hash (name) % table_size;
5707 /* FIXME: Allocate from the mempool */
5708 new_entry = g_new0 (GlobalsTableEntry, 1);
5709 new_entry->value = i;
5711 entry = g_ptr_array_index (table, hash);
5712 if (entry == NULL) {
5713 new_entry->index = hash;
5714 g_ptr_array_index (table, hash) = new_entry;
5717 entry = entry->next;
5719 entry->next = new_entry;
5720 new_entry->index = table->len;
5721 g_ptr_array_add (table, new_entry);
5725 /* Emit the table */
5726 sprintf (symbol, ".Lglobals_hash");
5727 emit_section_change (acfg, RODATA_SECT, 0);
5728 emit_alignment (acfg, 8);
5729 emit_label (acfg, symbol);
5731 /* FIXME: Optimize memory usage */
5732 g_assert (table_size < 65000);
5733 emit_int16 (acfg, table_size);
5734 for (i = 0; i < table->len; ++i) {
5735 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5737 if (entry == NULL) {
5738 emit_int16 (acfg, 0);
5739 emit_int16 (acfg, 0);
5741 emit_int16 (acfg, entry->value + 1);
5743 emit_int16 (acfg, entry->next->index);
5745 emit_int16 (acfg, 0);
5749 /* Emit the names */
5750 for (i = 0; i < acfg->globals->len; ++i) {
5751 char *name = g_ptr_array_index (acfg->globals, i);
5753 sprintf (symbol, "name_%d", i);
5754 emit_section_change (acfg, RODATA_SECT, 1);
5755 emit_label (acfg, symbol);
5756 emit_string (acfg, name);
5759 /* Emit the globals table */
5760 sprintf (symbol, ".Lglobals");
5761 emit_section_change (acfg, ".data", 0);
5762 /* This is not a global, since it is accessed by the init function */
5763 emit_alignment (acfg, 8);
5764 emit_label (acfg, symbol);
5766 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5767 emit_pointer (acfg, symbol);
5769 for (i = 0; i < acfg->globals->len; ++i) {
5770 char *name = g_ptr_array_index (acfg->globals, i);
5772 sprintf (symbol, "name_%d", i);
5773 emit_pointer (acfg, symbol);
5775 sprintf (symbol, "%s", name);
5776 emit_pointer (acfg, symbol);
5778 /* Null terminate the table */
5779 emit_int32 (acfg, 0);
5780 emit_int32 (acfg, 0);
5784 emit_globals (MonoAotCompile *acfg)
5788 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5790 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5792 if (acfg->aot_opts.bind_to_runtime_version) {
5793 build_info = mono_get_runtime_build_info ();
5794 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5795 g_free (build_info);
5797 emit_string_symbol (acfg, "mono_runtime_version", "");
5801 * When static linking, we emit a global which will point to the symbol table.
5803 if (acfg->aot_opts.static_link) {
5807 /* Emit a string holding the assembly name */
5808 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5810 emit_globals_table (acfg);
5813 * Emit a global symbol which can be passed by an embedding app to
5814 * mono_aot_register_module ().
5816 #if defined(__MACH__) && !defined(__native_client_codegen__)
5817 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5819 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5822 /* Get rid of characters which cannot occur in symbols */
5824 for (p = symbol; *p; ++p) {
5825 if (!(isalnum (*p) || *p == '_'))
5828 acfg->static_linking_symbol = g_strdup (symbol);
5829 emit_global_inner (acfg, symbol, FALSE);
5830 emit_alignment (acfg, 8);
5831 emit_label (acfg, symbol);
5832 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5833 emit_pointer (acfg, symbol);
5838 emit_autoreg (MonoAotCompile *acfg)
5843 * Emit a function into the .ctor section which will be called by the ELF
5844 * loader to register this module with the runtime.
5846 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5849 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5851 arch_emit_autoreg (acfg, symbol);
5857 emit_mem_end (MonoAotCompile *acfg)
5861 sprintf (symbol, "mem_end");
5862 emit_section_change (acfg, ".text", 1);
5863 emit_global (acfg, symbol, FALSE);
5864 emit_alignment (acfg, 8);
5865 emit_label (acfg, symbol);
5869 * Emit a structure containing all the information not stored elsewhere.
5872 emit_file_info (MonoAotCompile *acfg)
5877 const char *gc_name;
5880 * The managed allocators are GC specific, so can't use an AOT image created by one GC
5883 gc_name = mono_gc_get_gc_name ();
5884 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
5886 sprintf (symbol, "mono_aot_file_info");
5887 emit_section_change (acfg, ".data", 0);
5888 emit_alignment (acfg, 8);
5889 emit_label (acfg, symbol);
5890 emit_global (acfg, symbol, FALSE);
5892 /* The data emitted here must match MonoAotFileInfo. */
5893 emit_int32 (acfg, acfg->plt_got_offset_base);
5894 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5895 emit_int32 (acfg, acfg->plt_offset);
5896 emit_int32 (acfg, acfg->nmethods);
5897 emit_int32 (acfg, acfg->flags);
5898 emit_int32 (acfg, acfg->opts);
5899 emit_int32 (acfg, gc_name_offset);
5901 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5902 emit_int32 (acfg, acfg->num_trampolines [i]);
5903 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5904 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5905 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5906 emit_int32 (acfg, acfg->trampoline_size [i]);
5910 emit_blob (MonoAotCompile *acfg)
5914 sprintf (symbol, "blob");
5915 emit_section_change (acfg, RODATA_SECT, 1);
5916 emit_global (acfg, symbol, FALSE);
5917 emit_alignment (acfg, 8);
5918 emit_label (acfg, symbol);
5920 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5924 emit_dwarf_info (MonoAotCompile *acfg)
5926 #ifdef EMIT_DWARF_INFO
5928 char symbol [128], symbol2 [128];
5930 /* DIEs for methods */
5931 for (i = 0; i < acfg->nmethods; ++i) {
5932 MonoCompile *cfg = acfg->cfgs [i];
5937 // FIXME: LLVM doesn't define .Lme_...
5938 if (cfg->compile_llvm)
5941 sprintf (symbol, "%s", cfg->asm_symbol);
5942 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5944 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
5950 collect_methods (MonoAotCompile *acfg)
5953 MonoImage *image = acfg->image;
5955 /* Collect methods */
5956 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5958 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5960 method = mono_get_method (acfg->image, token, NULL);
5963 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5967 /* Load all methods eagerly to skip the slower lazy loading code */
5968 mono_class_setup_methods (method->klass);
5970 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5971 /* Compile the wrapper instead */
5972 /* We do this here instead of add_wrappers () because it is easy to do it here */
5973 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5977 /* FIXME: Some mscorlib methods don't have debug info */
5979 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5980 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5981 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5982 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5983 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5984 if (!mono_debug_lookup_method (method)) {
5985 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5992 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5993 add_method_with_index (acfg, method, i, FALSE);
5994 acfg->method_index ++;
5997 add_generic_instances (acfg);
5999 if (acfg->aot_opts.full_aot)
6000 add_wrappers (acfg);
6004 compile_methods (MonoAotCompile *acfg)
6008 if (acfg->aot_opts.nthreads > 0) {
6013 gpointer *user_data;
6014 MonoMethod **methods;
6016 methods_len = acfg->methods->len;
6018 len = acfg->methods->len / acfg->aot_opts.nthreads;
6021 * Partition the list of methods into fragments, and hand it to threads to
6024 threads = g_ptr_array_new ();
6025 /* Make a copy since acfg->methods is modified by compile_method () */
6026 methods = g_new0 (MonoMethod*, methods_len);
6027 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6028 for (i = 0; i < methods_len; ++i)
6029 methods [i] = g_ptr_array_index (acfg->methods, i);
6031 while (i < methods_len) {
6032 frag = g_ptr_array_new ();
6033 for (j = 0; j < len; ++j) {
6034 if (i < methods_len) {
6035 g_ptr_array_add (frag, methods [i]);
6040 user_data = g_new0 (gpointer, 3);
6041 user_data [0] = mono_domain_get ();
6042 user_data [1] = acfg;
6043 user_data [2] = frag;
6045 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6046 g_ptr_array_add (threads, handle);
6050 for (i = 0; i < threads->len; ++i) {
6051 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6057 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6058 for (i = methods_len; i < acfg->methods->len; ++i) {
6059 /* This can new methods to acfg->methods */
6060 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6065 compile_asm (MonoAotCompile *acfg)
6067 char *command, *objfile;
6068 char *outfile_name, *tmp_outfile_name;
6069 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6071 #if defined(TARGET_AMD64)
6072 #define AS_OPTIONS "--64"
6073 #elif defined(TARGET_POWERPC64)
6074 #define AS_OPTIONS "-a64 -mppc64"
6075 #define LD_OPTIONS "-m elf64ppc"
6076 #elif defined(sparc) && SIZEOF_VOID_P == 8
6077 #define AS_OPTIONS "-xarch=v9"
6078 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6079 #define AS_OPTIONS "-arch i386 -W"
6081 #define AS_OPTIONS ""
6084 #ifdef __native_client_codegen__
6085 #define AS_NAME "nacl-as"
6087 #define AS_NAME "as"
6091 #define LD_OPTIONS ""
6095 #define EH_LD_OPTIONS "--eh-frame-hdr"
6097 #define EH_LD_OPTIONS ""
6100 if (acfg->aot_opts.asm_only) {
6101 printf ("Output file: '%s'.\n", acfg->tmpfname);
6102 if (acfg->aot_opts.static_link)
6103 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6107 if (acfg->aot_opts.static_link) {
6108 if (acfg->aot_opts.outfile)
6109 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6111 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6113 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6115 command = g_strdup_printf ("%s%s %s %s -o %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->tmpfname, objfile);
6116 printf ("Executing the native assembler: %s\n", command);
6117 if (system (command) != 0) {
6125 if (acfg->aot_opts.static_link) {
6126 printf ("Output file: '%s'.\n", objfile);
6127 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6132 if (acfg->aot_opts.outfile)
6133 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6135 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6137 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6140 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6141 #elif defined(__ppc__) && defined(__MACH__)
6142 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6143 #elif defined(HOST_WIN32)
6144 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6145 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6146 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6148 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6150 printf ("Executing the native linker: %s\n", command);
6151 if (system (command) != 0) {
6152 g_free (tmp_outfile_name);
6153 g_free (outfile_name);
6161 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6162 printf ("Stripping the binary: %s\n", com);
6166 #if defined(TARGET_ARM) && !defined(__MACH__)
6168 * gas generates 'mapping symbols' each time code and data is mixed, which
6169 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6171 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6172 printf ("Stripping the binary: %s\n", command);
6173 if (system (command) != 0) {
6174 g_free (tmp_outfile_name);
6175 g_free (outfile_name);
6182 rename (tmp_outfile_name, outfile_name);
6184 g_free (tmp_outfile_name);
6185 g_free (outfile_name);
6188 if (acfg->aot_opts.save_temps)
6189 printf ("Retained input file.\n");
6191 unlink (acfg->tmpfname);
6196 static MonoAotCompile*
6197 acfg_create (MonoAssembly *ass, guint32 opts)
6199 MonoImage *image = ass->image;
6200 MonoAotCompile *acfg;
6203 acfg = g_new0 (MonoAotCompile, 1);
6204 acfg->methods = g_ptr_array_new ();
6205 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6206 acfg->method_depth = g_hash_table_new (NULL, NULL);
6207 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6208 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6209 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6210 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6211 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6212 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6213 acfg->got_patches = g_ptr_array_new ();
6214 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6215 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6216 acfg->image_hash = g_hash_table_new (NULL, NULL);
6217 acfg->image_table = g_ptr_array_new ();
6218 acfg->globals = g_ptr_array_new ();
6219 acfg->image = image;
6221 acfg->mempool = mono_mempool_new ();
6222 acfg->extra_methods = g_ptr_array_new ();
6223 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6224 acfg->unwind_ops = g_ptr_array_new ();
6225 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6226 InitializeCriticalSection (&acfg->mutex);
6232 acfg_free (MonoAotCompile *acfg)
6236 img_writer_destroy (acfg->w);
6237 for (i = 0; i < acfg->nmethods; ++i)
6239 g_free (acfg->cfgs [i]);
6240 g_free (acfg->cfgs);
6241 g_free (acfg->static_linking_symbol);
6242 g_free (acfg->got_symbol);
6243 g_free (acfg->plt_symbol);
6244 g_ptr_array_free (acfg->methods, TRUE);
6245 g_ptr_array_free (acfg->got_patches, TRUE);
6246 g_ptr_array_free (acfg->image_table, TRUE);
6247 g_ptr_array_free (acfg->globals, TRUE);
6248 g_ptr_array_free (acfg->unwind_ops, TRUE);
6249 g_hash_table_destroy (acfg->method_indexes);
6250 g_hash_table_destroy (acfg->method_depth);
6251 g_hash_table_destroy (acfg->plt_offset_to_entry);
6252 g_hash_table_destroy (acfg->patch_to_plt_entry);
6253 g_hash_table_destroy (acfg->patch_to_got_offset);
6254 g_hash_table_destroy (acfg->method_to_cfg);
6255 g_hash_table_destroy (acfg->token_info_hash);
6256 g_hash_table_destroy (acfg->image_hash);
6257 g_hash_table_destroy (acfg->unwind_info_offsets);
6258 g_hash_table_destroy (acfg->method_label_hash);
6259 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6260 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6261 g_free (acfg->patch_to_got_offset_by_type);
6262 mono_mempool_destroy (acfg->mempool);
6267 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6269 MonoImage *image = ass->image;
6271 MonoAotCompile *acfg;
6272 char *outfile_name, *tmp_outfile_name, *p;
6276 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6278 acfg = acfg_create (ass, opts);
6280 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6281 acfg->aot_opts.write_symbols = TRUE;
6282 acfg->aot_opts.ntrampolines = 1024;
6283 acfg->aot_opts.nrgctx_trampolines = 1024;
6284 acfg->aot_opts.nimt_trampolines = 128;
6286 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6288 if (acfg->aot_opts.static_link)
6289 acfg->aot_opts.autoreg = TRUE;
6291 //acfg->aot_opts.print_skipped_methods = TRUE;
6293 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6294 if (acfg->aot_opts.full_aot) {
6295 printf ("--aot=full is not supported on this platform.\n");
6300 if (acfg->aot_opts.static_link)
6301 acfg->aot_opts.asm_writer = TRUE;
6303 if (acfg->aot_opts.soft_debug) {
6304 MonoDebugOptions *opt = mini_get_debug_options ();
6306 opt->mdb_optimizations = TRUE;
6307 opt->gen_seq_points = TRUE;
6309 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6310 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6315 if (mono_use_llvm) {
6317 acfg->aot_opts.asm_writer = TRUE;
6318 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6321 if (acfg->aot_opts.full_aot)
6322 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6324 load_profile_files (acfg);
6326 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6327 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6328 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6330 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6332 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
6333 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
6335 /* Get rid of characters which cannot occur in symbols */
6336 for (p = acfg->got_symbol_base; *p; ++p) {
6337 if (!(isalnum (*p) || *p == '_'))
6340 for (p = acfg->plt_symbol; *p; ++p) {
6341 if (!(isalnum (*p) || *p == '_'))
6345 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6348 * The prefix LLVM likes to put in front of symbol names on darwin.
6349 * The mach-os specs require this for globals, but LLVM puts them in front of all
6350 * symbols. We need to handle this, since we need to refer to LLVM generated
6353 acfg->llvm_label_prefix = "";
6355 acfg->llvm_label_prefix = LLVM_LABEL_PREFIX;
6357 acfg->method_index = 1;
6359 collect_methods (acfg);
6361 acfg->cfgs_size = acfg->methods->len + 32;
6362 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6364 /* PLT offset 0 is reserved for the PLT trampoline */
6365 acfg->plt_offset = 1;
6370 mono_llvm_create_aot_module (acfg->got_symbol_base);
6374 /* GOT offset 0 is reserved for the address of the current assembly */
6378 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6379 ji->type = MONO_PATCH_INFO_IMAGE;
6380 ji->data.image = acfg->image;
6382 get_got_offset (acfg, ji);
6384 /* Slot 1 is reserved for the mscorlib got addr */
6385 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6386 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6387 get_got_offset (acfg, ji);
6389 /* This is very common */
6390 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6391 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6392 get_got_offset (acfg, ji);
6397 compile_methods (acfg);
6401 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6407 if (acfg->aot_opts.asm_only) {
6408 if (acfg->aot_opts.outfile)
6409 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6411 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6413 acfg->tmpfname = g_strdup ("temp.s");
6416 emit_llvm_file (acfg);
6420 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6421 if (acfg->aot_opts.outfile)
6422 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6424 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6427 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6428 * it might be in another file system so the rename () won't work.
6430 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6432 acfg->fp = fopen (tmp_outfile_name, "w");
6434 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6438 acfg->w = img_writer_create (acfg->fp, TRUE);
6439 acfg->use_bin_writer = TRUE;
6442 /* Append to the .s file created by llvm */
6443 /* FIXME: Use multiple files instead */
6444 acfg->fp = fopen (acfg->tmpfname, "a+");
6446 if (acfg->aot_opts.asm_only) {
6447 if (acfg->aot_opts.outfile)
6448 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6450 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6451 acfg->fp = fopen (acfg->tmpfname, "w+");
6453 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6454 acfg->fp = fdopen (i, "w+");
6456 g_assert (acfg->fp);
6458 acfg->w = img_writer_create (acfg->fp, FALSE);
6460 tmp_outfile_name = NULL;
6461 outfile_name = NULL;
6464 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6466 /* Compute symbols for methods */
6467 for (i = 0; i < acfg->nmethods; ++i) {
6468 if (acfg->cfgs [i]) {
6469 MonoCompile *cfg = acfg->cfgs [i];
6470 int method_index = get_method_index (acfg, cfg->orig_method);
6472 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, LLVM_LABEL_PREFIX, method_index);
6476 if (!acfg->aot_opts.nodebug)
6477 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6479 img_writer_emit_start (acfg->w);
6482 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6488 emit_extra_methods (acfg);
6490 emit_trampolines (acfg);
6492 emit_class_name_table (acfg);
6494 emit_got_info (acfg);
6496 emit_exception_info (acfg);
6498 emit_unwind_info (acfg);
6500 emit_class_info (acfg);
6504 emit_image_table (acfg);
6508 emit_file_info (acfg);
6512 emit_globals (acfg);
6514 emit_autoreg (acfg);
6517 emit_dwarf_info (acfg);
6518 mono_dwarf_writer_close (acfg->dwarf);
6521 emit_mem_end (acfg);
6525 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6528 g_assert (acfg->got_offset <= acfg->final_got_size);
6530 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
6533 res = img_writer_emit_writeout (acfg->w);
6538 if (acfg->use_bin_writer) {
6539 int err = rename (tmp_outfile_name, outfile_name);
6542 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6546 res = compile_asm (acfg);
6553 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6555 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);
6556 if (acfg->stats.genericcount)
6557 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6558 if (acfg->stats.abscount)
6559 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6560 if (acfg->stats.lmfcount)
6561 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6562 if (acfg->stats.ocount)
6563 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6565 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6566 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);
6567 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6569 if (acfg->aot_opts.stats) {
6572 printf ("GOT slot distribution:\n");
6573 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6574 if (acfg->stats.got_slot_types [i])
6575 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6578 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);
6590 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)