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.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
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"
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72 #if defined(__linux__) || defined(__native_client_codegen__)
73 #define RODATA_SECT ".rodata"
75 #define RODATA_SECT ".text"
78 #define TV_DECLARE(name) gint64 name
79 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
80 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
83 #define SHARED_EXT ".dll"
84 #elif defined(__ppc__) && defined(TARGET_MACH)
85 #define SHARED_EXT ".dylib"
86 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
87 #define SHARED_EXT ".dylib"
89 #define SHARED_EXT ".so"
92 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
93 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
94 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
96 /* predefined values for static readonly fields without needed to run the .cctor */
97 typedef struct _ReadOnlyValue ReadOnlyValue;
98 struct _ReadOnlyValue {
101 int type; /* to be used later for typechecking to prevent user errors */
110 static ReadOnlyValue *readonly_values = NULL;
112 typedef struct MonoAotOptions {
115 gboolean write_symbols;
116 gboolean metadata_only;
117 gboolean bind_to_runtime_version;
120 gboolean static_link;
125 gboolean log_generics;
126 gboolean direct_pinvoke;
127 gboolean direct_icalls;
128 gboolean no_direct_calls;
129 gboolean use_trampolines_page;
132 int nrgctx_trampolines;
133 int nimt_trampolines;
134 int ngsharedvt_arg_trampolines;
135 gboolean print_skipped_methods;
143 typedef struct MonoAotStats {
144 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
145 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
146 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
147 int got_slots, offsets_size;
148 int got_slot_types [MONO_PATCH_INFO_NONE];
149 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
150 int jit_time, gen_time, link_time;
153 typedef struct MonoAotCompile {
156 GHashTable *method_indexes;
157 GHashTable *method_depth;
160 GHashTable *patch_to_plt_entry;
161 GHashTable *plt_offset_to_entry;
162 GHashTable *patch_to_got_offset;
163 GHashTable **patch_to_got_offset_by_type;
164 GPtrArray *got_patches;
165 GHashTable *image_hash;
166 GHashTable *method_to_cfg;
167 GHashTable *token_info_hash;
168 GHashTable *method_to_pinvoke_import;
169 GPtrArray *extra_methods;
170 GPtrArray *image_table;
172 GPtrArray *method_order;
173 GHashTable *export_names;
174 /* Maps MonoClass* -> blob offset */
175 GHashTable *klass_blob_hash;
176 /* Maps MonoMethod* -> blob offset */
177 GHashTable *method_blob_hash;
178 guint32 *plt_got_info_offsets;
179 guint32 got_offset, plt_offset, plt_got_offset_base;
180 guint32 final_got_size;
181 /* Number of GOT entries reserved for trampolines */
182 guint32 num_trampoline_got_entries;
184 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
185 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
186 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
188 MonoAotOptions aot_opts;
192 MonoMemPool *mempool;
195 char *static_linking_symbol;
196 CRITICAL_SECTION mutex;
197 gboolean use_bin_writer;
199 MonoDwarfWriter *dwarf;
203 GHashTable *unwind_info_offsets;
204 GPtrArray *unwind_ops;
205 guint32 unwind_info_offset;
206 char *got_symbol_base;
209 GHashTable *method_label_hash;
210 const char *temp_prefix;
211 const char *llvm_label_prefix;
212 guint32 label_generator;
214 MonoAotFileFlags flags;
215 MonoDynamicStream blob;
216 MonoClass **typespec_classes;
219 char *assembly_name_sym;
220 GHashTable *plt_entry_debug_sym_cache;
221 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
222 GHashTable *ginst_hash;
223 gboolean global_symbols;
225 gboolean direct_method_addresses;
231 char *symbol, *llvm_symbol, *debug_sym;
233 gboolean jit_used, llvm_used;
236 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
237 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
239 /* This points to the current acfg in LLVM mode */
240 static MonoAotCompile *llvm_acfg;
242 #ifdef HAVE_ARRAY_ELEM_INIT
243 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
244 #define MSGSTRFIELD1(line) str##line
245 static const struct msgstr_t {
246 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
247 #include "patch-info.h"
250 #define PATCH_INFO(a,b) b,
251 #include "patch-info.h"
254 static const gint16 opidx [] = {
255 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
256 #include "patch-info.h"
260 static G_GNUC_UNUSED const char*
261 get_patch_name (int info)
263 return (const char*)&opstr + opidx [info];
267 #define PATCH_INFO(a,b) b,
268 static const char* const
269 patch_types [MONO_PATCH_INFO_NUM + 1] = {
270 #include "patch-info.h"
274 static G_GNUC_UNUSED const char*
275 get_patch_name (int info)
277 return patch_types [info];
283 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
285 /* Wrappers around the image writer functions */
288 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
290 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
294 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
296 img_writer_emit_push_section (acfg->w, section_name, subsection);
300 emit_pop_section (MonoAotCompile *acfg)
302 img_writer_emit_pop_section (acfg->w);
306 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
308 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
312 emit_label (MonoAotCompile *acfg, const char *name)
314 img_writer_emit_label (acfg->w, name);
318 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
320 img_writer_emit_bytes (acfg->w, buf, size);
324 emit_string (MonoAotCompile *acfg, const char *value)
326 img_writer_emit_string (acfg->w, value);
330 emit_line (MonoAotCompile *acfg)
332 img_writer_emit_line (acfg->w);
336 emit_alignment (MonoAotCompile *acfg, int size)
338 img_writer_emit_alignment (acfg->w, size);
342 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
344 img_writer_emit_pointer_unaligned (acfg->w, target);
348 emit_pointer (MonoAotCompile *acfg, const char *target)
350 img_writer_emit_pointer (acfg->w, target);
354 emit_int16 (MonoAotCompile *acfg, int value)
356 img_writer_emit_int16 (acfg->w, value);
360 emit_int32 (MonoAotCompile *acfg, int value)
362 img_writer_emit_int32 (acfg->w, value);
366 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
368 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
372 emit_zero_bytes (MonoAotCompile *acfg, int num)
374 img_writer_emit_zero_bytes (acfg->w, num);
378 emit_byte (MonoAotCompile *acfg, guint8 val)
380 img_writer_emit_byte (acfg->w, val);
383 #ifdef __native_client_codegen__
385 emit_nacl_call_alignment (MonoAotCompile *acfg)
387 img_writer_emit_nacl_call_alignment (acfg->w);
391 static G_GNUC_UNUSED void
392 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
394 img_writer_emit_global (acfg->w, name, func);
398 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
400 if (acfg->aot_opts.no_dlsym) {
401 g_ptr_array_add (acfg->globals, g_strdup (name));
402 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
404 img_writer_emit_global (acfg->w, name, func);
409 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
411 img_writer_emit_symbol_size (acfg->w, name, end_label);
415 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
417 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
419 /* On apple, all symbols need to be aligned to avoid warnings from ld */
420 emit_alignment (acfg, 4);
422 img_writer_emit_label (acfg->w, name);
423 img_writer_emit_string (acfg->w, value);
426 static G_GNUC_UNUSED void
427 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
430 guint8 b = value & 0x7f;
432 if (value != 0) /* more bytes to come */
438 static G_GNUC_UNUSED void
439 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
442 gboolean negative = (value < 0);
449 /* the following is unnecessary if the
450 * implementation of >>= uses an arithmetic rather
451 * than logical shift for a signed left operand
455 value |= - ((gint64)1 <<(size - 7));
456 /* sign bit of byte is second high order bit (0x40) */
457 if ((value == 0 && !(byte & 0x40)) ||
458 (value == -1 && (byte & 0x40)))
462 emit_byte (acfg, byte);
466 static G_GNUC_UNUSED void
467 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
472 guint8 b = value & 0x7f;
474 if (value != 0) /* more bytes to come */
482 static G_GNUC_UNUSED void
483 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
486 gboolean negative = (value < 0);
494 /* the following is unnecessary if the
495 * implementation of >>= uses an arithmetic rather
496 * than logical shift for a signed left operand
500 value |= - (1 <<(size - 7));
501 /* sign bit of byte is second high order bit (0x40) */
502 if ((value == 0 && !(byte & 0x40)) ||
503 (value == -1 && (byte & 0x40)))
513 /* ARCHITECTURE SPECIFIC CODE */
515 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
516 #define EMIT_DWARF_INFO 1
519 #if defined(TARGET_ARM)
520 #define AOT_FUNC_ALIGNMENT 4
522 #define AOT_FUNC_ALIGNMENT 16
524 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
525 #undef AOT_FUNC_ALIGNMENT
526 #define AOT_FUNC_ALIGNMENT 32
529 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
530 #define PPC_LD_OP "ld"
531 #define PPC_LDX_OP "ldx"
533 #define PPC_LD_OP "lwz"
534 #define PPC_LDX_OP "lwzx"
538 #define AOT_TARGET_STR "AMD64"
543 #define AOT_TARGET_STR "ARM (MACH)"
545 #define AOT_TARGET_STR "ARM (!MACH)"
549 #ifdef TARGET_POWERPC64
550 #ifdef __mono_ilp32__
551 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
553 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
556 #ifdef TARGET_POWERPC
557 #ifdef __mono_ilp32__
558 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
560 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
567 #define AOT_TARGET_STR "X86 (WIN32)"
568 #elif defined(__native_client_codegen__)
569 #define AOT_TARGET_STR "X86 (native client codegen)"
571 #define AOT_TARGET_STR "X86 (!native client codegen)"
575 #ifndef AOT_TARGET_STR
576 #define AOT_TARGET_STR ""
580 arch_init (MonoAotCompile *acfg)
582 acfg->llc_args = g_string_new ("");
583 acfg->as_args = g_string_new ("");
586 * The prefix LLVM likes to put in front of symbol names on darwin.
587 * The mach-os specs require this for globals, but LLVM puts them in front of all
588 * symbols. We need to handle this, since we need to refer to LLVM generated
591 acfg->llvm_label_prefix = "";
594 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
595 g_string_append (acfg->llc_args, "-mattr=+v6");
598 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
599 g_string_append (acfg->as_args, " -mfpu=vfp3");
601 g_string_append (acfg->llc_args, " -soft-float");
604 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
605 acfg->thumb_mixed = TRUE;
607 if (acfg->aot_opts.mtriple)
608 mono_arch_set_target (acfg->aot_opts.mtriple);
612 acfg->llvm_label_prefix = "_";
613 acfg->need_no_dead_strip = TRUE;
616 #if defined(__linux__) && !defined(TARGET_ARM)
617 acfg->need_pt_gnu_stack = TRUE;
621 acfg->direct_method_addresses = TRUE;
622 acfg->global_symbols = TRUE;
627 * arch_emit_direct_call:
629 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
633 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
635 #if defined(TARGET_X86) || defined(TARGET_AMD64)
636 /* Need to make sure this is exactly 5 bytes long */
637 if (FALSE && !acfg->use_bin_writer) {
638 img_writer_emit_unset_mode (acfg->w);
639 fprintf (acfg->fp, "call %s\n", target);
641 emit_byte (acfg, '\xe8');
642 emit_symbol_diff (acfg, target, ".", -4);
645 #elif defined(TARGET_ARM)
646 if (acfg->use_bin_writer) {
653 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
654 emit_bytes (acfg, buf, 4);
656 img_writer_emit_unset_mode (acfg->w);
657 fprintf (acfg->fp, "bl %s\n", target);
660 #elif defined(TARGET_POWERPC)
661 if (acfg->use_bin_writer) {
662 g_assert_not_reached ();
664 img_writer_emit_unset_mode (acfg->w);
665 fprintf (acfg->fp, "bl %s\n", target);
669 g_assert_not_reached ();
675 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
677 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
678 * in in the 2. slot of every GOT, and require every method to place the GOT
679 * address in r30, even when it doesn't access the GOT otherwise. This way,
680 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
685 * PPC64 uses function descriptors which greatly complicate all code, since
686 * these are used very inconsistently in the runtime. Some functions like
687 * mono_compile_method () return ftn descriptors, while others like the
688 * trampoline creation functions do not.
689 * We assume that all GOT slots contain function descriptors, and create
690 * descriptors in aot-runtime.c when needed.
691 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
692 * from function descriptors, we could do the same, but it would require
693 * rewriting all the ppc/aot code to handle function descriptors properly.
694 * So instead, we use the same approach as on PPC32.
695 * This is a horrible mess, but fixing it would probably lead to an even bigger
701 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
704 #ifdef MONO_ARCH_AOT_SUPPORTED
706 * arch_emit_got_offset:
708 * The memory pointed to by CODE should hold native code for computing the GOT
709 * address. Emit this code while patching it with the offset between code and
710 * the GOT. CODE_SIZE is set to the number of bytes emitted.
713 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
715 #if defined(TARGET_POWERPC64)
716 g_assert (!acfg->use_bin_writer);
717 img_writer_emit_unset_mode (acfg->w);
719 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
720 * unsupported relocations. So we store the got address into the .Lgot_addr
721 * symbol which is in the text segment, compute its address, and load it.
723 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
724 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
725 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
726 fprintf (acfg->fp, "add 30, 30, 0\n");
727 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
728 acfg->label_generator ++;
730 #elif defined(TARGET_POWERPC)
731 g_assert (!acfg->use_bin_writer);
732 img_writer_emit_unset_mode (acfg->w);
733 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
734 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
735 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
736 acfg->label_generator ++;
739 guint32 offset = mono_arch_get_patch_offset (code);
740 emit_bytes (acfg, code, offset);
741 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
743 *code_size = offset + 4;
748 * arch_emit_got_access:
750 * The memory pointed to by CODE should hold native code for loading a GOT
751 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
752 * CODE_SIZE is set to the number of bytes emitted.
755 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
757 /* Emit beginning of instruction */
758 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
760 /* Emit the offset */
762 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
763 *code_size = mono_arch_get_patch_offset (code) + 4;
764 #elif defined(TARGET_X86)
765 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
766 *code_size = mono_arch_get_patch_offset (code) + 4;
767 #elif defined(TARGET_ARM)
768 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
769 *code_size = mono_arch_get_patch_offset (code) + 4;
770 #elif defined(TARGET_POWERPC)
776 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
777 g_assert (code - buf == 8);
778 emit_bytes (acfg, buf, code - buf);
779 *code_size = code - buf;
782 g_assert_not_reached ();
789 * arch_emit_plt_entry:
791 * Emit code for the PLT entry with index INDEX.
794 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
796 #if defined(TARGET_X86)
797 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
798 #if defined(__default_codegen__)
799 /* jmp *<offset>(%ebx) */
800 emit_byte (acfg, 0xff);
801 emit_byte (acfg, 0xa3);
802 emit_int32 (acfg, offset);
803 /* Used by mono_aot_get_plt_info_offset */
804 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
805 #elif defined(__native_client_codegen__)
806 const guint8 kSizeOfNaClJmp = 11;
807 guint8 bytes[kSizeOfNaClJmp];
808 guint8 *pbytes = &bytes[0];
810 x86_jump_membase32 (pbytes, X86_EBX, offset);
811 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
812 /* four bytes of data, used by mono_arch_patch_plt_entry */
813 /* For Native Client, make this work with data embedded in push. */
814 emit_byte (acfg, 0x68); /* hide data in a push */
815 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
816 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
817 #endif /*__native_client_codegen__*/
818 #elif defined(TARGET_AMD64)
819 #if defined(__default_codegen__)
821 * We can't emit jumps because they are 32 bits only so they can't be patched.
822 * So we make indirect calls through GOT entries which are patched by the AOT
823 * loader to point to .Lpd entries.
825 /* jmpq *<offset>(%rip) */
826 emit_byte (acfg, '\xff');
827 emit_byte (acfg, '\x25');
828 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
829 /* Used by mono_aot_get_plt_info_offset */
830 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
831 #elif defined(__native_client_codegen__)
833 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
834 guint8 *code = buf_aligned;
836 /* mov <OFFSET>(%rip), %r11d */
837 emit_byte (acfg, '\x45');
838 emit_byte (acfg, '\x8b');
839 emit_byte (acfg, '\x1d');
840 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
842 amd64_jump_reg (code, AMD64_R11);
843 /* This should be constant for the plt patch */
844 g_assert ((size_t)(code-buf_aligned) == 10);
845 emit_bytes (acfg, buf_aligned, code - buf_aligned);
847 /* Hide data in a push imm32 so it passes validation */
848 emit_byte (acfg, 0x68); /* push */
849 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
850 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
851 #endif /*__native_client_codegen__*/
852 #elif defined(TARGET_ARM)
857 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
858 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
859 emit_bytes (acfg, buf, code - buf);
860 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
861 /* Used by mono_aot_get_plt_info_offset */
862 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
863 #elif defined(TARGET_POWERPC)
864 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
866 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
867 g_assert (!acfg->use_bin_writer);
868 img_writer_emit_unset_mode (acfg->w);
869 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
870 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
871 fprintf (acfg->fp, "add 11, 11, 30\n");
872 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
873 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
874 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
875 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
877 fprintf (acfg->fp, "mtctr 11\n");
878 fprintf (acfg->fp, "bctr\n");
879 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
881 g_assert_not_reached ();
886 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
888 #if defined(TARGET_ARM)
890 /* LLVM calls the PLT entries using bl, so emit a stub */
891 /* FIXME: Too much overhead on every call */
892 fprintf (acfg->fp, ".thumb_func\n");
893 fprintf (acfg->fp, "bx pc\n");
894 fprintf (acfg->fp, "nop\n");
895 fprintf (acfg->fp, ".arm\n");
897 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
898 /* The caller already transitioned to thumb */
899 /* The code below should be 12 bytes long */
900 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
901 /* thumb can't encode ld pc, [pc, ip] */
902 fprintf (acfg->fp, "add ip, pc, ip\n");
903 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
904 fprintf (acfg->fp, "bx ip\n");
905 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
906 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
908 g_assert_not_reached ();
913 * arch_emit_specific_trampoline_pages:
915 * Emits a page full of trampolines: each trampoline uses its own address to
916 * lookup both the generic trampoline code and the data argument.
917 * This page can be remapped in process multiple times so we can get an
918 * unlimited number of trampolines.
919 * Specifically this implementation uses the following trick: two memory pages
920 * are allocated, with the first containing the data and the second containing the trampolines.
921 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
922 * implementation does all the lifting.
923 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
924 * on the arm 32 bit system.
927 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
929 #if defined(TARGET_ARM)
932 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
934 #define COMMON_TRAMP_SIZE 16
935 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
936 int imm8, rot_amount;
938 if (!acfg->aot_opts.use_trampolines_page)
941 emit_alignment (acfg, mono_pagesize ());
942 emit_global (acfg, "specific_trampolines_page", TRUE);
943 emit_label (acfg, "specific_trampolines_page");
945 /* emit the generic code first, the trampoline address + 8 is in the lr register */
947 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
948 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
949 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
950 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
952 g_assert (code - buf == COMMON_TRAMP_SIZE);
955 emit_bytes (acfg, buf, code - buf);
957 for (i = 0; i < count; ++i) {
959 ARM_PUSH (code, 0x5fff);
961 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
962 g_assert (code - buf == 8);
963 emit_bytes (acfg, buf, code - buf);
966 /* now the rgctx trampolines: each specific trampolines puts in the ip register
967 * the instruction pointer address, so the generic trampoline at the start of the page
968 * subtracts 4096 to get to the data page and loads the values
969 * We again fit the generic trampiline in 16 bytes.
971 emit_global (acfg, "rgctx_trampolines_page", TRUE);
972 emit_label (acfg, "rgctx_trampolines_page");
974 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
975 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
976 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
977 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
979 g_assert (code - buf == COMMON_TRAMP_SIZE);
982 emit_bytes (acfg, buf, code - buf);
984 for (i = 0; i < count; ++i) {
986 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
988 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
989 g_assert (code - buf == 8);
990 emit_bytes (acfg, buf, code - buf);
992 /* now the imt trampolines: each specific trampolines puts in the ip register
993 * the instruction pointer address, so the generic trampoline at the start of the page
994 * subtracts 4096 to get to the data page and loads the values
995 * We again fit the generic trampiline in 16 bytes.
997 #define IMT_TRAMP_SIZE 72
998 emit_global (acfg, "imt_trampolines_page", TRUE);
999 emit_label (acfg, "imt_trampolines_page");
1001 /* Need at least two free registers, plus a slot for storing the pc */
1002 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1004 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1005 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1006 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1008 /* The IMT method is in v5, r0 has the imt array address */
1011 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1012 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1013 imt_found_check = code;
1014 ARM_B_COND (code, ARMCOND_EQ, 0);
1016 /* End-of-loop check */
1017 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1018 loop_end_check = code;
1019 ARM_B_COND (code, ARMCOND_EQ, 0);
1022 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1023 loop_branch_back = code;
1025 arm_patch (loop_branch_back, loop_start);
1028 arm_patch (imt_found_check, code);
1029 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1030 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1031 /* Save it to the third stack slot */
1032 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1033 /* Restore the registers and branch */
1034 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1037 arm_patch (loop_end_check, code);
1038 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1039 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1040 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1044 g_assert (code - buf == IMT_TRAMP_SIZE);
1045 emit_bytes (acfg, buf, code - buf);
1047 for (i = 0; i < count; ++i) {
1049 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1051 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1052 g_assert (code - buf == 8);
1053 emit_bytes (acfg, buf, code - buf);
1059 * arch_emit_specific_trampoline:
1061 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1062 * two GOT slots which contain the generic trampoline address and the trampoline
1063 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1066 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1069 * The trampolines created here are variations of the specific
1070 * trampolines created in mono_arch_create_specific_trampoline (). The
1072 * - the generic trampoline address is taken from a got slot.
1073 * - the offset of the got slot where the trampoline argument is stored
1074 * is embedded in the instruction stream, and the generic trampoline
1075 * can load the argument by loading the offset, adding it to the
1076 * address of the trampoline to get the address of the got slot, and
1077 * loading the argument from there.
1078 * - all the trampolines should be of the same length.
1080 #if defined(TARGET_AMD64)
1081 #if defined(__default_codegen__)
1082 /* This should be exactly 16 bytes long */
1084 /* call *<offset>(%rip) */
1085 emit_byte (acfg, '\x41');
1086 emit_byte (acfg, '\xff');
1087 emit_byte (acfg, '\x15');
1088 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1089 /* This should be relative to the start of the trampoline */
1090 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1091 emit_zero_bytes (acfg, 5);
1092 #elif defined(__native_client_codegen__)
1094 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1095 guint8 *code = buf_aligned;
1100 /* Emit this call in 'code' so we can find out how long it is. */
1101 amd64_call_reg (code, AMD64_R11);
1102 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1103 call_len = code - call_start;
1105 /* The tramp_size is twice the NaCl alignment because it starts with */
1106 /* a call which needs to be aligned to the end of the boundary. */
1107 *tramp_size = kNaClAlignment*2;
1109 /* Emit nops to align call site below which is 7 bytes plus */
1110 /* the length of the call sequence emitted above. */
1111 /* Note: this requires the specific trampoline starts on a */
1112 /* kNaclAlignedment aligned address, which it does because */
1113 /* it's its own function that is aligned. */
1114 guint8 nop_buf[256];
1115 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1116 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1117 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1119 /* The trampoline is stored at the offset'th pointer, the -4 is */
1120 /* present because RIP relative addressing starts at the end of */
1121 /* the current instruction, while the label "." is relative to */
1122 /* the beginning of the current asm location, which in this case */
1123 /* is not the mov instruction, but the offset itself, due to the */
1124 /* way the bytes and ints are emitted here. */
1125 got_offset = (offset * sizeof(gpointer)) - 4;
1127 /* mov <OFFSET>(%rip), %r11d */
1128 emit_byte (acfg, '\x45');
1129 emit_byte (acfg, '\x8b');
1130 emit_byte (acfg, '\x1d');
1131 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1134 emit_bytes (acfg, call_start, call_len);
1136 /* The arg is stored at the offset+1 pointer, relative to beginning */
1137 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1138 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1140 /* We can't emit this data directly, hide in a "push imm32" */
1141 emit_byte (acfg, '\x68'); /* push */
1142 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1143 emit_alignment (acfg, kNaClAlignment);
1144 #endif /*__native_client_codegen__*/
1145 #elif defined(TARGET_ARM)
1149 /* This should be exactly 20 bytes long */
1152 ARM_PUSH (code, 0x5fff);
1153 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1154 /* Load the value from the GOT */
1155 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1157 ARM_BLX_REG (code, ARMREG_R1);
1159 g_assert (code - buf == 16);
1162 emit_bytes (acfg, buf, code - buf);
1164 * Only one offset is needed, since the second one would be equal to the
1167 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1168 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1169 #elif defined(TARGET_POWERPC)
1176 g_assert (!acfg->use_bin_writer);
1179 * PPC has no ip relative addressing, so we need to compute the address
1180 * of the mscorlib got. That is slow and complex, so instead, we store it
1181 * in the second got slot of every aot image. The caller already computed
1182 * the address of its got and placed it into r30.
1184 img_writer_emit_unset_mode (acfg->w);
1185 /* Load mscorlib got address */
1186 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1187 /* Load generic trampoline address */
1188 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1189 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1190 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1191 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1192 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1194 fprintf (acfg->fp, "mtctr 11\n");
1195 /* Load trampoline argument */
1196 /* On ppc, we pass it normally to the generic trampoline */
1197 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1198 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1199 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1200 /* Branch to generic trampoline */
1201 fprintf (acfg->fp, "bctr\n");
1203 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1204 *tramp_size = 10 * 4;
1206 *tramp_size = 9 * 4;
1208 #elif defined(TARGET_X86)
1212 /* Similar to the PPC code above */
1214 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1216 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1217 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1218 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1222 /* Load mscorlib got address */
1223 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1224 /* Push trampoline argument */
1225 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1226 /* Load generic trampoline address */
1227 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1228 /* Branch to generic trampoline */
1229 x86_jump_reg (code, X86_ECX);
1231 #ifdef __native_client_codegen__
1233 /* emit nops to next 32 byte alignment */
1234 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1235 while (code < (buf + a)) x86_nop(code);
1238 emit_bytes (acfg, buf, code - buf);
1240 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1241 g_assert (code - buf == *tramp_size);
1243 g_assert_not_reached ();
1248 * arch_emit_unbox_trampoline:
1250 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1251 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1254 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1256 #if defined(TARGET_AMD64)
1261 this_reg = mono_arch_get_this_arg_reg (NULL);
1263 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1265 emit_bytes (acfg, buf, code - buf);
1267 emit_byte (acfg, '\xe9');
1268 emit_symbol_diff (acfg, call_target, ".", -4);
1269 #elif defined(TARGET_X86)
1276 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1278 emit_bytes (acfg, buf, code - buf);
1281 emit_byte (acfg, '\xe9');
1282 emit_symbol_diff (acfg, call_target, ".", -4);
1283 #elif defined(TARGET_ARM)
1287 if (acfg->thumb_mixed && cfg->compile_llvm) {
1288 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1289 fprintf (acfg->fp, "b %s\n", call_target);
1290 fprintf (acfg->fp, ".arm\n");
1296 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1298 emit_bytes (acfg, buf, code - buf);
1299 /* jump to method */
1300 if (acfg->use_bin_writer) {
1307 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1308 emit_bytes (acfg, buf, 4);
1310 if (acfg->thumb_mixed && cfg->compile_llvm)
1311 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1313 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1315 #elif defined(TARGET_POWERPC)
1318 g_assert (!acfg->use_bin_writer);
1320 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1321 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1323 g_assert_not_reached ();
1328 * arch_emit_static_rgctx_trampoline:
1330 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1331 * two GOT slots which contain the rgctx argument, and the method to jump to.
1332 * TRAMP_SIZE is set to the size of the emitted trampoline.
1333 * These kinds of trampolines cannot be enumerated statically, since there could
1334 * be one trampoline per method instantiation, so we emit the same code for all
1335 * trampolines, and parameterize them using two GOT slots.
1338 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1340 #if defined(TARGET_AMD64)
1341 #if defined(__default_codegen__)
1342 /* This should be exactly 13 bytes long */
1345 /* mov <OFFSET>(%rip), %r10 */
1346 emit_byte (acfg, '\x4d');
1347 emit_byte (acfg, '\x8b');
1348 emit_byte (acfg, '\x15');
1349 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1351 /* jmp *<offset>(%rip) */
1352 emit_byte (acfg, '\xff');
1353 emit_byte (acfg, '\x25');
1354 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1355 #elif defined(__native_client_codegen__)
1357 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1358 guint8 *code = buf_aligned;
1360 /* mov <OFFSET>(%rip), %r10d */
1361 emit_byte (acfg, '\x45');
1362 emit_byte (acfg, '\x8b');
1363 emit_byte (acfg, '\x15');
1364 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1366 /* mov <OFFSET>(%rip), %r11d */
1367 emit_byte (acfg, '\x45');
1368 emit_byte (acfg, '\x8b');
1369 emit_byte (acfg, '\x1d');
1370 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1373 amd64_jump_reg (code, AMD64_R11);
1374 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1376 emit_alignment (acfg, kNaClAlignment);
1377 *tramp_size = kNaClAlignment;
1378 #endif /*__native_client_codegen__*/
1380 #elif defined(TARGET_ARM)
1384 /* This should be exactly 24 bytes long */
1387 /* Load rgctx value */
1388 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1389 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1390 /* Load branch addr + branch */
1391 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1392 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1394 g_assert (code - buf == 16);
1397 emit_bytes (acfg, buf, code - buf);
1398 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1399 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1400 #elif defined(TARGET_POWERPC)
1407 g_assert (!acfg->use_bin_writer);
1410 * PPC has no ip relative addressing, so we need to compute the address
1411 * of the mscorlib got. That is slow and complex, so instead, we store it
1412 * in the second got slot of every aot image. The caller already computed
1413 * the address of its got and placed it into r30.
1415 img_writer_emit_unset_mode (acfg->w);
1416 /* Load mscorlib got address */
1417 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1419 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1420 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1421 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1422 /* Load target address */
1423 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1424 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1425 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1426 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1427 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1428 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1430 fprintf (acfg->fp, "mtctr 11\n");
1431 /* Branch to the target address */
1432 fprintf (acfg->fp, "bctr\n");
1434 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1435 *tramp_size = 11 * 4;
1437 *tramp_size = 9 * 4;
1440 #elif defined(TARGET_X86)
1444 /* Similar to the PPC code above */
1446 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1449 /* Load mscorlib got address */
1450 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1452 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1453 /* Branch to the target address */
1454 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1456 #ifdef __native_client_codegen__
1458 /* emit nops to next 32 byte alignment */
1459 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1460 while (code < (buf + a)) x86_nop(code);
1464 emit_bytes (acfg, buf, code - buf);
1466 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1467 g_assert (code - buf == *tramp_size);
1469 g_assert_not_reached ();
1474 * arch_emit_imt_thunk:
1476 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1477 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1478 * key is the IMT key, and ptr holds the address of a memory location holding
1479 * the address to branch to if the IMT arg matches the key. The array is
1480 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1482 * TRAMP_SIZE is set to the size of the emitted trampoline.
1485 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1487 #if defined(TARGET_AMD64)
1489 #if defined(__native_client_codegen__)
1492 guint8 *labels [16];
1494 guint8 *mov_buf_ptr = mov_buf;
1496 const int kSizeOfMove = 7;
1497 #if defined(__default_codegen__)
1498 code = buf = g_malloc (256);
1499 #elif defined(__native_client_codegen__)
1500 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1501 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1502 /* The RIP relative move below is emitted first */
1507 /* FIXME: Optimize this, i.e. use binary search etc. */
1508 /* Maybe move the body into a separate function (slower, but much smaller) */
1510 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1513 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1515 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1518 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1520 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1523 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1524 amd64_jump_code (code, labels [0]);
1527 mono_amd64_patch (labels [2], code);
1528 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1529 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1532 mono_amd64_patch (labels [1], code);
1533 /* Load fail tramp */
1534 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1535 /* Check if there is a fail tramp */
1536 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1538 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1539 /* Jump to fail tramp */
1540 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1543 mono_amd64_patch (labels [3], code);
1544 x86_breakpoint (code);
1546 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1547 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1548 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1549 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1550 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1551 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1553 emit_bytes (acfg, buf, code - buf);
1555 *tramp_size = code - buf + kSizeOfMove;
1556 #if defined(__native_client_codegen__)
1557 /* The tramp will be padded to the next kNaClAlignment bundle. */
1558 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1561 #if defined(__default_codegen__)
1563 #elif defined(__native_client_codegen__)
1567 #elif defined(TARGET_X86)
1569 #ifdef __native_client_codegen__
1572 guint8 *labels [16];
1574 #if defined(__default_codegen__)
1575 code = buf = g_malloc (256);
1576 #elif defined(__native_client_codegen__)
1577 buf_alloc = g_malloc (256 + kNaClAlignment);
1578 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1581 /* Allocate a temporary stack slot */
1582 x86_push_reg (code, X86_EAX);
1584 x86_push_reg (code, X86_EAX);
1586 /* Load mscorlib got address */
1587 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1589 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1592 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1594 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1597 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1599 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1602 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1603 x86_jump_code (code, labels [0]);
1606 mono_x86_patch (labels [2], code);
1607 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1608 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1609 /* Save the target address to the temporary stack location */
1610 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1612 x86_pop_reg (code, X86_EAX);
1613 /* Jump to the target address */
1617 mono_x86_patch (labels [1], code);
1618 /* Load fail tramp */
1619 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1620 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1622 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1623 /* Jump to fail tramp */
1624 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1625 x86_pop_reg (code, X86_EAX);
1629 mono_x86_patch (labels [3], code);
1630 x86_breakpoint (code);
1632 #ifdef __native_client_codegen__
1634 /* emit nops to next 32 byte alignment */
1635 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1636 while (code < (buf + a)) x86_nop(code);
1639 emit_bytes (acfg, buf, code - buf);
1641 *tramp_size = code - buf;
1643 #if defined(__default_codegen__)
1645 #elif defined(__native_client_codegen__)
1649 #elif defined(TARGET_ARM)
1651 guint8 *code, *code2, *labels [16];
1655 /* The IMT method is in v5 */
1657 /* Need at least two free registers, plus a slot for storing the pc */
1658 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1660 /* Load the parameter from the GOT */
1661 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1662 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1665 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1666 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1668 ARM_B_COND (code, ARMCOND_EQ, 0);
1670 /* End-of-loop check */
1671 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1673 ARM_B_COND (code, ARMCOND_EQ, 0);
1676 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1679 arm_patch (labels [4], labels [1]);
1682 arm_patch (labels [2], code);
1683 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1684 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1685 /* Save it to the third stack slot */
1686 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1687 /* Restore the registers and branch */
1688 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1691 arm_patch (labels [3], code);
1692 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1693 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1694 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1698 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1700 emit_bytes (acfg, buf, code - buf);
1701 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1703 *tramp_size = code - buf + 4;
1704 #elif defined(TARGET_POWERPC)
1706 guint8 *code, *labels [16];
1710 /* Load the mscorlib got address */
1711 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1712 /* Load the parameter from the GOT */
1713 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1714 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1716 /* Load and check key */
1718 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1719 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1721 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1723 /* End-of-loop check */
1724 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1726 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1729 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1732 mono_ppc_patch (labels [4], labels [1]);
1735 mono_ppc_patch (labels [2], code);
1736 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1737 /* r11 now contains the value of the vtable slot */
1738 /* this is not a function descriptor on ppc64 */
1739 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1740 ppc_mtctr (code, ppc_r11);
1741 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1744 mono_ppc_patch (labels [3], code);
1748 *tramp_size = code - buf;
1750 emit_bytes (acfg, buf, code - buf);
1752 g_assert_not_reached ();
1757 * arch_emit_gsharedvt_arg_trampoline:
1759 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1760 * two GOT slots which contain the argument, and the code to jump to.
1761 * TRAMP_SIZE is set to the size of the emitted trampoline.
1762 * These kinds of trampolines cannot be enumerated statically, since there could
1763 * be one trampoline per method instantiation, so we emit the same code for all
1764 * trampolines, and parameterize them using two GOT slots.
1767 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1769 #if defined(TARGET_X86)
1773 /* Similar to the PPC code above */
1775 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1778 /* Load mscorlib got address */
1779 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1781 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1782 /* Branch to the target address */
1783 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1785 #ifdef __native_client_codegen__
1787 /* emit nops to next 32 byte alignment */
1788 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1789 while (code < (buf + a)) x86_nop(code);
1793 emit_bytes (acfg, buf, code - buf);
1795 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1796 g_assert (code - buf == *tramp_size);
1797 #elif defined(TARGET_ARM)
1801 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1802 /* Similar to arch_emit_specific_trampoline () */
1805 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3) | (1 << ARMREG_LR));
1806 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1807 /* Load the arg value from the GOT */
1808 ARM_LDR_REG_REG (code, ARMREG_LR, ARMREG_PC, ARMREG_R1);
1809 /* Load the addr from the GOT */
1810 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1812 ARM_BX (code, ARMREG_R1);
1814 g_assert (code - buf == 20);
1817 emit_bytes (acfg, buf, code - buf);
1818 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1820 g_assert_not_reached ();
1825 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1827 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1828 /* Based on code generated by gcc */
1829 img_writer_emit_unset_mode (acfg->w);
1832 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1833 ".section .ctors,\"aw\",@progbits\n"
1837 ".section .opd,\"aw\"\n"
1840 ".long .%s,.TOC.@tocbase32\n"
1843 ".type .%s,@function\n"
1845 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1847 ".section .ctors,\"aw\",@progbits\n"
1851 ".section .opd,\"aw\"\n"
1854 ".long .%1$s,.TOC.@tocbase32\n"
1855 ".size %1$s,.-%1$s\n"
1857 ".type .%1$s,@function\n"
1859 ".%1$s:\n", symbol);
1870 "lis 3, .Lglobals@h\n"
1871 "ori 3, 3, .Lglobals@l\n"
1872 "bl .mono_aot_register_module\n"
1880 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1882 ".size .%s,.-.%s\n", symbol, symbol);
1885 ".size .%1$s,.-.%1$s\n", symbol);
1891 /* END OF ARCH SPECIFIC CODE */
1894 mono_get_field_token (MonoClassField *field)
1896 MonoClass *klass = field->parent;
1899 for (i = 0; i < klass->field.count; ++i) {
1900 if (field == &klass->fields [i])
1901 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1904 g_assert_not_reached ();
1909 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1913 //printf ("ENCODE: %d 0x%x.\n", value, value);
1916 * Same encoding as the one used in the metadata, extended to handle values
1917 * greater than 0x1fffffff.
1919 if ((value >= 0) && (value <= 127))
1921 else if ((value >= 0) && (value <= 16383)) {
1922 p [0] = 0x80 | (value >> 8);
1923 p [1] = value & 0xff;
1925 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1926 p [0] = (value >> 24) | 0xc0;
1927 p [1] = (value >> 16) & 0xff;
1928 p [2] = (value >> 8) & 0xff;
1929 p [3] = value & 0xff;
1934 p [1] = (value >> 24) & 0xff;
1935 p [2] = (value >> 16) & 0xff;
1936 p [3] = (value >> 8) & 0xff;
1937 p [4] = value & 0xff;
1945 stream_init (MonoDynamicStream *sh)
1948 sh->alloc_size = 4096;
1949 sh->data = g_malloc (4096);
1951 /* So offsets are > 0 */
1957 make_room_in_stream (MonoDynamicStream *stream, int size)
1959 if (size <= stream->alloc_size)
1962 while (stream->alloc_size <= size) {
1963 if (stream->alloc_size < 4096)
1964 stream->alloc_size = 4096;
1966 stream->alloc_size *= 2;
1969 stream->data = g_realloc (stream->data, stream->alloc_size);
1973 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1977 make_room_in_stream (stream, stream->index + len);
1978 memcpy (stream->data + stream->index, data, len);
1979 idx = stream->index;
1980 stream->index += len;
1987 * Add data to the binary blob inside the aot image. Returns the offset inside the
1988 * blob where the data was stored.
1991 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1993 if (acfg->blob.alloc_size == 0)
1994 stream_init (&acfg->blob);
1996 return add_stream_data (&acfg->blob, (char*)data, data_len);
2000 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2005 if (acfg->blob.alloc_size == 0)
2006 stream_init (&acfg->blob);
2008 count = acfg->blob.index % align;
2010 /* we assume the stream data will be aligned */
2012 add_stream_data (&acfg->blob, buf, 4 - count);
2014 return add_stream_data (&acfg->blob, (char*)data, data_len);
2018 * emit_offset_table:
2020 * Emit a table of increasing offsets in a compact form using differential encoding.
2021 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2022 * group size, the more compact the table becomes, but the slower it becomes to compute
2023 * a given entry. Returns the size of the table.
2026 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2028 gint32 current_offset;
2029 int i, buf_size, ngroups, index_entry_size;
2031 guint32 *index_offsets;
2033 ngroups = (noffsets + (group_size - 1)) / group_size;
2035 index_offsets = g_new0 (guint32, ngroups);
2037 buf_size = noffsets * 4;
2038 p = buf = g_malloc0 (buf_size);
2041 for (i = 0; i < noffsets; ++i) {
2042 //printf ("D: %d -> %d\n", i, offsets [i]);
2043 if ((i % group_size) == 0) {
2044 index_offsets [i / group_size] = p - buf;
2045 /* Emit the full value for these entries */
2046 encode_value (offsets [i], p, &p);
2048 /* The offsets are allowed to be non-increasing */
2049 //g_assert (offsets [i] >= current_offset);
2050 encode_value (offsets [i] - current_offset, p, &p);
2052 current_offset = offsets [i];
2055 if (ngroups && index_offsets [ngroups - 1] < 65000)
2056 index_entry_size = 2;
2058 index_entry_size = 4;
2060 /* Emit the header */
2061 emit_int32 (acfg, noffsets);
2062 emit_int32 (acfg, group_size);
2063 emit_int32 (acfg, ngroups);
2064 emit_int32 (acfg, index_entry_size);
2066 /* Emit the index */
2067 for (i = 0; i < ngroups; ++i) {
2068 if (index_entry_size == 2)
2069 emit_int16 (acfg, index_offsets [i]);
2071 emit_int32 (acfg, index_offsets [i]);
2075 emit_bytes (acfg, buf, p - buf);
2077 return (int)(p - buf) + (ngroups * 4);
2081 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2085 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2089 index = g_hash_table_size (cfg->image_hash);
2090 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2091 g_ptr_array_add (cfg->image_table, image);
2097 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2100 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2102 /* FIXME: Search referenced images as well */
2103 if (!acfg->typespec_classes) {
2104 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2105 for (i = 0; i < len; ++i) {
2106 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2109 for (i = 0; i < len; ++i) {
2110 if (acfg->typespec_classes [i] == klass)
2115 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2121 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2124 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2127 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2130 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2133 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2138 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2142 if (klass->generic_class) {
2144 g_assert (klass->type_token);
2146 /* Find a typespec for a class if possible */
2147 token = find_typespec_for_class (acfg, klass);
2149 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2150 encode_value (token, p, &p);
2152 MonoClass *gclass = klass->generic_class->container_class;
2153 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2154 static int count = 0;
2157 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2158 encode_klass_ref (acfg, gclass, p, &p);
2159 encode_ginst (acfg, inst, p, &p);
2163 } else if (klass->type_token) {
2164 int iindex = get_image_index (acfg, klass->image);
2166 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2168 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2169 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2171 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2172 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2173 encode_value (get_image_index (acfg, klass->image), p, &p);
2175 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2176 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2177 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2179 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2180 encode_value (klass->byval_arg.type, p, &p);
2181 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2183 encode_value (container ? 1 : 0, p, &p);
2185 encode_value (container->is_method, p, &p);
2186 g_assert (par->serial == 0);
2187 if (container->is_method)
2188 encode_method_ref (acfg, container->owner.method, p, &p);
2190 encode_klass_ref (acfg, container->owner.klass, p, &p);
2192 encode_value (par->serial, p, &p);
2194 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2195 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2196 encode_type (acfg, &klass->byval_arg, p, &p);
2199 g_assert (klass->rank > 0);
2200 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2201 encode_value (klass->rank, p, &p);
2202 encode_klass_ref (acfg, klass->element_class, p, &p);
2210 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2211 * standard metadata encoding.
2214 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2216 gboolean shared = FALSE;
2219 * The encoding of generic instances is large so emit them only once.
2221 if (klass->generic_class) {
2223 g_assert (klass->type_token);
2225 /* Find a typespec for a class if possible */
2226 token = find_typespec_for_class (acfg, klass);
2229 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2234 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2238 buf2 = g_malloc (1024);
2241 encode_klass_ref_inner (acfg, klass, p, &p);
2242 g_assert (p - buf2 < 1024);
2244 offset = add_to_blob (acfg, buf2, p - buf2);
2247 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2253 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2254 encode_value (offset, p, &p);
2259 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2263 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2265 guint32 token = mono_get_field_token (field);
2268 encode_klass_ref (cfg, field->parent, p, &p);
2269 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2270 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2275 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2280 encode_value (inst->type_argc, p, &p);
2281 for (i = 0; i < inst->type_argc; ++i)
2282 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2287 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2290 MonoGenericInst *inst;
2292 inst = context->class_inst;
2294 g_assert (inst->type_argc);
2295 encode_ginst (acfg, inst, p, &p);
2297 encode_value (0, p, &p);
2299 inst = context->method_inst;
2301 g_assert (inst->type_argc);
2302 encode_ginst (acfg, inst, p, &p);
2304 encode_value (0, p, &p);
2310 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2314 g_assert (t->num_mods == 0);
2315 /* t->attrs can be ignored */
2316 //g_assert (t->attrs == 0);
2319 *p = MONO_TYPE_PINNED;
2323 *p = MONO_TYPE_BYREF;
2331 case MONO_TYPE_VOID:
2332 case MONO_TYPE_BOOLEAN:
2333 case MONO_TYPE_CHAR:
2346 case MONO_TYPE_STRING:
2347 case MONO_TYPE_OBJECT:
2348 case MONO_TYPE_TYPEDBYREF:
2350 case MONO_TYPE_VALUETYPE:
2351 case MONO_TYPE_CLASS:
2352 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2354 case MONO_TYPE_SZARRAY:
2355 encode_klass_ref (acfg, t->data.klass, p, &p);
2358 encode_type (acfg, t->data.type, p, &p);
2360 case MONO_TYPE_GENERICINST: {
2361 MonoClass *gclass = t->data.generic_class->container_class;
2362 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2364 encode_klass_ref (acfg, gclass, p, &p);
2365 encode_ginst (acfg, inst, p, &p);
2368 case MONO_TYPE_ARRAY: {
2369 MonoArrayType *array = t->data.array;
2372 encode_klass_ref (acfg, array->eklass, p, &p);
2373 encode_value (array->rank, p, &p);
2374 encode_value (array->numsizes, p, &p);
2375 for (i = 0; i < array->numsizes; ++i)
2376 encode_value (array->sizes [i], p, &p);
2377 encode_value (array->numlobounds, p, &p);
2378 for (i = 0; i < array->numlobounds; ++i)
2379 encode_value (array->lobounds [i], p, &p);
2383 g_assert_not_reached ();
2390 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2396 /* Similar to the metadata encoding */
2397 if (sig->generic_param_count)
2401 if (sig->explicit_this)
2403 flags |= (sig->call_convention & 0x0F);
2407 if (sig->generic_param_count)
2408 encode_value (sig->generic_param_count, p, &p);
2409 encode_value (sig->param_count, p, &p);
2411 encode_type (acfg, sig->ret, p, &p);
2412 for (i = 0; i < sig->param_count; ++i) {
2413 if (sig->sentinelpos == i) {
2414 *p = MONO_TYPE_SENTINEL;
2417 encode_type (acfg, sig->params [i], p, &p);
2423 #define MAX_IMAGE_INDEX 250
2426 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2428 guint32 image_index = get_image_index (acfg, method->klass->image);
2429 guint32 token = method->token;
2430 MonoJumpInfoToken *ji;
2434 * The encoding for most methods is as follows:
2435 * - image index encoded as a leb128
2436 * - token index encoded as a leb128
2437 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2438 * types of method encodings.
2441 /* Mark methods which can't use aot trampolines because they need the further
2442 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2444 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2445 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2446 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2448 if (method->wrapper_type) {
2449 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2451 encode_value (method->wrapper_type, p, &p);
2453 switch (method->wrapper_type) {
2454 case MONO_WRAPPER_REMOTING_INVOKE:
2455 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2456 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2459 m = mono_marshal_method_from_wrapper (method);
2461 encode_method_ref (acfg, m, p, &p);
2464 case MONO_WRAPPER_PROXY_ISINST:
2465 case MONO_WRAPPER_LDFLD:
2466 case MONO_WRAPPER_LDFLDA:
2467 case MONO_WRAPPER_STFLD:
2468 case MONO_WRAPPER_ISINST: {
2469 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2470 encode_klass_ref (acfg, proxy_class, p, &p);
2473 case MONO_WRAPPER_LDFLD_REMOTE:
2474 case MONO_WRAPPER_STFLD_REMOTE:
2476 case MONO_WRAPPER_ALLOC: {
2477 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2479 /* The GC name is saved once in MonoAotFileInfo */
2480 g_assert (info->alloc_type != -1);
2481 encode_value (info->alloc_type, p, &p);
2484 case MONO_WRAPPER_WRITE_BARRIER:
2486 case MONO_WRAPPER_STELEMREF: {
2487 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2490 encode_value (info->subtype, p, &p);
2491 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2492 encode_value (info->d.virtual_stelemref.kind, p, &p);
2495 case MONO_WRAPPER_UNKNOWN: {
2496 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2499 encode_value (info->subtype, p, &p);
2500 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2501 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2502 encode_klass_ref (acfg, method->klass, p, &p);
2503 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2504 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2507 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2508 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2511 encode_value (info->subtype, p, &p);
2512 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2513 strcpy ((char*)p, method->name);
2514 p += strlen (method->name) + 1;
2515 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2516 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2518 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2519 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2523 case MONO_WRAPPER_SYNCHRONIZED: {
2526 m = mono_marshal_method_from_wrapper (method);
2528 g_assert (m != method);
2529 encode_method_ref (acfg, m, p, &p);
2532 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2533 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2536 encode_value (info->subtype, p, &p);
2538 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2539 encode_value (info->d.element_addr.rank, p, &p);
2540 encode_value (info->d.element_addr.elem_size, p, &p);
2541 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2542 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2544 g_assert_not_reached ();
2548 case MONO_WRAPPER_CASTCLASS: {
2549 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2552 encode_value (info->subtype, p, &p);
2555 case MONO_WRAPPER_RUNTIME_INVOKE: {
2556 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2559 encode_value (info->subtype, p, &p);
2560 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2561 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2563 MonoMethodSignature *sig;
2565 encode_value (0, p, &p);
2567 sig = mono_method_signature (method);
2568 encode_signature (acfg, sig, p, &p);
2572 case MONO_WRAPPER_DELEGATE_INVOKE:
2573 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2574 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2575 MonoMethodSignature *sig = mono_method_signature (method);
2576 encode_signature (acfg, sig, p, &p);
2579 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2580 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2583 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2584 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2588 g_assert_not_reached ();
2590 } else if (mono_method_signature (method)->is_inflated) {
2592 * This is a generic method, find the original token which referenced it and
2594 * Obtain the token from information recorded by the JIT.
2596 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2598 image_index = get_image_index (acfg, ji->image);
2599 g_assert (image_index < MAX_IMAGE_INDEX);
2602 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2603 encode_value (image_index, p, &p);
2604 encode_value (token, p, &p);
2606 MonoMethod *declaring;
2607 MonoGenericContext *context = mono_method_get_context (method);
2609 g_assert (method->is_inflated);
2610 declaring = ((MonoMethodInflated*)method)->declaring;
2613 * This might be a non-generic method of a generic instance, which
2614 * doesn't have a token since the reference is generated by the JIT
2615 * like Nullable:Box/Unbox, or by generic sharing.
2617 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2618 /* Encode the klass */
2619 encode_klass_ref (acfg, method->klass, p, &p);
2620 /* Encode the method */
2621 image_index = get_image_index (acfg, method->klass->image);
2622 g_assert (image_index < MAX_IMAGE_INDEX);
2623 g_assert (declaring->token);
2624 token = declaring->token;
2625 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2626 encode_value (image_index, p, &p);
2627 encode_value (token, p, &p);
2628 encode_generic_context (acfg, context, p, &p);
2630 } else if (token == 0) {
2631 /* This might be a method of a constructed type like int[,].Set */
2632 /* Obtain the token from information recorded by the JIT */
2633 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2635 image_index = get_image_index (acfg, ji->image);
2636 g_assert (image_index < MAX_IMAGE_INDEX);
2639 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2640 encode_value (image_index, p, &p);
2641 encode_value (token, p, &p);
2644 g_assert (method->klass->rank);
2646 /* Encode directly */
2647 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2648 encode_klass_ref (acfg, method->klass, p, &p);
2649 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2650 encode_value (0, p, &p);
2651 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2652 encode_value (1, p, &p);
2653 else if (!strcmp (method->name, "Get"))
2654 encode_value (2, p, &p);
2655 else if (!strcmp (method->name, "Address"))
2656 encode_value (3, p, &p);
2657 else if (!strcmp (method->name, "Set"))
2658 encode_value (4, p, &p);
2660 g_assert_not_reached ();
2663 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2665 if (image_index >= MONO_AOT_METHODREF_MIN) {
2666 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2667 encode_value (image_index, p, &p);
2668 encode_value (mono_metadata_token_index (token), p, &p);
2670 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2677 compare_patches (gconstpointer a, gconstpointer b)
2681 i = (*(MonoJumpInfo**)a)->ip.i;
2682 j = (*(MonoJumpInfo**)b)->ip.i;
2693 static G_GNUC_UNUSED char*
2694 patch_to_string (MonoJumpInfo *patch_info)
2698 str = g_string_new ("");
2700 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2702 switch (patch_info->type) {
2703 case MONO_PATCH_INFO_VTABLE:
2704 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2709 g_string_append_printf (str, ")");
2710 return g_string_free (str, FALSE);
2716 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2719 static inline gboolean
2720 is_plt_patch (MonoJumpInfo *patch_info)
2722 switch (patch_info->type) {
2723 case MONO_PATCH_INFO_METHOD:
2724 case MONO_PATCH_INFO_INTERNAL_METHOD:
2725 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2726 case MONO_PATCH_INFO_ICALL_ADDR:
2727 case MONO_PATCH_INFO_CLASS_INIT:
2728 case MONO_PATCH_INFO_RGCTX_FETCH:
2729 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2730 case MONO_PATCH_INFO_MONITOR_ENTER:
2731 case MONO_PATCH_INFO_MONITOR_EXIT:
2732 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2742 * Return the symbol identifying the plt entry PLT_OFFSET.
2745 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2749 * The Apple linker reorganizes object files, so it doesn't like branches to local
2750 * labels, since those have no relocations.
2752 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2754 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2761 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2763 static MonoPltEntry*
2764 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2768 if (!is_plt_patch (patch_info))
2771 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2773 // FIXME: This breaks the calculation of final_got_size
2774 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2776 * Allocate a separate PLT slot for each such patch, since some plt
2777 * entries will refer to the method itself, and some will refer to the
2784 MonoJumpInfo *new_ji;
2786 g_assert (!acfg->final_got_size);
2788 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2790 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2791 res->plt_offset = acfg->plt_offset;
2793 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2794 if (acfg->aot_opts.write_symbols)
2795 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2797 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2799 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2801 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2803 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2805 acfg->plt_offset ++;
2814 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2815 * JI could be found if it exists, otherwise allocates a new one.
2818 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2822 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2824 return got_offset - 1;
2826 got_offset = acfg->got_offset;
2827 acfg->got_offset ++;
2829 if (acfg->final_got_size)
2830 g_assert (got_offset < acfg->final_got_size);
2832 acfg->stats.got_slots ++;
2833 acfg->stats.got_slot_types [ji->type] ++;
2835 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2836 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2837 g_ptr_array_add (acfg->got_patches, ji);
2842 /* Add a method to the list of methods which need to be emitted */
2844 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2847 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2848 g_ptr_array_add (acfg->methods, method);
2849 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2850 acfg->nmethods = acfg->methods->len + 1;
2853 if (method->wrapper_type || extra)
2854 g_ptr_array_add (acfg->extra_methods, method);
2858 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2860 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2868 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2872 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2876 index = acfg->method_index;
2877 add_method_with_index (acfg, method, index, extra);
2879 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2881 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2883 acfg->method_index ++;
2889 add_method (MonoAotCompile *acfg, MonoMethod *method)
2891 return add_method_full (acfg, method, FALSE, 0);
2895 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2897 add_method_full (acfg, method, TRUE, 0);
2901 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2903 if (acfg->aot_opts.log_generics)
2904 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2906 add_method_full (acfg, method, TRUE, depth);
2910 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2912 MonoAotCompile *acfg = user_data;
2913 MonoJitICallInfo *callinfo = value;
2914 MonoMethod *wrapper;
2920 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2921 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2924 add_method (acfg, wrapper);
2928 get_runtime_invoke_sig (MonoMethodSignature *sig)
2930 MonoMethodBuilder *mb;
2933 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2934 m = mono_mb_create_method (mb, sig, 16);
2935 return mono_marshal_get_runtime_invoke (m, FALSE);
2939 can_marshal_struct (MonoClass *klass)
2941 MonoClassField *field;
2942 gboolean can_marshal = TRUE;
2943 gpointer iter = NULL;
2944 MonoMarshalType *info;
2947 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2950 info = mono_marshal_load_type_info (klass);
2952 /* Only allow a few field types to avoid asserts in the marshalling code */
2953 while ((field = mono_class_get_fields (klass, &iter))) {
2954 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2957 switch (field->type->type) {
2962 case MONO_TYPE_BOOLEAN:
2965 case MONO_TYPE_CHAR:
2973 case MONO_TYPE_STRING:
2975 case MONO_TYPE_VALUETYPE:
2976 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2977 can_marshal = FALSE;
2979 case MONO_TYPE_SZARRAY: {
2980 gboolean has_mspec = FALSE;
2983 for (i = 0; i < info->num_fields; ++i) {
2984 if (info->fields [i].field == field && info->fields [i].mspec)
2989 can_marshal = FALSE;
2993 can_marshal = FALSE;
2999 /* Its hard to compute whenever these can be marshalled or not */
3000 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3007 add_wrappers (MonoAotCompile *acfg)
3009 MonoMethod *method, *m;
3011 MonoMethodSignature *sig, *csig;
3015 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3016 * so there is only one wrapper of a given type, or inlining their contents into their
3021 * FIXME: This depends on the fact that different wrappers have different
3025 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3027 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3028 gboolean skip = FALSE;
3030 method = mono_get_method (acfg->image, token, NULL);
3032 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3033 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3034 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3037 if (method->is_generic || method->klass->generic_container)
3040 /* Skip methods which can not be handled by get_runtime_invoke () */
3041 sig = mono_method_signature (method);
3044 if ((sig->ret->type == MONO_TYPE_PTR) ||
3045 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3048 for (j = 0; j < sig->param_count; j++) {
3049 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3053 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3054 if (!method->klass->contextbound) {
3055 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3056 gboolean has_nullable = FALSE;
3058 for (j = 0; j < sig->param_count; j++) {
3059 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3060 has_nullable = TRUE;
3063 if (info && !has_nullable) {
3064 /* Supported by the dynamic runtime-invoke wrapper */
3072 //printf ("%s\n", mono_method_full_name (method, TRUE));
3073 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3077 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3078 #ifdef MONO_ARCH_HAVE_TLS_GET
3079 MonoMethodDesc *desc;
3080 MonoMethod *orig_method;
3084 /* Runtime invoke wrappers */
3086 /* void runtime-invoke () [.cctor] */
3087 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3088 csig->ret = &mono_defaults.void_class->byval_arg;
3089 add_method (acfg, get_runtime_invoke_sig (csig));
3091 /* void runtime-invoke () [Finalize] */
3092 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3094 csig->ret = &mono_defaults.void_class->byval_arg;
3095 add_method (acfg, get_runtime_invoke_sig (csig));
3097 /* void runtime-invoke (string) [exception ctor] */
3098 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3100 csig->ret = &mono_defaults.void_class->byval_arg;
3101 csig->params [0] = &mono_defaults.string_class->byval_arg;
3102 add_method (acfg, get_runtime_invoke_sig (csig));
3104 /* void runtime-invoke (string, string) [exception ctor] */
3105 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3107 csig->ret = &mono_defaults.void_class->byval_arg;
3108 csig->params [0] = &mono_defaults.string_class->byval_arg;
3109 csig->params [1] = &mono_defaults.string_class->byval_arg;
3110 add_method (acfg, get_runtime_invoke_sig (csig));
3112 /* string runtime-invoke () [Exception.ToString ()] */
3113 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3115 csig->ret = &mono_defaults.string_class->byval_arg;
3116 add_method (acfg, get_runtime_invoke_sig (csig));
3118 /* void runtime-invoke (string, Exception) [exception ctor] */
3119 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3121 csig->ret = &mono_defaults.void_class->byval_arg;
3122 csig->params [0] = &mono_defaults.string_class->byval_arg;
3123 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3124 add_method (acfg, get_runtime_invoke_sig (csig));
3126 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3127 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3129 csig->ret = &(mono_class_from_name (
3130 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3131 csig->params [0] = &mono_defaults.string_class->byval_arg;
3132 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3133 add_method (acfg, get_runtime_invoke_sig (csig));
3135 /* runtime-invoke used by finalizers */
3136 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3138 /* This is used by mono_runtime_capture_context () */
3139 method = mono_get_context_capture_method ();
3141 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3143 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3144 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3147 /* JIT icall wrappers */
3148 /* FIXME: locking */
3149 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3152 add_method (acfg, mono_marshal_get_stelemref ());
3154 #ifdef MONO_ARCH_HAVE_TLS_GET
3155 /* Managed Allocators */
3156 nallocators = mono_gc_get_managed_allocator_types ();
3157 for (i = 0; i < nallocators; ++i) {
3158 m = mono_gc_get_managed_allocator_by_type (i);
3160 add_method (acfg, m);
3163 /* Monitor Enter/Exit */
3164 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3165 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3166 /* This is a v4 method */
3168 method = mono_monitor_get_fast_path (orig_method);
3170 add_method (acfg, method);
3172 mono_method_desc_free (desc);
3174 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3175 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3176 g_assert (orig_method);
3177 mono_method_desc_free (desc);
3178 method = mono_monitor_get_fast_path (orig_method);
3180 add_method (acfg, method);
3183 /* Stelemref wrappers */
3184 /* There is only a constant number of these, iterating over all types should handle them all */
3185 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3188 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3189 klass = mono_class_get (acfg->image, token);
3191 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
3193 mono_loader_clear_error ();
3196 /* castclass_with_check wrapper */
3197 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3198 /* isinst_with_check wrapper */
3199 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3201 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3203 MonoMethodDesc *desc;
3206 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3207 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3208 mono_method_desc_free (desc);
3210 m = mono_monitor_get_fast_path (m);
3212 add_method (acfg, m);
3219 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3220 * we use the original method instead at runtime.
3221 * Since full-aot doesn't support remoting, this is not a problem.
3224 /* remoting-invoke wrappers */
3225 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3226 MonoMethodSignature *sig;
3228 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3229 method = mono_get_method (acfg->image, token, NULL);
3231 sig = mono_method_signature (method);
3233 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3234 m = mono_marshal_get_remoting_invoke_with_check (method);
3236 add_method (acfg, m);
3241 /* delegate-invoke wrappers */
3242 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3244 MonoCustomAttrInfo *cattr;
3246 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3247 klass = mono_class_get (acfg->image, token);
3250 mono_loader_clear_error ();
3254 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
3255 method = mono_get_delegate_invoke (klass);
3257 m = mono_marshal_get_delegate_invoke (method, NULL);
3259 add_method (acfg, m);
3261 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3263 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3265 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3267 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3269 cattr = mono_custom_attrs_from_class (klass);
3274 for (j = 0; j < cattr->num_attrs; ++j)
3275 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3277 if (j < cattr->num_attrs)
3278 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3283 /* Synchronized wrappers */
3284 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3285 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3286 method = mono_get_method (acfg->image, token, NULL);
3288 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3289 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3292 /* pinvoke wrappers */
3293 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3295 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3297 method = mono_get_method (acfg->image, token, NULL);
3299 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3300 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3301 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3305 /* native-to-managed wrappers */
3306 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3308 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3309 MonoCustomAttrInfo *cattr;
3312 method = mono_get_method (acfg->image, token, NULL);
3315 * Only generate native-to-managed wrappers for methods which have an
3316 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3317 * name to avoid defining a new assembly to contain it.
3319 cattr = mono_custom_attrs_from_method (method);
3322 for (j = 0; j < cattr->num_attrs; ++j)
3323 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3325 if (j < cattr->num_attrs) {
3326 MonoCustomAttrEntry *e = &cattr->attrs [j];
3327 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3328 const char *p = (const char*)e->data;
3330 int slen, num_named, named_type, data_type;
3334 char *export_name = NULL;
3335 MonoMethod *wrapper;
3337 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3338 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3339 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3340 mono_method_full_name (method, TRUE));
3344 g_assert (sig->param_count == 1);
3345 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3348 * Decode the cattr manually since we can't create objects
3349 * during aot compilation.
3355 /* From load_cattr_value () in reflection.c */
3356 slen = mono_metadata_decode_value (p, &p);
3357 n = g_memdup (p, slen + 1);
3359 t = mono_reflection_type_from_name (n, acfg->image);
3363 klass = mono_class_from_mono_type (t);
3364 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3368 num_named = read16 (p);
3371 g_assert (num_named < 2);
3372 if (num_named == 1) {
3375 MonoType *prop_type;
3377 /* parse ExportSymbol attribute */
3379 named_type = *named;
3384 name_len = mono_metadata_decode_blob_size (named, &named);
3385 name = g_malloc (name_len + 1);
3386 memcpy (name, named, name_len);
3387 name [name_len] = 0;
3390 g_assert (named_type == 0x54);
3391 g_assert (!strcmp (name, "ExportSymbol"));
3393 prop_type = &mono_defaults.string_class->byval_arg;
3395 /* load_cattr_value (), string case */
3396 g_assert (*named != (char)0xff);
3397 slen = mono_metadata_decode_value (named, &named);
3398 export_name = g_malloc (slen + 1);
3399 memcpy (export_name, named, slen);
3400 export_name [slen] = 0;
3404 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3405 add_method (acfg, wrapper);
3407 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3411 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3412 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3413 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3417 /* StructureToPtr/PtrToStructure wrappers */
3418 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3421 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3422 klass = mono_class_get (acfg->image, token);
3425 mono_loader_clear_error ();
3429 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3430 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3431 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3437 has_type_vars (MonoClass *klass)
3439 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3442 return has_type_vars (klass->element_class);
3443 if (klass->generic_class) {
3444 MonoGenericContext *context = &klass->generic_class->context;
3445 if (context->class_inst) {
3448 for (i = 0; i < context->class_inst->type_argc; ++i)
3449 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3457 method_has_type_vars (MonoMethod *method)
3459 if (has_type_vars (method->klass))
3462 if (method->is_inflated) {
3463 MonoGenericContext *context = mono_method_get_context (method);
3464 if (context->method_inst) {
3467 for (i = 0; i < context->method_inst->type_argc; ++i)
3468 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3475 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3478 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3480 /* This might lead to a huge code blowup so only do it if neccesary */
3481 if (!acfg->aot_opts.full_aot && !force)
3484 add_generic_class_with_depth (acfg, klass, 0, ref);
3488 check_type_depth (MonoType *t, int depth)
3496 case MONO_TYPE_GENERICINST: {
3497 MonoGenericClass *gklass = t->data.generic_class;
3498 MonoGenericInst *ginst = gklass->context.class_inst;
3501 for (i = 0; i < ginst->type_argc; ++i) {
3502 if (check_type_depth (ginst->type_argv [i], depth + 1))
3516 * add_generic_class:
3518 * Add all methods of a generic class.
3521 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3524 MonoClassField *field;
3527 if (!acfg->ginst_hash)
3528 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3530 mono_class_init (klass);
3532 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3535 if (has_type_vars (klass))
3538 if (!klass->generic_class && !klass->rank)
3541 if (klass->exception_type)
3544 if (!acfg->ginst_hash)
3545 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3547 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3550 if (check_type_depth (&klass->byval_arg, 0))
3553 if (acfg->aot_opts.log_generics)
3554 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3556 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3559 while ((method = mono_class_get_methods (klass, &iter))) {
3560 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE))
3564 if (method->is_generic)
3569 * FIXME: Instances which are referenced by these methods are not added,
3570 * for example Array.Resize<int> for List<int>.Add ().
3572 add_extra_method_with_depth (acfg, method, depth + 1);
3576 while ((field = mono_class_get_fields (klass, &iter))) {
3577 if (field->type->type == MONO_TYPE_GENERICINST)
3578 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3581 if (klass->delegate) {
3582 method = mono_get_delegate_invoke (klass);
3584 method = mono_marshal_get_delegate_invoke (method, NULL);
3586 if (acfg->aot_opts.log_generics)
3587 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3589 add_method (acfg, method);
3592 /* Add superclasses */
3594 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3597 * For ICollection<T>, add instances of the helper methods
3598 * in Array, since a T[] could be cast to ICollection<T>.
3600 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3601 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3602 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3603 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3607 if (!strcmp (klass->name, "IEnumerator`1"))
3608 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3610 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3612 /* Add the T[]/InternalEnumerator class */
3613 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3617 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3618 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3622 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3623 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3627 while ((method = mono_class_get_methods (array_class, &iter))) {
3628 if (strstr (method->name, name_prefix)) {
3629 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3631 add_extra_method_with_depth (acfg, m, depth);
3635 g_free (name_prefix);
3638 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3639 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3640 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3641 MonoClass *icomparable, *gcomparer;
3642 MonoGenericContext ctx;
3643 MonoType *args [16];
3645 memset (&ctx, 0, sizeof (ctx));
3647 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3648 g_assert (icomparable);
3649 args [0] = &tclass->byval_arg;
3650 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3652 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3653 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3654 g_assert (gcomparer);
3655 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3659 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3660 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3661 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3662 MonoClass *iface, *gcomparer;
3663 MonoGenericContext ctx;
3664 MonoType *args [16];
3666 memset (&ctx, 0, sizeof (ctx));
3668 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3670 args [0] = &tclass->byval_arg;
3671 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3673 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3674 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3675 g_assert (gcomparer);
3676 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3682 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3685 MonoGenericContext ctx;
3686 MonoType *args [16];
3688 memset (&ctx, 0, sizeof (ctx));
3690 for (i = 0; i < ninsts; ++i) {
3691 args [0] = insts [i];
3692 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3693 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3698 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3700 MonoMethodHeader *header;
3701 MonoMethodSignature *sig;
3704 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3706 sig = mono_method_signature (method);
3709 for (j = 0; j < sig->param_count; ++j)
3710 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3711 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3714 header = mono_method_get_header (method);
3717 for (j = 0; j < header->num_locals; ++j)
3718 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3719 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3724 * add_generic_instances:
3726 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3729 add_generic_instances (MonoAotCompile *acfg)
3734 MonoGenericContext *context;
3736 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3737 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3738 method = mono_get_method (acfg->image, token, NULL);
3743 if (method->klass->image != acfg->image)
3746 context = mono_method_get_context (method);
3748 if (context && ((context->class_inst && context->class_inst->is_open)))
3752 * For open methods, create an instantiation which can be passed to the JIT.
3753 * FIXME: Handle class_inst as well.
3755 if (context && context->method_inst && context->method_inst->is_open) {
3756 MonoGenericContext shared_context;
3757 MonoGenericInst *inst;
3758 MonoType **type_argv;
3760 MonoMethod *declaring_method;
3761 gboolean supported = TRUE;
3763 /* Check that the context doesn't contain open constructed types */
3764 if (context->class_inst) {
3765 inst = context->class_inst;
3766 for (i = 0; i < inst->type_argc; ++i) {
3767 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)
3769 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3773 if (context->method_inst) {
3774 inst = context->method_inst;
3775 for (i = 0; i < inst->type_argc; ++i) {
3776 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)
3778 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3786 memset (&shared_context, 0, sizeof (MonoGenericContext));
3788 inst = context->class_inst;
3790 type_argv = g_new0 (MonoType*, inst->type_argc);
3791 for (i = 0; i < inst->type_argc; ++i) {
3792 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)
3793 type_argv [i] = &mono_defaults.object_class->byval_arg;
3795 type_argv [i] = inst->type_argv [i];
3798 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3802 inst = context->method_inst;
3804 type_argv = g_new0 (MonoType*, inst->type_argc);
3805 for (i = 0; i < inst->type_argc; ++i) {
3806 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)
3807 type_argv [i] = &mono_defaults.object_class->byval_arg;
3809 type_argv [i] = inst->type_argv [i];
3812 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3816 if (method->is_generic || method->klass->generic_container)
3817 declaring_method = method;
3819 declaring_method = mono_method_get_declaring_generic_method (method);
3821 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3825 * If the method is fully sharable, it was already added in place of its
3826 * generic definition.
3828 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE, FALSE))
3832 * FIXME: Partially shared methods are not shared here, so we end up with
3833 * many identical methods.
3835 add_extra_method (acfg, method);
3838 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3841 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3843 klass = mono_class_get (acfg->image, token);
3844 if (!klass || klass->rank) {
3845 mono_loader_clear_error ();
3849 add_generic_class (acfg, klass, FALSE, "typespec");
3852 /* Add types of args/locals */
3853 for (i = 0; i < acfg->methods->len; ++i) {
3854 method = g_ptr_array_index (acfg->methods, i);
3855 add_types_from_method_header (acfg, method);
3858 if (acfg->image == mono_defaults.corlib) {
3860 MonoType *insts [256];
3863 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3864 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3865 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3866 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3867 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3868 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3869 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3870 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3871 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3872 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3873 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3874 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3876 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3877 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3879 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3880 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3882 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3884 /* Add instances of the array generic interfaces for primitive types */
3885 /* This will add instances of the InternalArray_ helper methods in Array too */
3886 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3888 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3889 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3891 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3892 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3894 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3897 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3898 * used for all instances of GetGenericValueImpl by the AOT runtime.
3901 MonoGenericContext ctx;
3902 MonoType *args [16];
3903 MonoMethod *get_method;
3904 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3906 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3909 memset (&ctx, 0, sizeof (ctx));
3910 args [0] = &mono_defaults.object_class->byval_arg;
3911 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3912 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3916 /* Same for CompareExchange<T>/Exchange<T> */
3918 MonoGenericContext ctx;
3919 MonoType *args [16];
3921 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3922 gpointer iter = NULL;
3924 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3925 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3926 memset (&ctx, 0, sizeof (ctx));
3927 args [0] = &mono_defaults.object_class->byval_arg;
3928 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3929 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3937 * is_direct_callable:
3939 * Return whenever the method identified by JI is directly callable without
3940 * going through the PLT.
3943 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3945 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3946 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3948 gboolean direct_callable = TRUE;
3950 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3951 direct_callable = FALSE;
3952 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3953 // FIXME: Maybe call the wrapper directly ?
3954 direct_callable = FALSE;
3956 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
3957 /* Disable this so all calls go through load_method (), see the
3958 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
3959 * mono_debugger_agent_init ().
3961 direct_callable = FALSE;
3964 if (direct_callable)
3967 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3968 if (acfg->aot_opts.direct_pinvoke)
3970 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
3971 if (acfg->aot_opts.direct_icalls)
3980 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
3982 MonoImage *image = method->klass->image;
3983 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
3984 MonoTableInfo *tables = image->tables;
3985 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
3986 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
3987 guint32 im_cols [MONO_IMPLMAP_SIZE];
3990 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
3994 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
3997 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
3999 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4002 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4004 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4010 * emit_and_reloc_code:
4012 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4013 * is true, calls are made through the GOT too. This is used for emitting trampolines
4014 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4015 * since trampolines are needed to make PTL work.
4018 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
4020 int i, pindex, start_index, method_index;
4022 MonoJumpInfo *patch_info;
4023 MonoMethodHeader *header;
4024 gboolean skip, direct_call;
4026 const char *direct_call_target;
4027 const char *direct_pinvoke;
4030 header = mono_method_get_header (method);
4032 method_index = get_method_index (acfg, method);
4035 /* Collect and sort relocations */
4036 patches = g_ptr_array_new ();
4037 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4038 g_ptr_array_add (patches, patch_info);
4039 g_ptr_array_sort (patches, compare_patches);
4042 for (i = 0; i < code_len; i++) {
4044 for (pindex = start_index; pindex < patches->len; ++pindex) {
4045 patch_info = g_ptr_array_index (patches, pindex);
4046 if (patch_info->ip.i >= i)
4050 #ifdef MONO_ARCH_AOT_SUPPORTED
4052 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4053 start_index = pindex;
4055 switch (patch_info->type) {
4056 case MONO_PATCH_INFO_NONE:
4058 case MONO_PATCH_INFO_GOT_OFFSET: {
4061 arch_emit_got_offset (acfg, code + i, &code_size);
4064 patch_info->type = MONO_PATCH_INFO_NONE;
4069 * If this patch is a call, try emitting a direct call instead of
4070 * through a PLT entry. This is possible if the called method is in
4071 * the same assembly and requires no initialization.
4073 direct_call = FALSE;
4074 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4075 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4076 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4077 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4079 direct_call_target = callee_cfg->asm_symbol;
4080 patch_info->type = MONO_PATCH_INFO_NONE;
4081 acfg->stats.direct_calls ++;
4084 acfg->stats.all_calls ++;
4085 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4086 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4087 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4088 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4090 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4091 if (direct_pinvoke) {
4093 #if defined(TARGET_MACH)
4099 g_assert (strlen (direct_pinvoke) < 1000);
4100 direct_call_target = g_strdup_printf ("%s%s", prefix, direct_pinvoke);
4106 patch_info->type = MONO_PATCH_INFO_NONE;
4107 acfg->stats.direct_calls ++;
4110 if (!got_only && !direct_call) {
4111 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4113 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4115 direct_call_target = plt_entry->symbol;
4117 /* Nullify the patch */
4118 patch_info->type = MONO_PATCH_INFO_NONE;
4119 plt_entry->jit_used = TRUE;
4126 arch_emit_direct_call (acfg, direct_call_target, &call_size);
4131 got_slot = get_got_offset (acfg, patch_info);
4133 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4140 #endif /* MONO_ARCH_AOT_SUPPORTED */
4143 /* Find next patch */
4145 for (pindex = start_index; pindex < patches->len; ++pindex) {
4146 patch_info = g_ptr_array_index (patches, pindex);
4147 if (patch_info->ip.i >= i)
4151 /* Try to emit multiple bytes at once */
4152 if (pindex < patches->len && patch_info->ip.i > i) {
4153 emit_bytes (acfg, code + i, patch_info->ip.i - i);
4154 i = patch_info->ip.i - 1;
4156 emit_bytes (acfg, code + i, 1);
4165 * Modify SYMBOL so it only includes characters permissible in symbols.
4168 sanitize_symbol (char *symbol)
4170 int i, len = strlen (symbol);
4172 for (i = 0; i < len; ++i)
4173 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4178 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4180 char *name1, *name2, *cached;
4181 int i, j, len, count;
4183 name1 = mono_method_full_name (method, TRUE);
4184 len = strlen (name1);
4185 name2 = malloc (strlen (prefix) + len + 16);
4186 memcpy (name2, prefix, strlen (prefix));
4187 j = strlen (prefix);
4188 for (i = 0; i < len; ++i) {
4189 if (isalnum (name1 [i])) {
4190 name2 [j ++] = name1 [i];
4191 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4193 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4196 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4205 while (g_hash_table_lookup (cache, name2)) {
4206 sprintf (name2 + j, "_%d", count);
4210 cached = g_strdup (name2);
4211 g_hash_table_insert (cache, cached, cached);
4217 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4222 char *debug_sym = NULL;
4223 char *symbol = NULL;
4224 int func_alignment = AOT_FUNC_ALIGNMENT;
4225 MonoMethodHeader *header;
4228 method = cfg->orig_method;
4229 code = cfg->native_code;
4230 header = cfg->header;
4232 method_index = get_method_index (acfg, method);
4233 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4236 /* Make the labels local */
4237 emit_section_change (acfg, ".text", 0);
4238 emit_alignment (acfg, func_alignment);
4240 if (acfg->global_symbols && acfg->need_no_dead_strip)
4241 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4243 emit_label (acfg, cfg->asm_symbol);
4245 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4247 * Write a C style symbol for every method, this has two uses:
4248 * - it works on platforms where the dwarf debugging info is not
4250 * - it allows the setting of breakpoints of aot-ed methods.
4252 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4254 if (acfg->need_no_dead_strip)
4255 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4256 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4257 emit_label (acfg, debug_sym);
4260 export_name = g_hash_table_lookup (acfg->export_names, method);
4262 /* Emit a global symbol for the method */
4263 emit_global_inner (acfg, export_name, TRUE);
4264 emit_label (acfg, export_name);
4267 if (cfg->verbose_level > 0)
4268 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4270 acfg->stats.code_size += cfg->code_len;
4272 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4274 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
4278 if (acfg->aot_opts.write_symbols) {
4279 emit_symbol_size (acfg, debug_sym, ".");
4283 emit_label (acfg, symbol);
4290 * Encode PATCH_INFO into its disk representation.
4293 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4297 switch (patch_info->type) {
4298 case MONO_PATCH_INFO_NONE:
4300 case MONO_PATCH_INFO_IMAGE:
4301 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4303 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4304 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4305 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4307 case MONO_PATCH_INFO_METHOD_REL:
4308 encode_value ((gint)patch_info->data.offset, p, &p);
4310 case MONO_PATCH_INFO_SWITCH: {
4311 gpointer *table = (gpointer *)patch_info->data.table->table;
4314 encode_value (patch_info->data.table->table_size, p, &p);
4315 for (k = 0; k < patch_info->data.table->table_size; k++)
4316 encode_value ((int)(gssize)table [k], p, &p);
4319 case MONO_PATCH_INFO_METHODCONST:
4320 case MONO_PATCH_INFO_METHOD:
4321 case MONO_PATCH_INFO_METHOD_JUMP:
4322 case MONO_PATCH_INFO_ICALL_ADDR:
4323 case MONO_PATCH_INFO_METHOD_RGCTX:
4324 encode_method_ref (acfg, patch_info->data.method, p, &p);
4326 case MONO_PATCH_INFO_INTERNAL_METHOD:
4327 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4328 guint32 len = strlen (patch_info->data.name);
4330 encode_value (len, p, &p);
4332 memcpy (p, patch_info->data.name, len);
4337 case MONO_PATCH_INFO_LDSTR: {
4338 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4339 guint32 token = patch_info->data.token->token;
4340 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4341 encode_value (image_index, p, &p);
4342 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4345 case MONO_PATCH_INFO_RVA:
4346 case MONO_PATCH_INFO_DECLSEC:
4347 case MONO_PATCH_INFO_LDTOKEN:
4348 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4349 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4350 encode_value (patch_info->data.token->token, p, &p);
4351 encode_value (patch_info->data.token->has_context, p, &p);
4352 if (patch_info->data.token->has_context)
4353 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4355 case MONO_PATCH_INFO_EXC_NAME: {
4356 MonoClass *ex_class;
4359 mono_class_from_name (mono_defaults.exception_class->image,
4360 "System", patch_info->data.target);
4361 g_assert (ex_class);
4362 encode_klass_ref (acfg, ex_class, p, &p);
4365 case MONO_PATCH_INFO_R4:
4366 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4368 case MONO_PATCH_INFO_R8:
4369 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4370 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4372 case MONO_PATCH_INFO_VTABLE:
4373 case MONO_PATCH_INFO_CLASS:
4374 case MONO_PATCH_INFO_IID:
4375 case MONO_PATCH_INFO_ADJUSTED_IID:
4376 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4378 case MONO_PATCH_INFO_CLASS_INIT:
4379 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4380 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4382 case MONO_PATCH_INFO_FIELD:
4383 case MONO_PATCH_INFO_SFLDA:
4384 encode_field_info (acfg, patch_info->data.field, p, &p);
4386 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4388 case MONO_PATCH_INFO_RGCTX_FETCH: {
4389 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4394 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4395 * reference the same method, so encode the method only once.
4397 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4399 buf2 = g_malloc (1024);
4402 encode_method_ref (acfg, entry->method, p2, &p2);
4403 g_assert (p2 - buf2 < 1024);
4405 offset = add_to_blob (acfg, buf2, p2 - buf2);
4408 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4413 encode_value (offset, p, &p);
4414 g_assert (entry->info_type < 256);
4415 g_assert (entry->data->type < 256);
4416 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4417 encode_patch (acfg, entry->data, p, &p);
4420 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4421 case MONO_PATCH_INFO_MONITOR_ENTER:
4422 case MONO_PATCH_INFO_MONITOR_EXIT:
4423 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4425 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4426 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4427 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4429 case MONO_PATCH_INFO_SIGNATURE:
4430 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4433 g_warning ("unable to handle jump info %d", patch_info->type);
4434 g_assert_not_reached ();
4441 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4444 guint32 pindex, offset;
4445 MonoJumpInfo *patch_info;
4447 encode_value (n_patches, p, &p);
4449 for (pindex = 0; pindex < patches->len; ++pindex) {
4450 patch_info = g_ptr_array_index (patches, pindex);
4452 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4456 offset = get_got_offset (acfg, patch_info);
4457 encode_value (offset, p, &p);
4464 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4468 int pindex, buf_size, n_patches;
4470 MonoJumpInfo *patch_info;
4471 MonoMethodHeader *header;
4472 guint32 method_index;
4474 guint32 first_got_offset;
4476 method = cfg->orig_method;
4477 header = mono_method_get_header (method);
4479 method_index = get_method_index (acfg, method);
4481 /* Sort relocations */
4482 patches = g_ptr_array_new ();
4483 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4484 g_ptr_array_add (patches, patch_info);
4485 g_ptr_array_sort (patches, compare_patches);
4487 first_got_offset = acfg->cfgs [method_index]->got_offset;
4489 /**********************/
4490 /* Encode method info */
4491 /**********************/
4493 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4494 p = buf = g_malloc (buf_size);
4496 if (mono_class_get_cctor (method->klass))
4497 encode_klass_ref (acfg, method->klass, p, &p);
4499 /* Not needed when loading the method */
4500 encode_value (0, p, &p);
4503 if (cfg->opt & MONO_OPT_SHARED) {
4504 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4505 for (l = cfg->ldstr_list; l; l = l->next) {
4506 encode_value ((long)l->data, p, &p);
4510 /* Used only in shared mode */
4511 g_assert (!cfg->ldstr_list);
4514 for (pindex = 0; pindex < patches->len; ++pindex) {
4515 patch_info = g_ptr_array_index (patches, pindex);
4517 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4518 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4519 patch_info->type = MONO_PATCH_INFO_NONE;
4524 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4525 /* Stored in a GOT slot initialized at module load time */
4526 patch_info->type = MONO_PATCH_INFO_NONE;
4530 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4531 /* Stored in a GOT slot initialized at module load time */
4532 patch_info->type = MONO_PATCH_INFO_NONE;
4536 if (is_plt_patch (patch_info)) {
4537 /* Calls are made through the PLT */
4538 patch_info->type = MONO_PATCH_INFO_NONE;
4546 g_assert (cfg->has_got_slots);
4548 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4550 acfg->stats.info_size += p - buf;
4552 g_assert (p - buf < buf_size);
4554 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4559 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4561 guint32 cache_index;
4564 /* Reuse the unwind module to canonize and store unwind info entries */
4565 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4567 /* Use +/- 1 to distinguish 0s from missing entries */
4568 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4576 * It would be easier to use assembler symbols, but the caller needs an
4579 offset = acfg->unwind_info_offset;
4580 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4581 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4584 encode_value (encoded_len, p, &p);
4586 acfg->unwind_info_offset += encoded_len + (p - buf);
4592 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4595 int i, k, buf_size, method_index;
4596 guint32 debug_info_size;
4598 MonoMethodHeader *header;
4599 guint8 *p, *buf, *debug_info;
4600 MonoJitInfo *jinfo = cfg->jit_info;
4602 gboolean use_unwind_ops = FALSE;
4603 MonoSeqPointInfo *seq_points;
4605 method = cfg->orig_method;
4606 code = cfg->native_code;
4607 header = cfg->header;
4609 method_index = get_method_index (acfg, method);
4611 if (!acfg->aot_opts.nodebug) {
4612 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4615 debug_info_size = 0;
4618 seq_points = cfg->seq_point_info;
4620 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4621 p = buf = g_malloc (buf_size);
4623 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4624 use_unwind_ops = cfg->unwind_ops != NULL;
4627 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) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
4629 encode_value (flags, p, &p);
4631 if (use_unwind_ops) {
4632 guint32 encoded_len;
4636 * This is a duplicate of the data in the .debug_frame section, but that
4637 * section cannot be accessed using the dl interface.
4639 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4640 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4643 encode_value (jinfo->used_regs, p, &p);
4646 /*Encode the number of holes before the number of clauses to make decoding easier*/
4647 if (jinfo->has_try_block_holes) {
4648 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4649 encode_value (table->num_holes, p, &p);
4652 /* Exception table */
4653 if (cfg->compile_llvm) {
4655 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4656 * since the information is only available to llc. Instead, we let llc save the data
4657 * into the LSDA, and read it from there at runtime.
4659 /* The assembly might be CIL stripped so emit the data ourselves */
4660 if (header->num_clauses)
4661 encode_value (header->num_clauses, p, &p);
4663 for (k = 0; k < header->num_clauses; ++k) {
4664 MonoExceptionClause *clause;
4666 clause = &header->clauses [k];
4668 encode_value (clause->flags, p, &p);
4669 if (clause->data.catch_class) {
4670 encode_value (1, p, &p);
4671 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4673 encode_value (0, p, &p);
4676 /* Emit a list of nesting clauses */
4677 for (i = 0; i < header->num_clauses; ++i) {
4679 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4681 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4683 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4684 encode_value (i, p, &p);
4686 encode_value (-1, p, &p);
4689 if (jinfo->num_clauses)
4690 encode_value (jinfo->num_clauses, p, &p);
4692 for (k = 0; k < jinfo->num_clauses; ++k) {
4693 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4695 encode_value (ei->flags, p, &p);
4696 encode_value (ei->exvar_offset, p, &p);
4698 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4699 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4701 if (ei->data.catch_class) {
4702 encode_value (1, p, &p);
4703 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4705 encode_value (0, p, &p);
4709 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4710 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4711 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4715 if (jinfo->has_generic_jit_info) {
4716 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4717 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
4721 encode_value (gi->nlocs, p, &p);
4723 for (i = 0; i < gi->nlocs; ++i) {
4724 MonoDwarfLocListEntry *entry = &gi->locations [i];
4726 encode_value (entry->is_reg ? 1 : 0, p, &p);
4727 encode_value (entry->reg, p, &p);
4729 encode_value (entry->offset, p, &p);
4731 g_assert (entry->from == 0);
4733 encode_value (entry->from, p, &p);
4734 encode_value (entry->to, p, &p);
4737 if (!cfg->compile_llvm) {
4738 encode_value (gi->has_this ? 1 : 0, p, &p);
4739 encode_value (gi->this_reg, p, &p);
4740 encode_value (gi->this_offset, p, &p);
4745 * Need to encode jinfo->method too, since it is not equal to 'method'
4746 * when using generic sharing.
4748 encode_method_ref (acfg, jinfo->method, p, &p);
4750 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
4751 MonoMethodInflated *inflated;
4752 MonoGenericContext *context;
4753 MonoGenericInst *inst;
4755 g_assert (jinfo->method->is_inflated);
4756 inflated = (MonoMethodInflated*)jinfo->method;
4757 context = &inflated->context;
4759 encode_value (1, p, &p);
4760 if (context->class_inst) {
4761 inst = context->class_inst;
4763 encode_value (inst->type_argc, p, &p);
4764 for (i = 0; i < inst->type_argc; ++i)
4765 encode_value (gsctx->var_is_vt [i], p, &p);
4767 encode_value (0, p, &p);
4769 if (context->method_inst) {
4770 inst = context->method_inst;
4772 encode_value (inst->type_argc, p, &p);
4773 for (i = 0; i < inst->type_argc; ++i)
4774 encode_value (gsctx->mvar_is_vt [i], p, &p);
4776 encode_value (0, p, &p);
4779 encode_value (0, p, &p);
4783 if (jinfo->has_try_block_holes) {
4784 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4785 for (i = 0; i < table->num_holes; ++i) {
4786 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4787 encode_value (hole->clause, p, &p);
4788 encode_value (hole->length, p, &p);
4789 encode_value (hole->offset, p, &p);
4793 if (jinfo->has_arch_eh_info) {
4794 MonoArchEHJitInfo *eh_info;
4796 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4797 encode_value (eh_info->stack_size, p, &p);
4801 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4803 encode_value (seq_points->len, p, &p);
4804 last_il_offset = last_native_offset = 0;
4805 for (i = 0; i < seq_points->len; ++i) {
4806 SeqPoint *sp = &seq_points->seq_points [i];
4807 il_offset = sp->il_offset;
4808 native_offset = sp->native_offset;
4809 encode_value (il_offset - last_il_offset, p, &p);
4810 encode_value (native_offset - last_native_offset, p, &p);
4811 last_il_offset = il_offset;
4812 last_native_offset = native_offset;
4814 encode_value (sp->next_len, p, &p);
4815 for (j = 0; j < sp->next_len; ++j)
4816 encode_value (sp->next [j], p, &p);
4820 g_assert (debug_info_size < buf_size);
4822 encode_value (debug_info_size, p, &p);
4823 if (debug_info_size) {
4824 memcpy (p, debug_info, debug_info_size);
4825 p += debug_info_size;
4826 g_free (debug_info);
4831 encode_value (cfg->gc_map_size, p, &p);
4832 /* The GC map requires 4 bytes of alignment */
4833 while ((gsize)p % 4)
4835 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4836 p += cfg->gc_map_size;
4839 acfg->stats.ex_info_size += p - buf;
4841 g_assert (p - buf < buf_size);
4844 /* The GC Map requires 4 byte alignment */
4845 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4850 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4852 MonoClass *klass = mono_class_get (acfg->image, token);
4854 int i, buf_size, res;
4855 gboolean no_special_static, cant_encode;
4856 gpointer iter = NULL;
4859 mono_loader_clear_error ();
4863 p = buf = g_malloc (buf_size);
4865 /* Mark as unusable */
4866 encode_value (-1, p, &p);
4868 res = add_to_blob (acfg, buf, p - buf);
4874 buf_size = 10240 + (klass->vtable_size * 16);
4875 p = buf = g_malloc (buf_size);
4879 mono_class_init (klass);
4881 mono_class_get_nested_types (klass, &iter);
4882 g_assert (klass->nested_classes_inited);
4884 mono_class_setup_vtable (klass);
4887 * Emit all the information which is required for creating vtables so
4888 * the runtime does not need to create the MonoMethod structures which
4889 * take up a lot of space.
4892 no_special_static = !mono_class_has_special_static_fields (klass);
4894 /* Check whenever we have enough info to encode the vtable */
4895 cant_encode = FALSE;
4896 for (i = 0; i < klass->vtable_size; ++i) {
4897 MonoMethod *cm = klass->vtable [i];
4899 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4903 mono_class_has_finalizer (klass);
4905 if (klass->generic_container || cant_encode) {
4906 encode_value (-1, p, &p);
4908 encode_value (klass->vtable_size, p, &p);
4909 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);
4910 if (klass->has_cctor)
4911 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4912 if (klass->has_finalize)
4913 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4915 encode_value (klass->instance_size, p, &p);
4916 encode_value (mono_class_data_size (klass), p, &p);
4917 encode_value (klass->packing_size, p, &p);
4918 encode_value (klass->min_align, p, &p);
4920 for (i = 0; i < klass->vtable_size; ++i) {
4921 MonoMethod *cm = klass->vtable [i];
4924 encode_method_ref (acfg, cm, p, &p);
4926 encode_value (0, p, &p);
4930 acfg->stats.class_info_size += p - buf;
4932 g_assert (p - buf < buf_size);
4933 res = add_to_blob (acfg, buf, p - buf);
4940 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4942 char *debug_sym = NULL;
4945 case MONO_PATCH_INFO_METHOD:
4946 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4948 case MONO_PATCH_INFO_INTERNAL_METHOD:
4949 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4951 case MONO_PATCH_INFO_CLASS_INIT:
4952 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4953 sanitize_symbol (debug_sym);
4955 case MONO_PATCH_INFO_RGCTX_FETCH:
4956 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4958 case MONO_PATCH_INFO_ICALL_ADDR: {
4959 char *s = get_debug_sym (ji->data.method, "", cache);
4961 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4965 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4966 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4968 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4969 debug_sym = g_strdup_printf ("plt__generic_class_init");
4979 * Calls made from AOTed code are routed through a table of jumps similar to the
4980 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4981 * control to the AOT runtime through a trampoline.
4984 emit_plt (MonoAotCompile *acfg)
4990 sprintf (symbol, "plt");
4992 emit_section_change (acfg, ".text", 0);
4993 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4994 emit_label (acfg, symbol);
4995 emit_label (acfg, acfg->plt_symbol);
4997 for (i = 0; i < acfg->plt_offset; ++i) {
4998 char *debug_sym = NULL;
4999 MonoPltEntry *plt_entry = NULL;
5004 * The first plt entry is unused.
5008 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5013 * If the target is directly callable, alias the plt symbol to point to
5015 * FIXME: Use this to simplify emit_and_reloc_code ().
5016 * FIXME: Avoid the got slot.
5017 * FIXME: Add support to the binary writer.
5019 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5020 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5023 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5024 /* LLVM calls the PLT entries using bl, so emit a stub */
5025 fprintf (acfg->fp, "\n.thumb_func\n");
5026 emit_label (acfg, plt_entry->llvm_symbol);
5027 fprintf (acfg->fp, "bx pc\n");
5028 fprintf (acfg->fp, "nop\n");
5029 fprintf (acfg->fp, ".arm\n");
5030 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5032 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5039 debug_sym = plt_entry->debug_sym;
5041 if (acfg->thumb_mixed && !plt_entry->jit_used)
5042 /* Emit only a thumb version */
5045 if (acfg->llvm && !acfg->thumb_mixed)
5046 emit_label (acfg, plt_entry->llvm_symbol);
5049 if (acfg->need_no_dead_strip) {
5050 img_writer_emit_unset_mode (acfg->w);
5051 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5053 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5054 emit_label (acfg, debug_sym);
5057 emit_label (acfg, plt_entry->symbol);
5059 arch_emit_plt_entry (acfg, i);
5062 emit_symbol_size (acfg, debug_sym, ".");
5065 if (acfg->thumb_mixed) {
5066 /* Make sure the ARM symbols don't alias the thumb ones */
5067 emit_zero_bytes (acfg, 16);
5070 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5073 for (i = 0; i < acfg->plt_offset; ++i) {
5074 char *debug_sym = NULL;
5075 MonoPltEntry *plt_entry = NULL;
5081 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5084 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5087 /* Skip plt entries not actually called by LLVM code */
5088 if (!plt_entry->llvm_used)
5091 if (acfg->aot_opts.write_symbols) {
5092 if (plt_entry->debug_sym)
5093 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5097 #if defined(TARGET_MACH)
5098 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5099 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5101 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5102 emit_label (acfg, debug_sym);
5104 fprintf (acfg->fp, "\n.thumb_func\n");
5106 emit_label (acfg, plt_entry->llvm_symbol);
5108 arch_emit_llvm_plt_entry (acfg, i);
5111 emit_symbol_size (acfg, debug_sym, ".");
5117 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5119 sprintf (symbol, "plt_end");
5120 emit_label (acfg, symbol);
5123 static G_GNUC_UNUSED void
5124 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5126 char start_symbol [256];
5128 guint32 buf_size, info_offset;
5129 MonoJumpInfo *patch_info;
5140 code_size = info->code_size;
5142 unwind_ops = info->unwind_ops;
5144 #ifdef __native_client_codegen__
5145 mono_nacl_fix_patches (code, ji);
5150 sprintf (start_symbol, "%s", name);
5152 emit_section_change (acfg, ".text", 0);
5153 emit_global (acfg, start_symbol, TRUE);
5154 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5155 emit_label (acfg, start_symbol);
5157 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5158 emit_label (acfg, symbol);
5161 * The code should access everything through the GOT, so we pass
5164 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
5166 emit_symbol_size (acfg, start_symbol, ".");
5170 /* Sort relocations */
5171 patches = g_ptr_array_new ();
5172 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5173 if (patch_info->type != MONO_PATCH_INFO_NONE)
5174 g_ptr_array_add (patches, patch_info);
5175 g_ptr_array_sort (patches, compare_patches);
5177 buf_size = patches->len * 128 + 128;
5178 buf = g_malloc (buf_size);
5181 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5182 g_assert (p - buf < buf_size);
5184 sprintf (symbol, "%s_p", name);
5186 info_offset = add_to_blob (acfg, buf, p - buf);
5188 emit_section_change (acfg, RODATA_SECT, 0);
5189 emit_global (acfg, symbol, FALSE);
5190 emit_label (acfg, symbol);
5192 emit_int32 (acfg, info_offset);
5194 /* Emit debug info */
5198 sprintf (symbol, "%s", name);
5199 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5202 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5207 emit_trampolines (MonoAotCompile *acfg)
5210 char end_symbol [256];
5211 int i, tramp_got_offset;
5212 MonoAotTrampoline ntype;
5213 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5217 if (!acfg->aot_opts.full_aot)
5220 g_assert (acfg->image->assembly);
5222 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5223 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5224 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5225 MonoTrampInfo *info;
5228 * Emit the generic trampolines.
5230 * We could save some code by treating the generic trampolines as a wrapper
5231 * method, but that approach has its own complexities, so we choose the simpler
5234 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5235 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5236 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5237 emit_trampoline (acfg, acfg->got_offset, info);
5240 mono_arch_get_nullified_class_init_trampoline (&info);
5241 emit_trampoline (acfg, acfg->got_offset, info);
5242 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5243 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5244 emit_trampoline (acfg, acfg->got_offset, info);
5245 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5246 emit_trampoline (acfg, acfg->got_offset, info);
5249 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5250 emit_trampoline (acfg, acfg->got_offset, info);
5252 /* Emit the exception related code pieces */
5253 mono_arch_get_restore_context (&info, TRUE);
5254 emit_trampoline (acfg, acfg->got_offset, info);
5255 mono_arch_get_call_filter (&info, TRUE);
5256 emit_trampoline (acfg, acfg->got_offset, info);
5257 mono_arch_get_throw_exception (&info, TRUE);
5258 emit_trampoline (acfg, acfg->got_offset, info);
5259 mono_arch_get_rethrow_exception (&info, TRUE);
5260 emit_trampoline (acfg, acfg->got_offset, info);
5261 mono_arch_get_throw_corlib_exception (&info, TRUE);
5262 emit_trampoline (acfg, acfg->got_offset, info);
5264 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5265 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5266 emit_trampoline (acfg, acfg->got_offset, info);
5269 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5271 GSList *l = mono_arch_get_trampolines (TRUE);
5274 MonoTrampInfo *info = l->data;
5276 emit_trampoline (acfg, acfg->got_offset, info);
5282 for (i = 0; i < 128; ++i) {
5285 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5286 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5287 emit_trampoline (acfg, acfg->got_offset, info);
5289 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5290 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5291 emit_trampoline (acfg, acfg->got_offset, info);
5297 /* delegate_invoke_impl trampolines */
5298 l = mono_arch_get_delegate_invoke_impls ();
5300 MonoTrampInfo *info = l->data;
5302 emit_trampoline (acfg, acfg->got_offset, info);
5307 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5309 /* Emit trampolines which are numerous */
5312 * These include the following:
5313 * - specific trampolines
5314 * - static rgctx invoke trampolines
5316 * These trampolines have the same code, they are parameterized by GOT
5318 * They are defined in this file, in the arch_... routines instead of
5319 * in tramp-<ARCH>.c, since it is easier to do it this way.
5323 * When running in aot-only mode, we can't create specific trampolines at
5324 * runtime, so we create a few, and save them in the AOT file.
5325 * Normal trampolines embed their argument as a literal inside the
5326 * trampoline code, we can't do that here, so instead we embed an offset
5327 * which needs to be added to the trampoline address to get the address of
5328 * the GOT slot which contains the argument value.
5329 * The generated trampolines jump to the generic trampolines using another
5330 * GOT slot, which will be setup by the AOT loader to point to the
5331 * generic trampoline code of the given type.
5335 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5339 emit_section_change (acfg, ".text", 0);
5341 tramp_got_offset = acfg->got_offset;
5343 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5345 case MONO_AOT_TRAMP_SPECIFIC:
5346 sprintf (symbol, "specific_trampolines");
5348 case MONO_AOT_TRAMP_STATIC_RGCTX:
5349 sprintf (symbol, "static_rgctx_trampolines");
5351 case MONO_AOT_TRAMP_IMT_THUNK:
5352 sprintf (symbol, "imt_thunks");
5354 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5355 sprintf (symbol, "gsharedvt_arg_trampolines");
5358 g_assert_not_reached ();
5361 sprintf (end_symbol, "%s_e", symbol);
5363 if (acfg->aot_opts.write_symbols)
5364 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5366 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5367 emit_label (acfg, symbol);
5369 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5371 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5375 case MONO_AOT_TRAMP_SPECIFIC:
5376 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5377 tramp_got_offset += 2;
5379 case MONO_AOT_TRAMP_STATIC_RGCTX:
5380 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5381 tramp_got_offset += 2;
5383 case MONO_AOT_TRAMP_IMT_THUNK:
5384 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5385 tramp_got_offset += 1;
5387 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5388 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
5389 tramp_got_offset += 2;
5392 g_assert_not_reached ();
5394 #ifdef __native_client_codegen__
5395 /* align to avoid 32-byte boundary crossings */
5396 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5399 if (!acfg->trampoline_size [ntype]) {
5400 g_assert (tramp_size);
5401 acfg->trampoline_size [ntype] = tramp_size;
5405 emit_label (acfg, end_symbol);
5408 arch_emit_specific_trampoline_pages (acfg);
5410 /* Reserve some entries at the end of the GOT for our use */
5411 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5414 acfg->got_offset += acfg->num_trampoline_got_entries;
5418 str_begins_with (const char *str1, const char *str2)
5420 int len = strlen (str2);
5421 return strncmp (str1, str2, len) == 0;
5425 mono_aot_readonly_field_override (MonoClassField *field)
5428 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5429 char *p = rdv->name;
5431 len = strlen (field->parent->name_space);
5432 if (strncmp (p, field->parent->name_space, len))
5437 len = strlen (field->parent->name);
5438 if (strncmp (p, field->parent->name, len))
5443 if (strcmp (p, field->name))
5445 switch (rdv->type) {
5447 return &rdv->value.i1;
5449 return &rdv->value.i2;
5451 return &rdv->value.i4;
5460 add_readonly_value (MonoAotOptions *opts, const char *val)
5465 /* the format of val is:
5466 * namespace.typename.fieldname=type/value
5467 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5469 fval = strrchr (val, '/');
5471 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5474 tval = strrchr (val, '=');
5476 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5479 rdv = g_new0 (ReadOnlyValue, 1);
5480 rdv->name = g_malloc0 (tval - val + 1);
5481 memcpy (rdv->name, val, tval - val);
5484 if (strncmp (tval, "i1", 2) == 0) {
5485 rdv->value.i1 = atoi (fval);
5486 rdv->type = MONO_TYPE_I1;
5487 } else if (strncmp (tval, "i2", 2) == 0) {
5488 rdv->value.i2 = atoi (fval);
5489 rdv->type = MONO_TYPE_I2;
5490 } else if (strncmp (tval, "i4", 2) == 0) {
5491 rdv->value.i4 = atoi (fval);
5492 rdv->type = MONO_TYPE_I4;
5494 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5497 rdv->next = readonly_values;
5498 readonly_values = rdv;
5502 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5504 gchar **args, **ptr;
5506 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5507 for (ptr = args; ptr && *ptr; ptr ++) {
5508 const char *arg = *ptr;
5510 if (str_begins_with (arg, "outfile=")) {
5511 opts->outfile = g_strdup (arg + strlen ("outfile="));
5512 } else if (str_begins_with (arg, "save-temps")) {
5513 opts->save_temps = TRUE;
5514 } else if (str_begins_with (arg, "keep-temps")) {
5515 opts->save_temps = TRUE;
5516 } else if (str_begins_with (arg, "write-symbols")) {
5517 opts->write_symbols = TRUE;
5518 } else if (str_begins_with (arg, "no-write-symbols")) {
5519 opts->write_symbols = FALSE;
5520 } else if (str_begins_with (arg, "metadata-only")) {
5521 opts->metadata_only = TRUE;
5522 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5523 opts->bind_to_runtime_version = TRUE;
5524 } else if (str_begins_with (arg, "full")) {
5525 opts->full_aot = TRUE;
5526 } else if (str_begins_with (arg, "threads=")) {
5527 opts->nthreads = atoi (arg + strlen ("threads="));
5528 } else if (str_begins_with (arg, "static")) {
5529 opts->static_link = TRUE;
5530 opts->no_dlsym = TRUE;
5531 } else if (str_begins_with (arg, "asmonly")) {
5532 opts->asm_only = TRUE;
5533 } else if (str_begins_with (arg, "asmwriter")) {
5534 opts->asm_writer = TRUE;
5535 } else if (str_begins_with (arg, "nodebug")) {
5536 opts->nodebug = TRUE;
5537 } else if (str_begins_with (arg, "nopagetrampolines")) {
5538 opts->use_trampolines_page = FALSE;
5539 } else if (str_begins_with (arg, "ntrampolines=")) {
5540 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5541 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5542 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5543 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5544 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5545 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
5546 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
5547 } else if (str_begins_with (arg, "autoreg")) {
5548 opts->autoreg = TRUE;
5549 } else if (str_begins_with (arg, "tool-prefix=")) {
5550 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5551 } else if (str_begins_with (arg, "soft-debug")) {
5552 opts->soft_debug = TRUE;
5553 } else if (str_begins_with (arg, "direct-pinvoke")) {
5554 opts->direct_pinvoke = TRUE;
5555 } else if (str_begins_with (arg, "direct-icalls")) {
5556 opts->direct_icalls = TRUE;
5557 #if defined(TARGET_ARM)
5558 } else if (str_begins_with (arg, "iphone-abi")) {
5559 // older full-aot users did depend on this.
5561 } else if (str_begins_with (arg, "no-direct-calls")) {
5562 opts->no_direct_calls = TRUE;
5563 } else if (str_begins_with (arg, "print-skipped")) {
5564 opts->print_skipped_methods = TRUE;
5565 } else if (str_begins_with (arg, "stats")) {
5567 } else if (str_begins_with (arg, "log-generics")) {
5568 opts->log_generics = TRUE;
5569 } else if (str_begins_with (arg, "mtriple=")) {
5570 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5571 } else if (str_begins_with (arg, "llvm-path=")) {
5572 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5573 } else if (str_begins_with (arg, "readonly-value=")) {
5574 add_readonly_value (opts, arg + strlen ("readonly-value="));
5575 } else if (str_begins_with (arg, "info")) {
5576 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5578 } else if (str_begins_with (arg, "gc-maps")) {
5579 mini_gc_enable_gc_maps_for_aot ();
5580 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5581 printf ("Supported options for --aot:\n");
5582 printf (" outfile=\n");
5583 printf (" save-temps\n");
5584 printf (" keep-temps\n");
5585 printf (" write-symbols\n");
5586 printf (" metadata-only\n");
5587 printf (" bind-to-runtime-version\n");
5589 printf (" threads=\n");
5590 printf (" static\n");
5591 printf (" asmonly\n");
5592 printf (" asmwriter\n");
5593 printf (" nodebug\n");
5594 printf (" ntrampolines=\n");
5595 printf (" nrgctx-trampolines=\n");
5596 printf (" nimt-trampolines=\n");
5597 printf (" ngsharedvt-trampolines=\n");
5598 printf (" autoreg\n");
5599 printf (" tool-prefix=\n");
5600 printf (" readonly-value=\n");
5601 printf (" soft-debug\n");
5602 printf (" gc-maps\n");
5603 printf (" print-skipped\n");
5604 printf (" stats\n");
5606 printf (" help/?\n");
5609 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5614 if (opts->use_trampolines_page) {
5615 opts->ntrampolines = 0;
5616 opts->nrgctx_trampolines = 0;
5617 opts->nimt_trampolines = 0;
5623 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5625 MonoMethod *method = (MonoMethod*)key;
5626 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5627 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5628 MonoAotCompile *acfg = user_data;
5630 new_ji->image = ji->image;
5631 new_ji->token = ji->token;
5632 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5636 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5638 if (klass->type_token)
5640 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5643 return can_encode_class (acfg, klass->element_class);
5648 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5650 switch (patch_info->type) {
5651 case MONO_PATCH_INFO_METHOD:
5652 case MONO_PATCH_INFO_METHODCONST: {
5653 MonoMethod *method = patch_info->data.method;
5655 if (method->wrapper_type) {
5656 switch (method->wrapper_type) {
5657 case MONO_WRAPPER_NONE:
5658 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5659 case MONO_WRAPPER_XDOMAIN_INVOKE:
5660 case MONO_WRAPPER_STFLD:
5661 case MONO_WRAPPER_LDFLD:
5662 case MONO_WRAPPER_LDFLDA:
5663 case MONO_WRAPPER_LDFLD_REMOTE:
5664 case MONO_WRAPPER_STFLD_REMOTE:
5665 case MONO_WRAPPER_STELEMREF:
5666 case MONO_WRAPPER_ISINST:
5667 case MONO_WRAPPER_PROXY_ISINST:
5668 case MONO_WRAPPER_ALLOC:
5669 case MONO_WRAPPER_REMOTING_INVOKE:
5670 case MONO_WRAPPER_UNKNOWN:
5671 case MONO_WRAPPER_WRITE_BARRIER:
5673 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5674 case MONO_WRAPPER_CASTCLASS: {
5675 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5684 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5688 if (!method->token) {
5689 /* The method is part of a constructed type like Int[,].Set (). */
5690 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5691 if (method->klass->rank)
5699 case MONO_PATCH_INFO_VTABLE:
5700 case MONO_PATCH_INFO_CLASS_INIT:
5701 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5702 case MONO_PATCH_INFO_CLASS:
5703 case MONO_PATCH_INFO_IID:
5704 case MONO_PATCH_INFO_ADJUSTED_IID:
5705 if (!can_encode_class (acfg, patch_info->data.klass)) {
5706 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5710 case MONO_PATCH_INFO_RGCTX_FETCH: {
5711 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5713 if (!can_encode_patch (acfg, entry->data))
5727 * AOT compile a given method.
5728 * This function might be called by multiple threads, so it must be thread-safe.
5731 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5734 MonoJumpInfo *patch_info;
5737 MonoMethod *wrapped;
5739 if (acfg->aot_opts.metadata_only)
5742 mono_acfg_lock (acfg);
5743 index = get_method_index (acfg, method);
5744 mono_acfg_unlock (acfg);
5746 /* fixme: maybe we can also precompile wrapper methods */
5747 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5748 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5749 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5750 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5754 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5757 wrapped = mono_marshal_method_from_wrapper (method);
5758 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5759 // FIXME: The wrapper should be generic too, but it is not
5762 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5765 InterlockedIncrement (&acfg->stats.mcount);
5768 if (method->is_generic || method->klass->generic_container) {
5769 InterlockedIncrement (&acfg->stats.genericcount);
5774 //acfg->aot_opts.print_skipped_methods = TRUE;
5777 * Since these methods are the only ones which are compiled with
5778 * AOT support, and they are not used by runtime startup/shutdown code,
5779 * the runtime will not see AOT methods during AOT compilation,so it
5780 * does not need to support them by creating a fake GOT etc.
5782 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5783 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5784 if (acfg->aot_opts.print_skipped_methods)
5785 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
5786 InterlockedIncrement (&acfg->stats.genericcount);
5789 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5790 if (acfg->aot_opts.print_skipped_methods)
5791 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5792 /* Let the exception happen at runtime */
5796 if (cfg->disable_aot) {
5797 if (acfg->aot_opts.print_skipped_methods)
5798 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5799 InterlockedIncrement (&acfg->stats.ocount);
5800 mono_destroy_compile (cfg);
5804 /* Nullify patches which need no aot processing */
5805 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5806 switch (patch_info->type) {
5807 case MONO_PATCH_INFO_LABEL:
5808 case MONO_PATCH_INFO_BB:
5809 patch_info->type = MONO_PATCH_INFO_NONE;
5816 /* Collect method->token associations from the cfg */
5817 mono_acfg_lock (acfg);
5818 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5819 mono_acfg_unlock (acfg);
5822 * Check for absolute addresses.
5825 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5826 switch (patch_info->type) {
5827 case MONO_PATCH_INFO_ABS:
5828 /* unable to handle this */
5837 if (acfg->aot_opts.print_skipped_methods)
5838 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5839 InterlockedIncrement (&acfg->stats.abscount);
5840 mono_destroy_compile (cfg);
5844 /* Lock for the rest of the code */
5845 mono_acfg_lock (acfg);
5848 * Check for methods/klasses we can't encode.
5851 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5852 if (!can_encode_patch (acfg, patch_info))
5857 if (acfg->aot_opts.print_skipped_methods)
5858 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5859 acfg->stats.ocount++;
5860 mono_destroy_compile (cfg);
5861 mono_acfg_unlock (acfg);
5865 /* Adds generic instances referenced by this method */
5867 * The depth is used to avoid infinite loops when generic virtual recursion is
5870 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5872 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5873 switch (patch_info->type) {
5874 case MONO_PATCH_INFO_METHOD: {
5875 MonoMethod *m = patch_info->data.method;
5876 if (m->is_inflated) {
5877 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5878 mono_method_is_generic_sharable_impl_full (m, FALSE, FALSE, FALSE)) &&
5879 !method_has_type_vars (m)) {
5880 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5881 if (acfg->aot_opts.full_aot)
5882 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5884 add_extra_method_with_depth (acfg, m, depth + 1);
5885 add_types_from_method_header (acfg, m);
5888 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
5890 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5891 add_extra_method_with_depth (acfg, m, depth + 1);
5894 case MONO_PATCH_INFO_VTABLE: {
5895 MonoClass *klass = patch_info->data.klass;
5897 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5898 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
5901 case MONO_PATCH_INFO_SFLDA: {
5902 MonoClass *klass = patch_info->data.field->parent;
5904 /* The .cctor needs to run at runtime. */
5905 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5906 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5915 /* Determine whenever the method has GOT slots */
5916 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5917 switch (patch_info->type) {
5918 case MONO_PATCH_INFO_GOT_OFFSET:
5919 case MONO_PATCH_INFO_NONE:
5920 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5922 case MONO_PATCH_INFO_IMAGE:
5923 /* The assembly is stored in GOT slot 0 */
5924 if (patch_info->data.image != acfg->image)
5925 cfg->has_got_slots = TRUE;
5928 if (!is_plt_patch (patch_info))
5929 cfg->has_got_slots = TRUE;
5934 if (!cfg->has_got_slots)
5935 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5938 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5940 /* Make a copy of the patch info which is in the mempool */
5942 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5944 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5945 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5948 patches = new_patch_info;
5950 patches_end->next = new_patch_info;
5951 patches_end = new_patch_info;
5953 cfg->patch_info = patches;
5955 /* Make a copy of the unwind info */
5957 GSList *l, *unwind_ops;
5961 for (l = cfg->unwind_ops; l; l = l->next) {
5962 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5963 memcpy (op, l->data, sizeof (MonoUnwindOp));
5964 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5966 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5968 /* Make a copy of the argument/local info */
5970 MonoInst **args, **locals;
5971 MonoMethodSignature *sig;
5972 MonoMethodHeader *header;
5975 sig = mono_method_signature (method);
5976 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5977 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5978 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5979 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5983 header = mono_method_get_header (method);
5984 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5985 for (i = 0; i < header->num_locals; ++i) {
5986 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5987 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5989 cfg->locals = locals;
5992 /* Free some fields used by cfg to conserve memory */
5993 mono_mempool_destroy (cfg->mempool);
5994 cfg->mempool = NULL;
5995 g_free (cfg->varinfo);
5996 cfg->varinfo = NULL;
6000 mono_regstate_free (cfg->rs);
6004 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6006 while (index >= acfg->cfgs_size) {
6007 MonoCompile **new_cfgs;
6010 new_size = acfg->cfgs_size * 2;
6011 new_cfgs = g_new0 (MonoCompile*, new_size);
6012 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6013 g_free (acfg->cfgs);
6014 acfg->cfgs = new_cfgs;
6015 acfg->cfgs_size = new_size;
6017 acfg->cfgs [index] = cfg;
6019 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6022 if (cfg->orig_method->wrapper_type)
6023 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6026 mono_acfg_unlock (acfg);
6028 InterlockedIncrement (&acfg->stats.ccount);
6032 compile_thread_main (gpointer *user_data)
6034 MonoDomain *domain = user_data [0];
6035 MonoAotCompile *acfg = user_data [1];
6036 GPtrArray *methods = user_data [2];
6039 mono_thread_attach (domain);
6041 for (i = 0; i < methods->len; ++i)
6042 compile_method (acfg, g_ptr_array_index (methods, i));
6046 load_profile_files (MonoAotCompile *acfg)
6050 int file_index, res, method_index, i;
6053 GList *unordered, *l;
6058 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6060 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6065 infile = fopen (tmp, "r");
6068 printf ("Using profile data file '%s'\n", tmp);
6073 res = fscanf (infile, "%32s\n", ver);
6074 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6075 printf ("Profile file has wrong version or invalid.\n");
6082 MonoMethodDesc *desc;
6085 if (fgets (name, 1023, infile) == NULL)
6088 /* Kill the newline */
6089 if (strlen (name) > 0)
6090 name [strlen (name) - 1] = '\0';
6092 desc = mono_method_desc_new (name, TRUE);
6094 method = mono_method_desc_search_in_image (desc, acfg->image);
6096 if (method && mono_method_get_token (method)) {
6097 token = mono_method_get_token (method);
6098 method_index = mono_metadata_token_index (token) - 1;
6101 for (i = 0; i < acfg->method_order->len; ++i) {
6102 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6108 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6110 //printf ("No method found matching '%s'.\n", name);
6116 /* Add missing methods */
6118 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6120 for (i = 0; i < acfg->method_order->len; ++i) {
6121 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6127 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6129 unordered = g_list_reverse (unordered);
6130 for (l = unordered; l; l = l->next)
6131 g_ptr_array_add (acfg->method_order, l->data);
6134 /* Used by the LLVM backend */
6136 mono_aot_get_got_offset (MonoJumpInfo *ji)
6138 return get_got_offset (llvm_acfg, ji);
6142 mono_aot_get_method_name (MonoCompile *cfg)
6144 if (llvm_acfg->aot_opts.static_link)
6145 /* Include the assembly name too to avoid duplicate symbol errors */
6146 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6148 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6152 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6154 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6155 MonoPltEntry *plt_entry;
6158 ji->data.target = data;
6160 if (!can_encode_patch (llvm_acfg, ji))
6163 plt_entry = get_plt_entry (llvm_acfg, ji);
6164 plt_entry->llvm_used = TRUE;
6166 #if defined(TARGET_MACH)
6167 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6169 return g_strdup_printf (plt_entry->llvm_symbol);
6174 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6178 mono_acfg_lock (llvm_acfg);
6179 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6180 mono_acfg_unlock (llvm_acfg);
6190 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6194 emit_llvm_file (MonoAotCompile *acfg)
6196 char *command, *opts, *tempbc;
6198 MonoJumpInfo *patch_info;
6201 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6205 /* Compute the final size of the got */
6206 for (i = 0; i < acfg->nmethods; ++i) {
6207 if (acfg->cfgs [i]) {
6208 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6209 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6210 if (!is_plt_patch (patch_info))
6211 get_got_offset (acfg, patch_info);
6213 get_plt_entry (acfg, patch_info);
6219 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6221 if (acfg->aot_opts.full_aot) {
6225 * Need to add the got entries used by the trampolines.
6226 * This is only a conservative approximation.
6228 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6229 /* For the generic + rgctx trampolines */
6230 acfg->final_got_size += 400;
6231 /* For the specific trampolines */
6232 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6233 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6238 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6239 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6243 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6244 * a lot of time, and doesn't seem to save much space.
6245 * The following optimizations cannot be enabled:
6247 * - 'jump-threading' changes our blockaddress references to int constants.
6248 * - 'basiccg' fails because it contains:
6249 * if (CS && !isa<IntrinsicInst>(II)) {
6250 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6251 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6252 * The opt list below was produced by taking the output of:
6253 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6254 * then removing tailcallelim + the global opts, and adding a second gvn.
6256 opts = g_strdup ("-instcombine -simplifycfg");
6257 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
6259 command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6260 printf ("Executing opt: %s\n", command);
6261 if (system (command) != 0) {
6267 if (!acfg->llc_args)
6268 acfg->llc_args = g_string_new ("");
6270 /* Verbose asm slows down llc greatly */
6271 g_string_append (acfg->llc_args, " -asm-verbose=false");
6273 if (acfg->aot_opts.mtriple)
6274 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6276 if (llvm_acfg->aot_opts.static_link)
6277 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6279 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6280 unlink (acfg->tmpfname);
6282 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s %s.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
6284 printf ("Executing llc: %s\n", command);
6286 if (system (command) != 0) {
6293 emit_code (MonoAotCompile *acfg)
6295 int oindex, i, prev_index;
6297 char end_symbol [256];
6299 #if defined(TARGET_POWERPC64)
6300 sprintf (symbol, ".Lgot_addr");
6301 emit_section_change (acfg, ".text", 0);
6302 emit_alignment (acfg, 8);
6303 emit_label (acfg, symbol);
6304 emit_pointer (acfg, acfg->got_symbol);
6308 * This global symbol is used to compute the address of each method using the
6309 * code_offsets array. It is also used to compute the memory ranges occupied by
6310 * AOT code, so it must be equal to the address of the first emitted method.
6312 sprintf (symbol, "methods");
6313 emit_section_change (acfg, ".text", 0);
6314 emit_alignment (acfg, 8);
6316 for (i = 0; i < acfg->nmethods; ++i) {
6317 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6318 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6322 if (i == acfg->nmethods)
6323 /* No LLVM compiled methods */
6324 emit_label (acfg, symbol);
6326 emit_label (acfg, symbol);
6330 * Emit some padding so the local symbol for the first method doesn't have the
6331 * same address as 'methods'.
6333 #if defined(__default_codegen__)
6334 emit_zero_bytes (acfg, 16);
6335 #elif defined(__native_client_codegen__)
6337 const int kPaddingSize = 16;
6338 guint8 pad_buffer[kPaddingSize];
6339 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6340 emit_bytes (acfg, pad_buffer, kPaddingSize);
6344 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6348 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6350 cfg = acfg->cfgs [i];
6355 method = cfg->orig_method;
6357 /* Emit unbox trampoline */
6358 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6359 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6361 emit_section_change (acfg, ".text", 0);
6362 #ifdef __native_client_codegen__
6363 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6366 if (acfg->thumb_mixed && cfg->compile_llvm)
6367 fprintf (acfg->fp, "\n.thumb_func\n");
6369 emit_label (acfg, symbol);
6371 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6374 if (cfg->compile_llvm)
6375 acfg->stats.llvm_count ++;
6377 emit_method_code (acfg, cfg);
6380 sprintf (symbol, "methods_end");
6381 emit_section_change (acfg, ".text", 0);
6382 emit_alignment (acfg, 8);
6383 emit_label (acfg, symbol);
6386 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6387 * from optimizing them away, since it doesn't see that code_offsets references them.
6388 * JITted methods don't need this since they are referenced using assembler local
6390 * FIXME: This is why write-symbols doesn't work on OSX ?
6392 if (acfg->llvm && acfg->need_no_dead_strip) {
6393 fprintf (acfg->fp, "\n");
6394 for (i = 0; i < acfg->nmethods; ++i) {
6395 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6396 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6401 if (acfg->direct_method_addresses) {
6402 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6404 sprintf (symbol, "method_addresses");
6405 emit_section_change (acfg, RODATA_SECT, 1);
6406 emit_alignment (acfg, 8);
6407 emit_label (acfg, symbol);
6409 for (i = 0; i < acfg->nmethods; ++i) {
6410 if (acfg->cfgs [i]) {
6411 emit_pointer (acfg, acfg->cfgs [i]->asm_symbol);
6413 emit_pointer (acfg, NULL);
6418 sprintf (symbol, "code_offsets");
6419 emit_section_change (acfg, RODATA_SECT, 1);
6420 emit_alignment (acfg, 8);
6421 emit_label (acfg, symbol);
6423 sprintf (symbol, "code_offsets");
6424 emit_section_change (acfg, RODATA_SECT, 1);
6425 emit_alignment (acfg, 8);
6426 emit_label (acfg, symbol);
6428 acfg->stats.offsets_size += acfg->nmethods * 4;
6430 sprintf (end_symbol, "methods");
6431 for (i = 0; i < acfg->nmethods; ++i) {
6432 if (acfg->cfgs [i]) {
6433 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6435 emit_int32 (acfg, 0xffffffff);
6440 sprintf (symbol, "code_offsets");
6441 emit_section_change (acfg, RODATA_SECT, 1);
6442 emit_alignment (acfg, 8);
6443 emit_label (acfg, symbol);
6445 acfg->stats.offsets_size += acfg->nmethods * 4;
6447 sprintf (end_symbol, "methods");
6448 for (i = 0; i < acfg->nmethods; ++i) {
6449 if (acfg->cfgs [i]) {
6450 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6452 emit_int32 (acfg, 0xffffffff);
6458 /* Emit a sorted table mapping methods to their unbox trampolines */
6459 sprintf (symbol, "unbox_trampolines");
6460 emit_section_change (acfg, RODATA_SECT, 1);
6461 emit_alignment (acfg, 8);
6462 emit_label (acfg, symbol);
6464 sprintf (end_symbol, "methods");
6466 for (i = 0; i < acfg->nmethods; ++i) {
6471 cfg = acfg->cfgs [i];
6475 method = cfg->orig_method;
6477 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
6478 index = get_method_index (acfg, method);
6479 sprintf (symbol, "ut_%d", index);
6481 emit_int32 (acfg, index);
6482 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6483 /* Make sure the table is sorted by index */
6484 g_assert (index > prev_index);
6488 sprintf (symbol, "unbox_trampolines_end");
6489 emit_label (acfg, symbol);
6493 emit_info (MonoAotCompile *acfg)
6499 offsets = g_new0 (gint32, acfg->nmethods);
6501 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6502 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6504 if (acfg->cfgs [i]) {
6505 emit_method_info (acfg, acfg->cfgs [i]);
6506 offsets [i] = acfg->cfgs [i]->method_info_offset;
6512 sprintf (symbol, "method_info_offsets");
6513 emit_section_change (acfg, RODATA_SECT, 1);
6514 emit_alignment (acfg, 8);
6515 emit_label (acfg, symbol);
6517 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6522 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6524 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6525 #define mix(a,b,c) { \
6526 a -= c; a ^= rot(c, 4); c += b; \
6527 b -= a; b ^= rot(a, 6); a += c; \
6528 c -= b; c ^= rot(b, 8); b += a; \
6529 a -= c; a ^= rot(c,16); c += b; \
6530 b -= a; b ^= rot(a,19); a += c; \
6531 c -= b; c ^= rot(b, 4); b += a; \
6533 #define final(a,b,c) { \
6534 c ^= b; c -= rot(b,14); \
6535 a ^= c; a -= rot(c,11); \
6536 b ^= a; b -= rot(a,25); \
6537 c ^= b; c -= rot(b,16); \
6538 a ^= c; a -= rot(c,4); \
6539 b ^= a; b -= rot(a,14); \
6540 c ^= b; c -= rot(b,24); \
6544 mono_aot_type_hash (MonoType *t1)
6546 guint hash = t1->type;
6548 hash |= t1->byref << 6; /* do not collide with t1->type values */
6550 case MONO_TYPE_VALUETYPE:
6551 case MONO_TYPE_CLASS:
6552 case MONO_TYPE_SZARRAY:
6553 /* check if the distribution is good enough */
6554 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6556 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6557 case MONO_TYPE_ARRAY:
6558 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6559 case MONO_TYPE_GENERICINST:
6560 return ((hash << 5) - hash) ^ 0;
6567 * mono_aot_method_hash:
6569 * Return a hash code for methods which only depends on metadata.
6572 mono_aot_method_hash (MonoMethod *method)
6574 MonoMethodSignature *sig;
6578 guint32 *hashes_start, *hashes;
6580 MonoGenericInst *ginst = NULL;
6582 /* Similar to the hash in mono_method_get_imt_slot () */
6584 sig = mono_method_signature (method);
6586 if (method->is_inflated)
6587 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6589 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6590 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6591 hashes = hashes_start;
6593 /* Some wrappers are assigned to random classes */
6594 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6595 klass = method->klass;
6597 klass = mono_defaults.object_class;
6599 if (!method->wrapper_type) {
6600 char *full_name = mono_type_full_name (&klass->byval_arg);
6602 hashes [0] = mono_metadata_str_hash (full_name);
6606 hashes [0] = mono_metadata_str_hash (klass->name);
6607 hashes [1] = mono_metadata_str_hash (klass->name_space);
6609 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6610 /* The method name includes a stringified pointer */
6613 hashes [2] = mono_metadata_str_hash (method->name);
6614 hashes [3] = method->wrapper_type;
6615 hashes [4] = mono_aot_type_hash (sig->ret);
6617 for (i = 0; i < sig->param_count; i++) {
6618 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6621 for (i = 0; i < ginst->type_argc; ++i)
6622 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6624 g_assert (hindex == hashes_count);
6626 /* Setup internal state */
6627 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6629 /* Handle most of the hashes */
6630 while (hashes_count > 3) {
6639 /* Handle the last 3 hashes (all the case statements fall through) */
6640 switch (hashes_count) {
6641 case 3 : c += hashes [2];
6642 case 2 : b += hashes [1];
6643 case 1 : a += hashes [0];
6645 case 0: /* nothing left to add */
6649 free (hashes_start);
6658 * mono_aot_wrapper_name:
6660 * Return a string which uniqely identifies the given wrapper method.
6663 mono_aot_wrapper_name (MonoMethod *method)
6665 char *name, *tmpsig, *klass_desc;
6667 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6669 switch (method->wrapper_type) {
6670 case MONO_WRAPPER_RUNTIME_INVOKE:
6671 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6672 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6674 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6677 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6678 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6679 g_free (klass_desc);
6689 * mono_aot_get_array_helper_from_wrapper;
6691 * Get the helper method in Array called by an array wrapper method.
6694 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6698 MonoGenericContext ctx;
6699 MonoType *args [16];
6700 char *mname, *iname, *s, *s2, *helper_name = NULL;
6702 prefix = "System.Collections.Generic";
6703 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6704 s2 = strstr (s, "`1.");
6710 //printf ("X: %s %s\n", iname, mname);
6712 if (!strcmp (iname, "IList"))
6713 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6715 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6716 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6718 g_free (helper_name);
6721 if (m->is_generic) {
6722 memset (&ctx, 0, sizeof (ctx));
6723 args [0] = &method->klass->element_class->byval_arg;
6724 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6725 m = mono_class_inflate_generic_method (m, &ctx);
6731 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6733 typedef struct HashEntry {
6734 guint32 key, value, index;
6735 struct HashEntry *next;
6739 * emit_extra_methods:
6741 * Emit methods which are not in the METHOD table, like wrappers.
6744 emit_extra_methods (MonoAotCompile *acfg)
6746 int i, table_size, buf_size;
6749 guint32 *info_offsets;
6752 HashEntry *entry, *new_entry;
6753 int nmethods, max_chain_length;
6756 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6758 /* Emit method info */
6760 for (i = 0; i < acfg->extra_methods->len; ++i) {
6761 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6762 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6768 p = buf = g_malloc (buf_size);
6772 method = cfg->method_to_register;
6774 encode_method_ref (acfg, method, p, &p);
6776 g_assert ((p - buf) < buf_size);
6778 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6783 * Construct a chained hash table for mapping indexes in extra_method_info to
6786 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6787 table = g_ptr_array_sized_new (table_size);
6788 for (i = 0; i < table_size; ++i)
6789 g_ptr_array_add (table, NULL);
6790 chain_lengths = g_new0 (int, table_size);
6791 max_chain_length = 0;
6792 for (i = 0; i < acfg->extra_methods->len; ++i) {
6793 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6794 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6800 key = info_offsets [i];
6801 value = get_method_index (acfg, method);
6803 hash = mono_aot_method_hash (method) % table_size;
6805 chain_lengths [hash] ++;
6806 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6808 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6809 new_entry->key = key;
6810 new_entry->value = value;
6812 entry = g_ptr_array_index (table, hash);
6813 if (entry == NULL) {
6814 new_entry->index = hash;
6815 g_ptr_array_index (table, hash) = new_entry;
6818 entry = entry->next;
6820 entry->next = new_entry;
6821 new_entry->index = table->len;
6822 g_ptr_array_add (table, new_entry);
6826 //printf ("MAX: %d\n", max_chain_length);
6828 /* Emit the table */
6829 sprintf (symbol, "extra_method_table");
6830 emit_section_change (acfg, RODATA_SECT, 0);
6831 emit_alignment (acfg, 8);
6832 emit_label (acfg, symbol);
6834 emit_int32 (acfg, table_size);
6835 for (i = 0; i < table->len; ++i) {
6836 HashEntry *entry = g_ptr_array_index (table, i);
6838 if (entry == NULL) {
6839 emit_int32 (acfg, 0);
6840 emit_int32 (acfg, 0);
6841 emit_int32 (acfg, 0);
6843 //g_assert (entry->key > 0);
6844 emit_int32 (acfg, entry->key);
6845 emit_int32 (acfg, entry->value);
6847 emit_int32 (acfg, entry->next->index);
6849 emit_int32 (acfg, 0);
6854 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6855 * This is used by mono_aot_find_jit_info ().
6857 sprintf (symbol, "extra_method_info_offsets");
6858 emit_section_change (acfg, RODATA_SECT, 0);
6859 emit_alignment (acfg, 8);
6860 emit_label (acfg, symbol);
6862 emit_int32 (acfg, acfg->extra_methods->len);
6863 for (i = 0; i < acfg->extra_methods->len; ++i) {
6864 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6866 emit_int32 (acfg, get_method_index (acfg, method));
6867 emit_int32 (acfg, info_offsets [i]);
6872 emit_exception_info (MonoAotCompile *acfg)
6878 offsets = g_new0 (gint32, acfg->nmethods);
6879 for (i = 0; i < acfg->nmethods; ++i) {
6880 if (acfg->cfgs [i]) {
6881 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6882 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6888 sprintf (symbol, "ex_info_offsets");
6889 emit_section_change (acfg, RODATA_SECT, 1);
6890 emit_alignment (acfg, 8);
6891 emit_label (acfg, symbol);
6893 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6898 emit_unwind_info (MonoAotCompile *acfg)
6904 * The unwind info contains a lot of duplicates so we emit each unique
6905 * entry once, and only store the offset from the start of the table in the
6909 sprintf (symbol, "unwind_info");
6910 emit_section_change (acfg, RODATA_SECT, 1);
6911 emit_alignment (acfg, 8);
6912 emit_label (acfg, symbol);
6914 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6915 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6916 guint8 *unwind_info;
6917 guint32 unwind_info_len;
6921 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6924 encode_value (unwind_info_len, p, &p);
6925 emit_bytes (acfg, buf, p - buf);
6926 emit_bytes (acfg, unwind_info, unwind_info_len);
6928 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6933 emit_class_info (MonoAotCompile *acfg)
6939 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6940 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6941 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6943 sprintf (symbol, "class_info_offsets");
6944 emit_section_change (acfg, RODATA_SECT, 1);
6945 emit_alignment (acfg, 8);
6946 emit_label (acfg, symbol);
6948 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6952 typedef struct ClassNameTableEntry {
6953 guint32 token, index;
6954 struct ClassNameTableEntry *next;
6955 } ClassNameTableEntry;
6958 emit_class_name_table (MonoAotCompile *acfg)
6961 guint32 token, hash;
6966 ClassNameTableEntry *entry, *new_entry;
6969 * Construct a chained hash table for mapping class names to typedef tokens.
6971 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6972 table = g_ptr_array_sized_new (table_size);
6973 for (i = 0; i < table_size; ++i)
6974 g_ptr_array_add (table, NULL);
6975 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6976 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6977 klass = mono_class_get (acfg->image, token);
6979 mono_loader_clear_error ();
6982 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6983 hash = mono_metadata_str_hash (full_name) % table_size;
6986 /* FIXME: Allocate from the mempool */
6987 new_entry = g_new0 (ClassNameTableEntry, 1);
6988 new_entry->token = token;
6990 entry = g_ptr_array_index (table, hash);
6991 if (entry == NULL) {
6992 new_entry->index = hash;
6993 g_ptr_array_index (table, hash) = new_entry;
6996 entry = entry->next;
6998 entry->next = new_entry;
6999 new_entry->index = table->len;
7000 g_ptr_array_add (table, new_entry);
7004 /* Emit the table */
7005 sprintf (symbol, "class_name_table");
7006 emit_section_change (acfg, RODATA_SECT, 0);
7007 emit_alignment (acfg, 8);
7008 emit_label (acfg, symbol);
7010 /* FIXME: Optimize memory usage */
7011 g_assert (table_size < 65000);
7012 emit_int16 (acfg, table_size);
7013 g_assert (table->len < 65000);
7014 for (i = 0; i < table->len; ++i) {
7015 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7017 if (entry == NULL) {
7018 emit_int16 (acfg, 0);
7019 emit_int16 (acfg, 0);
7021 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7023 emit_int16 (acfg, entry->next->index);
7025 emit_int16 (acfg, 0);
7031 emit_image_table (MonoAotCompile *acfg)
7037 * The image table is small but referenced in a lot of places.
7038 * So we emit it at once, and reference its elements by an index.
7041 sprintf (symbol, "image_table");
7042 emit_section_change (acfg, RODATA_SECT, 1);
7043 emit_alignment (acfg, 8);
7044 emit_label (acfg, symbol);
7046 emit_int32 (acfg, acfg->image_table->len);
7047 for (i = 0; i < acfg->image_table->len; i++) {
7048 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7049 MonoAssemblyName *aname = &image->assembly->aname;
7051 /* FIXME: Support multi-module assemblies */
7052 g_assert (image->assembly->image == image);
7054 emit_string (acfg, image->assembly_name);
7055 emit_string (acfg, image->guid);
7056 emit_string (acfg, aname->culture ? aname->culture : "");
7057 emit_string (acfg, (const char*)aname->public_key_token);
7059 emit_alignment (acfg, 8);
7060 emit_int32 (acfg, aname->flags);
7061 emit_int32 (acfg, aname->major);
7062 emit_int32 (acfg, aname->minor);
7063 emit_int32 (acfg, aname->build);
7064 emit_int32 (acfg, aname->revision);
7069 emit_got_info (MonoAotCompile *acfg)
7072 int i, first_plt_got_patch, buf_size;
7074 guint32 *got_info_offsets;
7076 /* Add the patches needed by the PLT to the GOT */
7077 acfg->plt_got_offset_base = acfg->got_offset;
7078 first_plt_got_patch = acfg->got_patches->len;
7079 for (i = 1; i < acfg->plt_offset; ++i) {
7080 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7082 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7084 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7087 acfg->got_offset += acfg->plt_offset;
7091 * - optimize offsets table.
7092 * - reduce number of exported symbols.
7093 * - emit info for a klass only once.
7094 * - determine when a method uses a GOT slot which is guaranteed to be already
7096 * - clean up and document the code.
7097 * - use String.Empty in class libs.
7100 /* Encode info required to decode shared GOT entries */
7101 buf_size = acfg->got_patches->len * 128;
7102 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7103 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7104 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7106 if (acfg->plt_offset)
7107 acfg->plt_got_info_offsets [0] = 0;
7108 for (i = 0; i < acfg->got_patches->len; ++i) {
7109 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7114 encode_value (ji->type, p, &p);
7116 encode_patch (acfg, ji, p, &p);
7117 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7118 g_assert (p - buf <= buf_size);
7119 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7121 if (i >= first_plt_got_patch)
7122 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7123 acfg->stats.got_info_size += p - buf;
7126 /* Emit got_info_offsets table */
7127 sprintf (symbol, "got_info_offsets");
7128 emit_section_change (acfg, RODATA_SECT, 1);
7129 emit_alignment (acfg, 8);
7130 emit_label (acfg, symbol);
7132 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7133 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7137 emit_got (MonoAotCompile *acfg)
7142 /* Don't make GOT global so accesses to it don't need relocations */
7143 sprintf (symbol, "%s", acfg->got_symbol);
7144 emit_section_change (acfg, ".bss", 0);
7145 emit_alignment (acfg, 8);
7146 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7147 emit_label (acfg, symbol);
7148 if (acfg->got_offset > 0)
7149 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7151 sprintf (symbol, "got_end");
7152 emit_label (acfg, symbol);
7156 typedef struct GlobalsTableEntry {
7157 guint32 value, index;
7158 struct GlobalsTableEntry *next;
7159 } GlobalsTableEntry;
7162 emit_globals (MonoAotCompile *acfg)
7168 GlobalsTableEntry *entry, *new_entry;
7170 if (!acfg->aot_opts.static_link)
7174 * When static linking, we emit a table containing our globals.
7178 * Construct a chained hash table for mapping global names to their index in
7179 * the globals table.
7181 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7182 table = g_ptr_array_sized_new (table_size);
7183 for (i = 0; i < table_size; ++i)
7184 g_ptr_array_add (table, NULL);
7185 for (i = 0; i < acfg->globals->len; ++i) {
7186 char *name = g_ptr_array_index (acfg->globals, i);
7188 hash = mono_metadata_str_hash (name) % table_size;
7190 /* FIXME: Allocate from the mempool */
7191 new_entry = g_new0 (GlobalsTableEntry, 1);
7192 new_entry->value = i;
7194 entry = g_ptr_array_index (table, hash);
7195 if (entry == NULL) {
7196 new_entry->index = hash;
7197 g_ptr_array_index (table, hash) = new_entry;
7200 entry = entry->next;
7202 entry->next = new_entry;
7203 new_entry->index = table->len;
7204 g_ptr_array_add (table, new_entry);
7208 /* Emit the table */
7209 sprintf (symbol, ".Lglobals_hash");
7210 emit_section_change (acfg, RODATA_SECT, 0);
7211 emit_alignment (acfg, 8);
7212 emit_label (acfg, symbol);
7214 /* FIXME: Optimize memory usage */
7215 g_assert (table_size < 65000);
7216 emit_int16 (acfg, table_size);
7217 for (i = 0; i < table->len; ++i) {
7218 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7220 if (entry == NULL) {
7221 emit_int16 (acfg, 0);
7222 emit_int16 (acfg, 0);
7224 emit_int16 (acfg, entry->value + 1);
7226 emit_int16 (acfg, entry->next->index);
7228 emit_int16 (acfg, 0);
7232 /* Emit the names */
7233 for (i = 0; i < acfg->globals->len; ++i) {
7234 char *name = g_ptr_array_index (acfg->globals, i);
7236 sprintf (symbol, "name_%d", i);
7237 emit_section_change (acfg, RODATA_SECT, 1);
7239 emit_alignment (acfg, 4);
7241 emit_label (acfg, symbol);
7242 emit_string (acfg, name);
7245 /* Emit the globals table */
7246 sprintf (symbol, "globals");
7247 emit_section_change (acfg, ".data", 0);
7248 /* This is not a global, since it is accessed by the init function */
7249 emit_alignment (acfg, 8);
7250 emit_label (acfg, symbol);
7252 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7253 emit_pointer (acfg, symbol);
7255 for (i = 0; i < acfg->globals->len; ++i) {
7256 char *name = g_ptr_array_index (acfg->globals, i);
7258 sprintf (symbol, "name_%d", i);
7259 emit_pointer (acfg, symbol);
7261 sprintf (symbol, "%s", name);
7262 emit_pointer (acfg, symbol);
7264 /* Null terminate the table */
7265 emit_int32 (acfg, 0);
7266 emit_int32 (acfg, 0);
7270 emit_autoreg (MonoAotCompile *acfg)
7275 * Emit a function into the .ctor section which will be called by the ELF
7276 * loader to register this module with the runtime.
7278 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7281 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7283 arch_emit_autoreg (acfg, symbol);
7289 emit_mem_end (MonoAotCompile *acfg)
7293 sprintf (symbol, "mem_end");
7294 emit_section_change (acfg, ".text", 1);
7295 emit_alignment (acfg, 8);
7296 emit_label (acfg, symbol);
7300 * Emit a structure containing all the information not stored elsewhere.
7303 emit_file_info (MonoAotCompile *acfg)
7308 const char *gc_name;
7311 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7313 if (acfg->aot_opts.bind_to_runtime_version) {
7314 build_info = mono_get_runtime_build_info ();
7315 emit_string_symbol (acfg, "runtime_version", build_info);
7316 g_free (build_info);
7318 emit_string_symbol (acfg, "runtime_version", "");
7321 /* Emit a string holding the assembly name */
7322 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7325 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7328 gc_name = mono_gc_get_gc_name ();
7329 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7331 sprintf (symbol, "mono_aot_file_info");
7332 emit_section_change (acfg, ".data", 0);
7333 emit_alignment (acfg, 8);
7334 emit_label (acfg, symbol);
7335 if (!acfg->aot_opts.static_link)
7336 emit_global (acfg, symbol, FALSE);
7338 /* The data emitted here must match MonoAotFileInfo. */
7340 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7341 emit_int32 (acfg, 0);
7344 * We emit pointers to our data structures instead of emitting global symbols which
7345 * point to them, to reduce the number of globals, and because using globals leads to
7346 * various problems (i.e. arm/thumb).
7348 emit_pointer (acfg, acfg->got_symbol);
7349 emit_pointer (acfg, "methods");
7352 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7354 emit_pointer (acfg, "mono_eh_frame");
7356 emit_pointer (acfg, NULL);
7358 emit_pointer (acfg, "blob");
7359 emit_pointer (acfg, "class_name_table");
7360 emit_pointer (acfg, "class_info_offsets");
7361 emit_pointer (acfg, "method_info_offsets");
7362 emit_pointer (acfg, "ex_info_offsets");
7363 emit_pointer (acfg, "code_offsets");
7365 emit_pointer (acfg, "method_addresses");
7367 emit_pointer (acfg, "extra_method_info_offsets");
7368 emit_pointer (acfg, "extra_method_table");
7369 emit_pointer (acfg, "got_info_offsets");
7370 emit_pointer (acfg, "methods_end");
7371 emit_pointer (acfg, "unwind_info");
7372 emit_pointer (acfg, "mem_end");
7373 emit_pointer (acfg, "image_table");
7374 emit_pointer (acfg, "plt");
7375 emit_pointer (acfg, "plt_end");
7376 emit_pointer (acfg, "assembly_guid");
7377 emit_pointer (acfg, "runtime_version");
7378 if (acfg->num_trampoline_got_entries) {
7379 emit_pointer (acfg, "specific_trampolines");
7380 emit_pointer (acfg, "static_rgctx_trampolines");
7381 emit_pointer (acfg, "imt_thunks");
7382 emit_pointer (acfg, "gsharedvt_arg_trampolines");
7384 emit_pointer (acfg, NULL);
7385 emit_pointer (acfg, NULL);
7386 emit_pointer (acfg, NULL);
7387 emit_pointer (acfg, NULL);
7389 if (acfg->thumb_mixed) {
7390 emit_pointer (acfg, "thumb_end");
7392 emit_pointer (acfg, NULL);
7394 if (acfg->aot_opts.static_link) {
7395 emit_pointer (acfg, "globals");
7397 emit_pointer (acfg, NULL);
7399 emit_pointer (acfg, "assembly_name");
7400 emit_pointer (acfg, "unbox_trampolines");
7401 emit_pointer (acfg, "unbox_trampolines_end");
7403 emit_int32 (acfg, acfg->plt_got_offset_base);
7404 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7405 emit_int32 (acfg, acfg->plt_offset);
7406 emit_int32 (acfg, acfg->nmethods);
7407 emit_int32 (acfg, acfg->flags);
7408 emit_int32 (acfg, acfg->opts);
7409 emit_int32 (acfg, acfg->simd_opts);
7410 emit_int32 (acfg, gc_name_offset);
7412 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7413 emit_int32 (acfg, acfg->num_trampolines [i]);
7414 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7415 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7416 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7417 emit_int32 (acfg, acfg->trampoline_size [i]);
7419 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7424 memset (&t, 0, sizeof (MonoType));
7425 t.type = MONO_TYPE_R8;
7426 mono_type_size (&t, &align);
7428 emit_int32 (acfg, align);
7430 memset (&t, 0, sizeof (MonoType));
7431 t.type = MONO_TYPE_I8;
7432 mono_type_size (&t, &align);
7434 emit_int32 (acfg, align);
7437 emit_int32 (acfg, __alignof__ (double));
7438 emit_int32 (acfg, __alignof__ (gint64));
7441 if (acfg->aot_opts.static_link) {
7445 * Emit a global symbol which can be passed by an embedding app to
7446 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7449 #if defined(TARGET_MACH) && !defined(__native_client_codegen__)
7450 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7452 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
7455 /* Get rid of characters which cannot occur in symbols */
7457 for (p = symbol; *p; ++p) {
7458 if (!(isalnum (*p) || *p == '_'))
7461 acfg->static_linking_symbol = g_strdup (symbol);
7462 emit_global_inner (acfg, symbol, FALSE);
7463 emit_label (acfg, symbol);
7464 emit_pointer (acfg, "mono_aot_file_info");
7469 emit_blob (MonoAotCompile *acfg)
7473 sprintf (symbol, "blob");
7474 emit_section_change (acfg, RODATA_SECT, 1);
7475 emit_alignment (acfg, 8);
7476 emit_label (acfg, symbol);
7478 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7482 emit_dwarf_info (MonoAotCompile *acfg)
7484 #ifdef EMIT_DWARF_INFO
7488 /* DIEs for methods */
7489 for (i = 0; i < acfg->nmethods; ++i) {
7490 MonoCompile *cfg = acfg->cfgs [i];
7495 // FIXME: LLVM doesn't define .Lme_...
7496 if (cfg->compile_llvm)
7499 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7501 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_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 ()));
7507 collect_methods (MonoAotCompile *acfg)
7510 MonoImage *image = acfg->image;
7512 /* Collect methods */
7513 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7515 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7517 method = mono_get_method (acfg->image, token, NULL);
7520 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7524 /* Load all methods eagerly to skip the slower lazy loading code */
7525 mono_class_setup_methods (method->klass);
7527 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7528 /* Compile the wrapper instead */
7529 /* We do this here instead of add_wrappers () because it is easy to do it here */
7530 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7534 /* FIXME: Some mscorlib methods don't have debug info */
7536 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7537 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7538 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7539 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7540 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7541 if (!mono_debug_lookup_method (method)) {
7542 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7549 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7550 add_method_with_index (acfg, method, i, FALSE);
7551 acfg->method_index ++;
7554 /* gsharedvt methods */
7555 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
7557 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
7559 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
7562 method = mono_get_method (acfg->image, token, NULL);
7565 if (method->is_generic || method->klass->generic_container) {
7566 /* Create a vtype instantiation */
7567 MonoGenericContext shared_context;
7568 MonoGenericContext ctx;
7570 MonoGenericInst *inst;
7571 MonoMethod *inflated, *gshared;
7572 MonoGenericContainer *container;
7573 MonoClass **constraints;
7575 memset (&ctx, 0, sizeof (ctx));
7577 if (method->klass->generic_container) {
7578 shared_context = method->klass->generic_container->context;
7579 inst = shared_context.class_inst;
7581 args = g_new0 (MonoType*, inst->type_argc);
7582 for (i = 0; i < inst->type_argc; ++i) {
7583 args [i] = &mono_defaults.int_class->byval_arg;
7585 ctx.class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
7587 if (method->is_generic) {
7588 container = mono_method_get_generic_container (method);
7589 shared_context = container->context;
7590 inst = shared_context.method_inst;
7592 args = g_new0 (MonoType*, inst->type_argc);
7593 for (i = 0; i < container->type_argc; ++i) {
7594 MonoGenericParamInfo *info = &container->type_params [i].info;
7595 gboolean ref_only = FALSE;
7597 if (info && info->constraints) {
7598 constraints = info->constraints;
7600 while (*constraints) {
7601 MonoClass *cklass = *constraints;
7602 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
7603 /* Inflaring the method with our vtype would not be valid */
7610 args [i] = &mono_defaults.object_class->byval_arg;
7612 args [i] = &mono_defaults.int_class->byval_arg;
7614 ctx.method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
7617 inflated = mono_class_inflate_generic_method (method, &ctx);
7618 gshared = mini_get_shared_method_full (inflated, FALSE, TRUE);
7619 add_extra_method (acfg, gshared);
7623 add_generic_instances (acfg);
7625 if (acfg->aot_opts.full_aot)
7626 add_wrappers (acfg);
7630 compile_methods (MonoAotCompile *acfg)
7634 if (acfg->aot_opts.nthreads > 0) {
7639 gpointer *user_data;
7640 MonoMethod **methods;
7642 methods_len = acfg->methods->len;
7644 len = acfg->methods->len / acfg->aot_opts.nthreads;
7647 * Partition the list of methods into fragments, and hand it to threads to
7650 threads = g_ptr_array_new ();
7651 /* Make a copy since acfg->methods is modified by compile_method () */
7652 methods = g_new0 (MonoMethod*, methods_len);
7653 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7654 for (i = 0; i < methods_len; ++i)
7655 methods [i] = g_ptr_array_index (acfg->methods, i);
7657 while (i < methods_len) {
7658 frag = g_ptr_array_new ();
7659 for (j = 0; j < len; ++j) {
7660 if (i < methods_len) {
7661 g_ptr_array_add (frag, methods [i]);
7666 user_data = g_new0 (gpointer, 3);
7667 user_data [0] = mono_domain_get ();
7668 user_data [1] = acfg;
7669 user_data [2] = frag;
7671 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7672 g_ptr_array_add (threads, handle);
7676 for (i = 0; i < threads->len; ++i) {
7677 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7683 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7684 for (i = methods_len; i < acfg->methods->len; ++i) {
7685 /* This can new methods to acfg->methods */
7686 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7691 compile_asm (MonoAotCompile *acfg)
7693 char *command, *objfile;
7694 char *outfile_name, *tmp_outfile_name;
7695 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7697 #if defined(TARGET_AMD64)
7698 #define AS_OPTIONS "--64"
7699 #elif defined(TARGET_POWERPC64)
7700 #define AS_OPTIONS "-a64 -mppc64"
7701 #define LD_OPTIONS "-m elf64ppc"
7702 #elif defined(sparc) && SIZEOF_VOID_P == 8
7703 #define AS_OPTIONS "-xarch=v9"
7704 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7705 #define AS_OPTIONS "-arch i386 -W"
7707 #define AS_OPTIONS ""
7710 #ifdef __native_client_codegen__
7711 #if defined(TARGET_AMD64)
7712 #define AS_NAME "nacl64-as"
7714 #define AS_NAME "nacl-as"
7717 #define AS_NAME "as"
7721 #define LD_OPTIONS ""
7724 #define EH_LD_OPTIONS ""
7726 if (acfg->aot_opts.asm_only) {
7727 printf ("Output file: '%s'.\n", acfg->tmpfname);
7728 if (acfg->aot_opts.static_link)
7729 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7733 if (acfg->aot_opts.static_link) {
7734 if (acfg->aot_opts.outfile)
7735 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7737 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7739 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7741 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
7742 printf ("Executing the native assembler: %s\n", command);
7743 if (system (command) != 0) {
7751 if (acfg->aot_opts.static_link) {
7752 printf ("Output file: '%s'.\n", objfile);
7753 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7758 if (acfg->aot_opts.outfile)
7759 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7761 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7763 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7766 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7767 #elif defined(__ppc__) && defined(TARGET_MACH)
7768 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7769 #elif defined(HOST_WIN32)
7770 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7771 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7772 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7774 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7776 printf ("Executing the native linker: %s\n", command);
7777 if (system (command) != 0) {
7778 g_free (tmp_outfile_name);
7779 g_free (outfile_name);
7787 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7788 printf ("Stripping the binary: %s\n", com);
7792 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
7794 * gas generates 'mapping symbols' each time code and data is mixed, which
7795 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7797 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7798 printf ("Stripping the binary: %s\n", command);
7799 if (system (command) != 0) {
7800 g_free (tmp_outfile_name);
7801 g_free (outfile_name);
7808 rename (tmp_outfile_name, outfile_name);
7810 #if defined(TARGET_MACH)
7811 command = g_strdup_printf ("dsymutil %s", outfile_name);
7812 printf ("Generating debug symbols: %s\n", command);
7813 if (system (command) != 0) {
7818 if (!acfg->aot_opts.save_temps)
7821 g_free (tmp_outfile_name);
7822 g_free (outfile_name);
7825 if (acfg->aot_opts.save_temps)
7826 printf ("Retained input file.\n");
7828 unlink (acfg->tmpfname);
7833 static MonoAotCompile*
7834 acfg_create (MonoAssembly *ass, guint32 opts)
7836 MonoImage *image = ass->image;
7837 MonoAotCompile *acfg;
7840 acfg = g_new0 (MonoAotCompile, 1);
7841 acfg->methods = g_ptr_array_new ();
7842 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7843 acfg->method_depth = g_hash_table_new (NULL, NULL);
7844 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7845 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7846 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7847 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7848 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7849 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7850 acfg->got_patches = g_ptr_array_new ();
7851 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7852 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7853 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7854 acfg->image_hash = g_hash_table_new (NULL, NULL);
7855 acfg->image_table = g_ptr_array_new ();
7856 acfg->globals = g_ptr_array_new ();
7857 acfg->image = image;
7859 /* TODO: Write out set of SIMD instructions used, rather than just those available */
7860 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
7861 acfg->mempool = mono_mempool_new ();
7862 acfg->extra_methods = g_ptr_array_new ();
7863 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7864 acfg->unwind_ops = g_ptr_array_new ();
7865 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7866 acfg->method_order = g_ptr_array_new ();
7867 acfg->export_names = g_hash_table_new (NULL, NULL);
7868 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7869 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7870 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7871 InitializeCriticalSection (&acfg->mutex);
7877 acfg_free (MonoAotCompile *acfg)
7881 img_writer_destroy (acfg->w);
7882 for (i = 0; i < acfg->nmethods; ++i)
7884 g_free (acfg->cfgs [i]);
7885 g_free (acfg->cfgs);
7886 g_free (acfg->static_linking_symbol);
7887 g_free (acfg->got_symbol);
7888 g_free (acfg->plt_symbol);
7889 g_ptr_array_free (acfg->methods, TRUE);
7890 g_ptr_array_free (acfg->got_patches, TRUE);
7891 g_ptr_array_free (acfg->image_table, TRUE);
7892 g_ptr_array_free (acfg->globals, TRUE);
7893 g_ptr_array_free (acfg->unwind_ops, TRUE);
7894 g_hash_table_destroy (acfg->method_indexes);
7895 g_hash_table_destroy (acfg->method_depth);
7896 g_hash_table_destroy (acfg->plt_offset_to_entry);
7897 g_hash_table_destroy (acfg->patch_to_plt_entry);
7898 g_hash_table_destroy (acfg->patch_to_got_offset);
7899 g_hash_table_destroy (acfg->method_to_cfg);
7900 g_hash_table_destroy (acfg->token_info_hash);
7901 g_hash_table_destroy (acfg->method_to_pinvoke_import);
7902 g_hash_table_destroy (acfg->image_hash);
7903 g_hash_table_destroy (acfg->unwind_info_offsets);
7904 g_hash_table_destroy (acfg->method_label_hash);
7905 g_hash_table_destroy (acfg->export_names);
7906 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7907 g_hash_table_destroy (acfg->klass_blob_hash);
7908 g_hash_table_destroy (acfg->method_blob_hash);
7909 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7910 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7911 g_free (acfg->patch_to_got_offset_by_type);
7912 mono_mempool_destroy (acfg->mempool);
7917 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7919 MonoImage *image = ass->image;
7921 MonoAotCompile *acfg;
7922 char *outfile_name, *tmp_outfile_name, *p;
7926 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7928 acfg = acfg_create (ass, opts);
7930 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7931 acfg->aot_opts.write_symbols = TRUE;
7932 acfg->aot_opts.ntrampolines = 1024;
7933 acfg->aot_opts.nrgctx_trampolines = 1024;
7934 acfg->aot_opts.nimt_trampolines = 128;
7935 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
7936 acfg->aot_opts.llvm_path = g_strdup ("");
7938 acfg->aot_opts.use_trampolines_page = TRUE;
7941 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7943 if (acfg->aot_opts.static_link)
7944 acfg->aot_opts.autoreg = TRUE;
7946 //acfg->aot_opts.print_skipped_methods = TRUE;
7948 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7949 if (acfg->aot_opts.full_aot) {
7950 printf ("--aot=full is not supported on this platform.\n");
7955 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
7956 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
7960 if (acfg->aot_opts.static_link)
7961 acfg->aot_opts.asm_writer = TRUE;
7963 if (acfg->aot_opts.soft_debug) {
7964 MonoDebugOptions *opt = mini_get_debug_options ();
7966 opt->mdb_optimizations = TRUE;
7967 opt->gen_seq_points = TRUE;
7969 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7970 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7973 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7976 if (mono_use_llvm) {
7978 acfg->aot_opts.asm_writer = TRUE;
7979 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7981 if (acfg->aot_opts.soft_debug) {
7982 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7987 if (acfg->aot_opts.full_aot)
7988 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7990 load_profile_files (acfg);
7992 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7993 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7994 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7996 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7997 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
7998 if (acfg->opts & MONO_OPT_GSHAREDVT)
7999 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8002 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8006 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8007 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8008 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8010 /* Get rid of characters which cannot occur in symbols */
8011 for (p = acfg->got_symbol_base; *p; ++p) {
8012 if (!(isalnum (*p) || *p == '_'))
8015 for (p = acfg->plt_symbol; *p; ++p) {
8016 if (!(isalnum (*p) || *p == '_'))
8019 for (p = acfg->assembly_name_sym; *p; ++p) {
8020 if (!(isalnum (*p) || *p == '_'))
8024 acfg->method_index = 1;
8026 collect_methods (acfg);
8028 acfg->cfgs_size = acfg->methods->len + 32;
8029 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8031 /* PLT offset 0 is reserved for the PLT trampoline */
8032 acfg->plt_offset = 1;
8037 mono_llvm_create_aot_module (acfg->got_symbol_base);
8041 /* GOT offset 0 is reserved for the address of the current assembly */
8045 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8046 ji->type = MONO_PATCH_INFO_IMAGE;
8047 ji->data.image = acfg->image;
8049 get_got_offset (acfg, ji);
8051 /* Slot 1 is reserved for the mscorlib got addr */
8052 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8053 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8054 get_got_offset (acfg, ji);
8056 /* This is very common */
8057 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8058 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8059 get_got_offset (acfg, ji);
8064 compile_methods (acfg);
8068 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8074 if (acfg->aot_opts.asm_only) {
8075 if (acfg->aot_opts.outfile)
8076 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8078 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8080 acfg->tmpfname = g_strdup ("temp.s");
8083 emit_llvm_file (acfg);
8087 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8088 if (acfg->aot_opts.outfile)
8089 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8091 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8094 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8095 * it might be in another file system so the rename () won't work.
8097 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8099 acfg->fp = fopen (tmp_outfile_name, "w");
8101 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8105 acfg->w = img_writer_create (acfg->fp, TRUE);
8106 acfg->use_bin_writer = TRUE;
8109 /* Append to the .s file created by llvm */
8110 /* FIXME: Use multiple files instead */
8111 acfg->fp = fopen (acfg->tmpfname, "a+");
8113 if (acfg->aot_opts.asm_only) {
8114 if (acfg->aot_opts.outfile)
8115 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8117 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8118 acfg->fp = fopen (acfg->tmpfname, "w+");
8120 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8121 acfg->fp = fdopen (i, "w+");
8123 if (acfg->fp == 0) {
8124 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8128 acfg->w = img_writer_create (acfg->fp, FALSE);
8130 tmp_outfile_name = NULL;
8131 outfile_name = NULL;
8134 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8136 /* Compute symbols for methods */
8137 for (i = 0; i < acfg->nmethods; ++i) {
8138 if (acfg->cfgs [i]) {
8139 MonoCompile *cfg = acfg->cfgs [i];
8140 int method_index = get_method_index (acfg, cfg->orig_method);
8142 if (COMPILE_LLVM (cfg))
8143 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8144 else if (acfg->global_symbols)
8145 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8147 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8151 if (!acfg->aot_opts.nodebug)
8152 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
8154 img_writer_emit_start (acfg->w);
8157 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8159 if (acfg->thumb_mixed) {
8162 * This global symbol marks the end of THUMB code, and the beginning of ARM
8163 * code generated by our JIT.
8165 sprintf (symbol, "thumb_end");
8166 emit_section_change (acfg, ".text", 0);
8167 emit_alignment (acfg, 8);
8168 emit_label (acfg, symbol);
8169 emit_zero_bytes (acfg, 16);
8171 fprintf (acfg->fp, ".arm\n");
8178 emit_extra_methods (acfg);
8180 emit_trampolines (acfg);
8182 emit_class_name_table (acfg);
8184 emit_got_info (acfg);
8186 emit_exception_info (acfg);
8188 emit_unwind_info (acfg);
8190 emit_class_info (acfg);
8194 emit_image_table (acfg);
8198 emit_file_info (acfg);
8202 emit_globals (acfg);
8204 emit_autoreg (acfg);
8207 emit_dwarf_info (acfg);
8208 mono_dwarf_writer_close (acfg->dwarf);
8211 emit_mem_end (acfg);
8213 if (acfg->need_pt_gnu_stack) {
8214 /* This is required so the .so doesn't have an executable stack */
8215 /* The bin writer already emits this */
8216 if (!acfg->use_bin_writer)
8217 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8222 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8225 g_assert (acfg->got_offset <= acfg->final_got_size);
8227 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);
8228 printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8229 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8230 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8231 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8232 if (acfg->stats.genericcount)
8233 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8234 if (acfg->stats.abscount)
8235 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8236 if (acfg->stats.lmfcount)
8237 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8238 if (acfg->stats.ocount)
8239 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8241 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8244 res = img_writer_emit_writeout (acfg->w);
8249 if (acfg->use_bin_writer) {
8250 int err = rename (tmp_outfile_name, outfile_name);
8253 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8257 res = compile_asm (acfg);
8264 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8266 if (acfg->aot_opts.stats) {
8269 printf ("GOT slot distribution:\n");
8270 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8271 if (acfg->stats.got_slot_types [i])
8272 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8275 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);
8287 mono_aot_readonly_field_override (MonoClassField *field)
8293 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)