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"
74 #elif defined(TARGET_MACH)
75 #define RODATA_SECT ".section __TEXT, __const"
77 #define RODATA_SECT ".text"
80 #define TV_DECLARE(name) gint64 name
81 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
82 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
85 #define SHARED_EXT ".dll"
86 #elif defined(__ppc__) && defined(TARGET_MACH)
87 #define SHARED_EXT ".dylib"
88 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
89 #define SHARED_EXT ".dylib"
90 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
91 #define SHARED_EXT ".dylib"
93 #define SHARED_EXT ".so"
96 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
97 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
98 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
100 /* predefined values for static readonly fields without needed to run the .cctor */
101 typedef struct _ReadOnlyValue ReadOnlyValue;
102 struct _ReadOnlyValue {
105 int type; /* to be used later for typechecking to prevent user errors */
114 static ReadOnlyValue *readonly_values = NULL;
116 typedef struct MonoAotOptions {
119 gboolean write_symbols;
120 gboolean metadata_only;
121 gboolean bind_to_runtime_version;
124 gboolean static_link;
128 gboolean dwarf_debug;
130 gboolean log_generics;
131 gboolean direct_pinvoke;
132 gboolean direct_icalls;
133 gboolean no_direct_calls;
134 gboolean use_trampolines_page;
135 gboolean no_instances;
139 int nrgctx_trampolines;
140 int nimt_trampolines;
141 int ngsharedvt_arg_trampolines;
142 int nrgctx_fetch_trampolines;
143 gboolean print_skipped_methods;
151 typedef struct MonoAotStats {
152 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
153 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
154 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
155 int got_slots, offsets_size;
156 int got_slot_types [MONO_PATCH_INFO_NONE];
157 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
158 int jit_time, gen_time, link_time;
161 typedef struct MonoAotCompile {
164 GHashTable *method_indexes;
165 GHashTable *method_depth;
168 GHashTable *patch_to_plt_entry;
169 GHashTable *plt_offset_to_entry;
170 GHashTable *patch_to_got_offset;
171 GHashTable **patch_to_got_offset_by_type;
172 GPtrArray *got_patches;
173 GHashTable *image_hash;
174 GHashTable *method_to_cfg;
175 GHashTable *token_info_hash;
176 GHashTable *method_to_pinvoke_import;
177 GPtrArray *extra_methods;
178 GPtrArray *image_table;
180 GPtrArray *method_order;
181 GHashTable *export_names;
182 /* Maps MonoClass* -> blob offset */
183 GHashTable *klass_blob_hash;
184 /* Maps MonoMethod* -> blob offset */
185 GHashTable *method_blob_hash;
186 guint32 *plt_got_info_offsets;
187 guint32 got_offset, plt_offset, plt_got_offset_base;
188 guint32 final_got_size;
189 /* Number of GOT entries reserved for trampolines */
190 guint32 num_trampoline_got_entries;
192 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
193 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
194 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
196 MonoAotOptions aot_opts;
200 MonoMemPool *mempool;
203 char *static_linking_symbol;
204 CRITICAL_SECTION mutex;
205 gboolean use_bin_writer;
206 gboolean gas_line_numbers;
208 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
215 char *got_symbol_base;
218 GHashTable *method_label_hash;
219 const char *temp_prefix;
220 const char *user_symbol_prefix;
221 const char *llvm_label_prefix;
222 guint32 label_generator;
224 MonoAotFileFlags flags;
225 MonoDynamicStream blob;
226 MonoClass **typespec_classes;
229 char *assembly_name_sym;
230 GHashTable *plt_entry_debug_sym_cache;
231 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
232 GHashTable *ginst_hash;
233 GHashTable *dwarf_ln_filenames;
234 gboolean global_symbols;
235 gboolean direct_method_addresses;
240 char *symbol, *llvm_symbol, *debug_sym;
242 gboolean jit_used, llvm_used;
245 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
246 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
248 /* This points to the current acfg in LLVM mode */
249 static MonoAotCompile *llvm_acfg;
251 #ifdef HAVE_ARRAY_ELEM_INIT
252 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
253 #define MSGSTRFIELD1(line) str##line
254 static const struct msgstr_t {
255 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
256 #include "patch-info.h"
259 #define PATCH_INFO(a,b) b,
260 #include "patch-info.h"
263 static const gint16 opidx [] = {
264 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
265 #include "patch-info.h"
269 static G_GNUC_UNUSED const char*
270 get_patch_name (int info)
272 return (const char*)&opstr + opidx [info];
276 #define PATCH_INFO(a,b) b,
277 static const char* const
278 patch_types [MONO_PATCH_INFO_NUM + 1] = {
279 #include "patch-info.h"
283 static G_GNUC_UNUSED const char*
284 get_patch_name (int info)
286 return patch_types [info];
292 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
294 /* Wrappers around the image writer functions */
297 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
299 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
303 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
305 img_writer_emit_push_section (acfg->w, section_name, subsection);
309 emit_pop_section (MonoAotCompile *acfg)
311 img_writer_emit_pop_section (acfg->w);
315 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
317 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
321 emit_label (MonoAotCompile *acfg, const char *name)
323 img_writer_emit_label (acfg->w, name);
327 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
329 img_writer_emit_bytes (acfg->w, buf, size);
333 emit_string (MonoAotCompile *acfg, const char *value)
335 img_writer_emit_string (acfg->w, value);
339 emit_line (MonoAotCompile *acfg)
341 img_writer_emit_line (acfg->w);
345 emit_alignment (MonoAotCompile *acfg, int size)
347 img_writer_emit_alignment (acfg->w, size);
351 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
353 img_writer_emit_pointer_unaligned (acfg->w, target);
357 emit_pointer (MonoAotCompile *acfg, const char *target)
359 img_writer_emit_pointer (acfg->w, target);
363 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
365 if (prefix [0] != '\0') {
366 char *s = g_strdup_printf ("%s%s", prefix, target);
367 img_writer_emit_pointer (acfg->w, s);
370 img_writer_emit_pointer (acfg->w, target);
375 emit_int16 (MonoAotCompile *acfg, int value)
377 img_writer_emit_int16 (acfg->w, value);
381 emit_int32 (MonoAotCompile *acfg, int value)
383 img_writer_emit_int32 (acfg->w, value);
387 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
389 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
393 emit_zero_bytes (MonoAotCompile *acfg, int num)
395 img_writer_emit_zero_bytes (acfg->w, num);
399 emit_byte (MonoAotCompile *acfg, guint8 val)
401 img_writer_emit_byte (acfg->w, val);
404 #ifdef __native_client_codegen__
406 emit_nacl_call_alignment (MonoAotCompile *acfg)
408 img_writer_emit_nacl_call_alignment (acfg->w);
412 static G_GNUC_UNUSED void
413 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
415 img_writer_emit_global (acfg->w, name, func);
419 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
421 if (acfg->aot_opts.no_dlsym) {
422 g_ptr_array_add (acfg->globals, g_strdup (name));
423 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
425 img_writer_emit_global (acfg->w, name, func);
430 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
432 img_writer_emit_symbol_size (acfg->w, name, end_label);
436 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
438 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
440 /* On apple, all symbols need to be aligned to avoid warnings from ld */
441 emit_alignment (acfg, 4);
443 img_writer_emit_label (acfg->w, name);
444 img_writer_emit_string (acfg->w, value);
447 static G_GNUC_UNUSED void
448 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
451 guint8 b = value & 0x7f;
453 if (value != 0) /* more bytes to come */
459 static G_GNUC_UNUSED void
460 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
463 gboolean negative = (value < 0);
470 /* the following is unnecessary if the
471 * implementation of >>= uses an arithmetic rather
472 * than logical shift for a signed left operand
476 value |= - ((gint64)1 <<(size - 7));
477 /* sign bit of byte is second high order bit (0x40) */
478 if ((value == 0 && !(byte & 0x40)) ||
479 (value == -1 && (byte & 0x40)))
483 emit_byte (acfg, byte);
487 static G_GNUC_UNUSED void
488 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
493 guint8 b = value & 0x7f;
495 if (value != 0) /* more bytes to come */
503 static G_GNUC_UNUSED void
504 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
507 gboolean negative = (value < 0);
515 /* the following is unnecessary if the
516 * implementation of >>= uses an arithmetic rather
517 * than logical shift for a signed left operand
521 value |= - (1 <<(size - 7));
522 /* sign bit of byte is second high order bit (0x40) */
523 if ((value == 0 && !(byte & 0x40)) ||
524 (value == -1 && (byte & 0x40)))
535 emit_unset_mode (MonoAotCompile *acfg)
537 img_writer_emit_unset_mode (acfg->w);
540 static G_GNUC_UNUSED void
541 emit_set_thumb_mode (MonoAotCompile *acfg)
543 emit_unset_mode (acfg);
544 fprintf (acfg->fp, ".code 16\n");
547 static G_GNUC_UNUSED void
548 emit_set_arm_mode (MonoAotCompile *acfg)
550 emit_unset_mode (acfg);
551 fprintf (acfg->fp, ".code 32\n");
554 /* ARCHITECTURE SPECIFIC CODE */
556 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
557 #define EMIT_DWARF_INFO 1
560 #if defined(TARGET_ARM)
561 #define AOT_FUNC_ALIGNMENT 4
563 #define AOT_FUNC_ALIGNMENT 16
565 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
566 #undef AOT_FUNC_ALIGNMENT
567 #define AOT_FUNC_ALIGNMENT 32
570 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
571 #define PPC_LD_OP "ld"
572 #define PPC_LDX_OP "ldx"
574 #define PPC_LD_OP "lwz"
575 #define PPC_LDX_OP "lwzx"
579 #define AOT_TARGET_STR "AMD64"
584 #define AOT_TARGET_STR "ARM (MACH)"
586 #define AOT_TARGET_STR "ARM (!MACH)"
590 #ifdef TARGET_POWERPC64
591 #ifdef __mono_ilp32__
592 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
594 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
597 #ifdef TARGET_POWERPC
598 #ifdef __mono_ilp32__
599 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
601 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
608 #define AOT_TARGET_STR "X86 (WIN32)"
609 #elif defined(__native_client_codegen__)
610 #define AOT_TARGET_STR "X86 (native client codegen)"
612 #define AOT_TARGET_STR "X86 (!native client codegen)"
616 #ifndef AOT_TARGET_STR
617 #define AOT_TARGET_STR ""
621 arch_init (MonoAotCompile *acfg)
623 acfg->llc_args = g_string_new ("");
624 acfg->as_args = g_string_new ("");
627 * The prefix LLVM likes to put in front of symbol names on darwin.
628 * The mach-os specs require this for globals, but LLVM puts them in front of all
629 * symbols. We need to handle this, since we need to refer to LLVM generated
632 acfg->llvm_label_prefix = "";
633 acfg->user_symbol_prefix = "";
635 #if defined(TARGET_AMD64) && defined(TARGET_MACH)
636 /* osx contains an old as which doesn't support avx opcodes */
637 g_string_append (acfg->llc_args, "-mattr=-avx");
641 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
642 g_string_append (acfg->llc_args, "-mattr=+v6");
645 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
646 g_string_append (acfg->as_args, " -mfpu=vfp3");
648 g_string_append (acfg->llc_args, " -soft-float");
651 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
652 acfg->thumb_mixed = TRUE;
654 if (acfg->aot_opts.mtriple)
655 mono_arch_set_target (acfg->aot_opts.mtriple);
659 acfg->user_symbol_prefix = "_";
660 acfg->llvm_label_prefix = "_";
661 acfg->need_no_dead_strip = TRUE;
662 acfg->aot_opts.gnu_asm = TRUE;
665 #if defined(__linux__) && !defined(TARGET_ARM)
666 acfg->need_pt_gnu_stack = TRUE;
670 acfg->direct_method_addresses = TRUE;
671 acfg->global_symbols = TRUE;
676 * arch_emit_direct_call:
678 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
682 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, int *call_size)
684 #if defined(TARGET_X86) || defined(TARGET_AMD64)
685 /* Need to make sure this is exactly 5 bytes long */
686 if (external && !acfg->use_bin_writer) {
687 emit_unset_mode (acfg);
688 fprintf (acfg->fp, "call %s\n", target);
690 emit_byte (acfg, '\xe8');
691 emit_symbol_diff (acfg, target, ".", -4);
694 #elif defined(TARGET_ARM)
695 if (acfg->use_bin_writer) {
702 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
703 emit_bytes (acfg, buf, 4);
705 emit_unset_mode (acfg);
706 fprintf (acfg->fp, "bl %s\n", target);
709 #elif defined(TARGET_POWERPC)
710 if (acfg->use_bin_writer) {
711 g_assert_not_reached ();
713 emit_unset_mode (acfg);
714 fprintf (acfg->fp, "bl %s\n", target);
718 g_assert_not_reached ();
724 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
726 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
727 * in in the 2. slot of every GOT, and require every method to place the GOT
728 * address in r30, even when it doesn't access the GOT otherwise. This way,
729 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
734 * PPC64 uses function descriptors which greatly complicate all code, since
735 * these are used very inconsistently in the runtime. Some functions like
736 * mono_compile_method () return ftn descriptors, while others like the
737 * trampoline creation functions do not.
738 * We assume that all GOT slots contain function descriptors, and create
739 * descriptors in aot-runtime.c when needed.
740 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
741 * from function descriptors, we could do the same, but it would require
742 * rewriting all the ppc/aot code to handle function descriptors properly.
743 * So instead, we use the same approach as on PPC32.
744 * This is a horrible mess, but fixing it would probably lead to an even bigger
750 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
753 #ifdef MONO_ARCH_AOT_SUPPORTED
755 * arch_emit_got_offset:
757 * The memory pointed to by CODE should hold native code for computing the GOT
758 * address. Emit this code while patching it with the offset between code and
759 * the GOT. CODE_SIZE is set to the number of bytes emitted.
762 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
764 #if defined(TARGET_POWERPC64)
765 g_assert (!acfg->use_bin_writer);
766 emit_unset_mode (acfg);
768 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
769 * unsupported relocations. So we store the got address into the .Lgot_addr
770 * symbol which is in the text segment, compute its address, and load it.
772 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
773 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
774 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
775 fprintf (acfg->fp, "add 30, 30, 0\n");
776 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
777 acfg->label_generator ++;
779 #elif defined(TARGET_POWERPC)
780 g_assert (!acfg->use_bin_writer);
781 emit_unset_mode (acfg);
782 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
783 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
784 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
785 acfg->label_generator ++;
788 guint32 offset = mono_arch_get_patch_offset (code);
789 emit_bytes (acfg, code, offset);
790 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
792 *code_size = offset + 4;
797 * arch_emit_got_access:
799 * The memory pointed to by CODE should hold native code for loading a GOT
800 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
801 * CODE_SIZE is set to the number of bytes emitted.
804 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
806 /* Emit beginning of instruction */
807 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
809 /* Emit the offset */
811 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
812 *code_size = mono_arch_get_patch_offset (code) + 4;
813 #elif defined(TARGET_X86)
814 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
815 *code_size = mono_arch_get_patch_offset (code) + 4;
816 #elif defined(TARGET_ARM)
817 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
818 *code_size = mono_arch_get_patch_offset (code) + 4;
819 #elif defined(TARGET_POWERPC)
825 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
826 g_assert (code - buf == 8);
827 emit_bytes (acfg, buf, code - buf);
828 *code_size = code - buf;
831 g_assert_not_reached ();
838 * arch_emit_plt_entry:
840 * Emit code for the PLT entry with index INDEX.
843 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
845 #if defined(TARGET_X86)
846 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
847 #if defined(__default_codegen__)
848 /* jmp *<offset>(%ebx) */
849 emit_byte (acfg, 0xff);
850 emit_byte (acfg, 0xa3);
851 emit_int32 (acfg, offset);
852 /* Used by mono_aot_get_plt_info_offset */
853 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
854 #elif defined(__native_client_codegen__)
855 const guint8 kSizeOfNaClJmp = 11;
856 guint8 bytes[kSizeOfNaClJmp];
857 guint8 *pbytes = &bytes[0];
859 x86_jump_membase32 (pbytes, X86_EBX, offset);
860 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
861 /* four bytes of data, used by mono_arch_patch_plt_entry */
862 /* For Native Client, make this work with data embedded in push. */
863 emit_byte (acfg, 0x68); /* hide data in a push */
864 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
865 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
866 #endif /*__native_client_codegen__*/
867 #elif defined(TARGET_AMD64)
868 #if defined(__default_codegen__)
870 * We can't emit jumps because they are 32 bits only so they can't be patched.
871 * So we make indirect calls through GOT entries which are patched by the AOT
872 * loader to point to .Lpd entries.
874 /* jmpq *<offset>(%rip) */
875 emit_byte (acfg, '\xff');
876 emit_byte (acfg, '\x25');
877 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
878 /* Used by mono_aot_get_plt_info_offset */
879 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
880 #elif defined(__native_client_codegen__)
882 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
883 guint8 *code = buf_aligned;
885 /* mov <OFFSET>(%rip), %r11d */
886 emit_byte (acfg, '\x45');
887 emit_byte (acfg, '\x8b');
888 emit_byte (acfg, '\x1d');
889 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
891 amd64_jump_reg (code, AMD64_R11);
892 /* This should be constant for the plt patch */
893 g_assert ((size_t)(code-buf_aligned) == 10);
894 emit_bytes (acfg, buf_aligned, code - buf_aligned);
896 /* Hide data in a push imm32 so it passes validation */
897 emit_byte (acfg, 0x68); /* push */
898 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
899 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
900 #endif /*__native_client_codegen__*/
901 #elif defined(TARGET_ARM)
906 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
907 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
908 emit_bytes (acfg, buf, code - buf);
909 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
910 /* Used by mono_aot_get_plt_info_offset */
911 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
912 #elif defined(TARGET_POWERPC)
913 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
915 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
916 g_assert (!acfg->use_bin_writer);
917 emit_unset_mode (acfg);
918 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
919 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
920 fprintf (acfg->fp, "add 11, 11, 30\n");
921 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
922 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
923 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
924 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
926 fprintf (acfg->fp, "mtctr 11\n");
927 fprintf (acfg->fp, "bctr\n");
928 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
930 g_assert_not_reached ();
935 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
937 #if defined(TARGET_ARM)
939 /* LLVM calls the PLT entries using bl, so emit a stub */
940 /* FIXME: Too much overhead on every call */
941 fprintf (acfg->fp, ".thumb_func\n");
942 fprintf (acfg->fp, "bx pc\n");
943 fprintf (acfg->fp, "nop\n");
944 fprintf (acfg->fp, ".arm\n");
946 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
947 /* The caller already transitioned to thumb */
948 /* The code below should be 12 bytes long */
949 /* clang has trouble encoding these instructions, so emit the binary */
951 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
952 /* thumb can't encode ld pc, [pc, ip] */
953 fprintf (acfg->fp, "add ip, pc, ip\n");
954 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
955 fprintf (acfg->fp, "bx ip\n");
957 emit_set_thumb_mode (acfg);
958 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
959 fprintf (acfg->fp, ".2byte 0x44fc\n");
960 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
961 fprintf (acfg->fp, ".2byte 0x4760\n");
962 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
963 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
964 emit_unset_mode (acfg);
965 emit_set_arm_mode (acfg);
967 g_assert_not_reached ();
972 * arch_emit_specific_trampoline_pages:
974 * Emits a page full of trampolines: each trampoline uses its own address to
975 * lookup both the generic trampoline code and the data argument.
976 * This page can be remapped in process multiple times so we can get an
977 * unlimited number of trampolines.
978 * Specifically this implementation uses the following trick: two memory pages
979 * are allocated, with the first containing the data and the second containing the trampolines.
980 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
981 * implementation does all the lifting.
982 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
983 * on the arm 32 bit system.
986 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
988 #if defined(TARGET_ARM)
991 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
993 #define COMMON_TRAMP_SIZE 16
994 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
995 int imm8, rot_amount;
998 if (!acfg->aot_opts.use_trampolines_page)
1001 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1002 emit_alignment (acfg, mono_pagesize ());
1003 emit_global (acfg, symbol, TRUE);
1004 emit_label (acfg, symbol);
1006 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1008 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1009 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1010 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1011 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1013 g_assert (code - buf == COMMON_TRAMP_SIZE);
1016 emit_bytes (acfg, buf, code - buf);
1018 for (i = 0; i < count; ++i) {
1020 ARM_PUSH (code, 0x5fff);
1022 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1023 g_assert (code - buf == 8);
1024 emit_bytes (acfg, buf, code - buf);
1027 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1028 * the instruction pointer address, so the generic trampoline at the start of the page
1029 * subtracts 4096 to get to the data page and loads the values
1030 * We again fit the generic trampiline in 16 bytes.
1032 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1033 emit_global (acfg, symbol, TRUE);
1034 emit_label (acfg, symbol);
1036 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1037 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1038 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1039 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1041 g_assert (code - buf == COMMON_TRAMP_SIZE);
1044 emit_bytes (acfg, buf, code - buf);
1046 for (i = 0; i < count; ++i) {
1048 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1050 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1051 g_assert (code - buf == 8);
1052 emit_bytes (acfg, buf, code - buf);
1056 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1058 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1059 emit_global (acfg, symbol, TRUE);
1060 emit_label (acfg, symbol);
1062 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1063 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1064 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1065 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1066 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1067 g_assert (code - buf == COMMON_TRAMP_SIZE);
1069 emit_bytes (acfg, buf, code - buf);
1071 for (i = 0; i < count; ++i) {
1073 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1075 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1076 g_assert (code - buf == 8);
1077 emit_bytes (acfg, buf, code - buf);
1080 /* now the imt trampolines: each specific trampolines puts in the ip register
1081 * the instruction pointer address, so the generic trampoline at the start of the page
1082 * subtracts 4096 to get to the data page and loads the values
1083 * We again fit the generic trampiline in 16 bytes.
1085 #define IMT_TRAMP_SIZE 72
1086 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1087 emit_global (acfg, symbol, TRUE);
1088 emit_label (acfg, symbol);
1090 /* Need at least two free registers, plus a slot for storing the pc */
1091 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1093 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1094 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1095 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1097 /* The IMT method is in v5, r0 has the imt array address */
1100 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1101 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1102 imt_found_check = code;
1103 ARM_B_COND (code, ARMCOND_EQ, 0);
1105 /* End-of-loop check */
1106 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1107 loop_end_check = code;
1108 ARM_B_COND (code, ARMCOND_EQ, 0);
1111 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1112 loop_branch_back = code;
1114 arm_patch (loop_branch_back, loop_start);
1117 arm_patch (imt_found_check, code);
1118 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1119 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1120 /* Save it to the third stack slot */
1121 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1122 /* Restore the registers and branch */
1123 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1126 arm_patch (loop_end_check, code);
1127 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1128 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1129 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1133 g_assert (code - buf == IMT_TRAMP_SIZE);
1134 emit_bytes (acfg, buf, code - buf);
1136 for (i = 0; i < count; ++i) {
1138 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1140 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1141 g_assert (code - buf == 8);
1142 emit_bytes (acfg, buf, code - buf);
1148 * arch_emit_specific_trampoline:
1150 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1151 * two GOT slots which contain the generic trampoline address and the trampoline
1152 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1155 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1158 * The trampolines created here are variations of the specific
1159 * trampolines created in mono_arch_create_specific_trampoline (). The
1161 * - the generic trampoline address is taken from a got slot.
1162 * - the offset of the got slot where the trampoline argument is stored
1163 * is embedded in the instruction stream, and the generic trampoline
1164 * can load the argument by loading the offset, adding it to the
1165 * address of the trampoline to get the address of the got slot, and
1166 * loading the argument from there.
1167 * - all the trampolines should be of the same length.
1169 #if defined(TARGET_AMD64)
1170 #if defined(__default_codegen__)
1171 /* This should be exactly 16 bytes long */
1173 /* call *<offset>(%rip) */
1174 emit_byte (acfg, '\x41');
1175 emit_byte (acfg, '\xff');
1176 emit_byte (acfg, '\x15');
1177 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1178 /* This should be relative to the start of the trampoline */
1179 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1180 emit_zero_bytes (acfg, 5);
1181 #elif defined(__native_client_codegen__)
1183 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1184 guint8 *code = buf_aligned;
1189 /* Emit this call in 'code' so we can find out how long it is. */
1190 amd64_call_reg (code, AMD64_R11);
1191 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1192 call_len = code - call_start;
1194 /* The tramp_size is twice the NaCl alignment because it starts with */
1195 /* a call which needs to be aligned to the end of the boundary. */
1196 *tramp_size = kNaClAlignment*2;
1198 /* Emit nops to align call site below which is 7 bytes plus */
1199 /* the length of the call sequence emitted above. */
1200 /* Note: this requires the specific trampoline starts on a */
1201 /* kNaclAlignedment aligned address, which it does because */
1202 /* it's its own function that is aligned. */
1203 guint8 nop_buf[256];
1204 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1205 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1206 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1208 /* The trampoline is stored at the offset'th pointer, the -4 is */
1209 /* present because RIP relative addressing starts at the end of */
1210 /* the current instruction, while the label "." is relative to */
1211 /* the beginning of the current asm location, which in this case */
1212 /* is not the mov instruction, but the offset itself, due to the */
1213 /* way the bytes and ints are emitted here. */
1214 got_offset = (offset * sizeof(gpointer)) - 4;
1216 /* mov <OFFSET>(%rip), %r11d */
1217 emit_byte (acfg, '\x45');
1218 emit_byte (acfg, '\x8b');
1219 emit_byte (acfg, '\x1d');
1220 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1223 emit_bytes (acfg, call_start, call_len);
1225 /* The arg is stored at the offset+1 pointer, relative to beginning */
1226 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1227 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1229 /* We can't emit this data directly, hide in a "push imm32" */
1230 emit_byte (acfg, '\x68'); /* push */
1231 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1232 emit_alignment (acfg, kNaClAlignment);
1233 #endif /*__native_client_codegen__*/
1234 #elif defined(TARGET_ARM)
1238 /* This should be exactly 20 bytes long */
1241 ARM_PUSH (code, 0x5fff);
1242 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1243 /* Load the value from the GOT */
1244 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1246 ARM_BLX_REG (code, ARMREG_R1);
1248 g_assert (code - buf == 16);
1251 emit_bytes (acfg, buf, code - buf);
1253 * Only one offset is needed, since the second one would be equal to the
1256 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1257 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1258 #elif defined(TARGET_POWERPC)
1265 g_assert (!acfg->use_bin_writer);
1268 * PPC has no ip relative addressing, so we need to compute the address
1269 * of the mscorlib got. That is slow and complex, so instead, we store it
1270 * in the second got slot of every aot image. The caller already computed
1271 * the address of its got and placed it into r30.
1273 emit_unset_mode (acfg);
1274 /* Load mscorlib got address */
1275 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1276 /* Load generic trampoline address */
1277 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1278 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1279 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1280 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1281 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1283 fprintf (acfg->fp, "mtctr 11\n");
1284 /* Load trampoline argument */
1285 /* On ppc, we pass it normally to the generic trampoline */
1286 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1287 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1288 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1289 /* Branch to generic trampoline */
1290 fprintf (acfg->fp, "bctr\n");
1292 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1293 *tramp_size = 10 * 4;
1295 *tramp_size = 9 * 4;
1297 #elif defined(TARGET_X86)
1301 /* Similar to the PPC code above */
1303 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1305 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1306 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1307 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1311 /* Load mscorlib got address */
1312 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1313 /* Push trampoline argument */
1314 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1315 /* Load generic trampoline address */
1316 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1317 /* Branch to generic trampoline */
1318 x86_jump_reg (code, X86_ECX);
1320 #ifdef __native_client_codegen__
1322 /* emit nops to next 32 byte alignment */
1323 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1324 while (code < (buf + a)) x86_nop(code);
1327 emit_bytes (acfg, buf, code - buf);
1329 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1330 g_assert (code - buf == *tramp_size);
1332 g_assert_not_reached ();
1337 * arch_emit_unbox_trampoline:
1339 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1340 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1343 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1345 #if defined(TARGET_AMD64)
1350 this_reg = mono_arch_get_this_arg_reg (NULL);
1352 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1354 emit_bytes (acfg, buf, code - buf);
1356 emit_byte (acfg, '\xe9');
1357 emit_symbol_diff (acfg, call_target, ".", -4);
1358 #elif defined(TARGET_X86)
1365 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1367 emit_bytes (acfg, buf, code - buf);
1370 emit_byte (acfg, '\xe9');
1371 emit_symbol_diff (acfg, call_target, ".", -4);
1372 #elif defined(TARGET_ARM)
1376 if (acfg->thumb_mixed && cfg->compile_llvm) {
1377 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1378 fprintf (acfg->fp, "b %s\n", call_target);
1379 fprintf (acfg->fp, ".arm\n");
1380 fprintf (acfg->fp, ".align 2\n");
1386 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1388 emit_bytes (acfg, buf, code - buf);
1389 /* jump to method */
1390 if (acfg->use_bin_writer) {
1397 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1398 emit_bytes (acfg, buf, 4);
1400 if (acfg->thumb_mixed && cfg->compile_llvm)
1401 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1403 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1405 #elif defined(TARGET_POWERPC)
1408 g_assert (!acfg->use_bin_writer);
1410 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1411 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1413 g_assert_not_reached ();
1418 * arch_emit_static_rgctx_trampoline:
1420 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1421 * two GOT slots which contain the rgctx argument, and the method to jump to.
1422 * TRAMP_SIZE is set to the size of the emitted trampoline.
1423 * These kinds of trampolines cannot be enumerated statically, since there could
1424 * be one trampoline per method instantiation, so we emit the same code for all
1425 * trampolines, and parameterize them using two GOT slots.
1428 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1430 #if defined(TARGET_AMD64)
1431 #if defined(__default_codegen__)
1432 /* This should be exactly 13 bytes long */
1435 /* mov <OFFSET>(%rip), %r10 */
1436 emit_byte (acfg, '\x4d');
1437 emit_byte (acfg, '\x8b');
1438 emit_byte (acfg, '\x15');
1439 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1441 /* jmp *<offset>(%rip) */
1442 emit_byte (acfg, '\xff');
1443 emit_byte (acfg, '\x25');
1444 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1445 #elif defined(__native_client_codegen__)
1447 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1448 guint8 *code = buf_aligned;
1450 /* mov <OFFSET>(%rip), %r10d */
1451 emit_byte (acfg, '\x45');
1452 emit_byte (acfg, '\x8b');
1453 emit_byte (acfg, '\x15');
1454 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1456 /* mov <OFFSET>(%rip), %r11d */
1457 emit_byte (acfg, '\x45');
1458 emit_byte (acfg, '\x8b');
1459 emit_byte (acfg, '\x1d');
1460 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1463 amd64_jump_reg (code, AMD64_R11);
1464 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1466 emit_alignment (acfg, kNaClAlignment);
1467 *tramp_size = kNaClAlignment;
1468 #endif /*__native_client_codegen__*/
1470 #elif defined(TARGET_ARM)
1474 /* This should be exactly 24 bytes long */
1477 /* Load rgctx value */
1478 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1479 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1480 /* Load branch addr + branch */
1481 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1482 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1484 g_assert (code - buf == 16);
1487 emit_bytes (acfg, buf, code - buf);
1488 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1489 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1490 #elif defined(TARGET_POWERPC)
1497 g_assert (!acfg->use_bin_writer);
1500 * PPC has no ip relative addressing, so we need to compute the address
1501 * of the mscorlib got. That is slow and complex, so instead, we store it
1502 * in the second got slot of every aot image. The caller already computed
1503 * the address of its got and placed it into r30.
1505 emit_unset_mode (acfg);
1506 /* Load mscorlib got address */
1507 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1509 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1510 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1511 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1512 /* Load target address */
1513 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1514 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1515 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1516 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1517 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1518 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1520 fprintf (acfg->fp, "mtctr 11\n");
1521 /* Branch to the target address */
1522 fprintf (acfg->fp, "bctr\n");
1524 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1525 *tramp_size = 11 * 4;
1527 *tramp_size = 9 * 4;
1530 #elif defined(TARGET_X86)
1534 /* Similar to the PPC code above */
1536 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1539 /* Load mscorlib got address */
1540 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1542 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1543 /* Branch to the target address */
1544 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1546 #ifdef __native_client_codegen__
1548 /* emit nops to next 32 byte alignment */
1549 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1550 while (code < (buf + a)) x86_nop(code);
1554 emit_bytes (acfg, buf, code - buf);
1556 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1557 g_assert (code - buf == *tramp_size);
1559 g_assert_not_reached ();
1564 * arch_emit_imt_thunk:
1566 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1567 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1568 * key is the IMT key, and ptr holds the address of a memory location holding
1569 * the address to branch to if the IMT arg matches the key. The array is
1570 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1572 * TRAMP_SIZE is set to the size of the emitted trampoline.
1575 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1577 #if defined(TARGET_AMD64)
1579 #if defined(__native_client_codegen__)
1582 guint8 *labels [16];
1584 guint8 *mov_buf_ptr = mov_buf;
1586 const int kSizeOfMove = 7;
1587 #if defined(__default_codegen__)
1588 code = buf = g_malloc (256);
1589 #elif defined(__native_client_codegen__)
1590 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1591 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1592 /* The RIP relative move below is emitted first */
1597 /* FIXME: Optimize this, i.e. use binary search etc. */
1598 /* Maybe move the body into a separate function (slower, but much smaller) */
1600 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1603 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1605 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1608 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1610 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1613 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1614 amd64_jump_code (code, labels [0]);
1617 mono_amd64_patch (labels [2], code);
1618 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1619 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1622 mono_amd64_patch (labels [1], code);
1623 /* Load fail tramp */
1624 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1625 /* Check if there is a fail tramp */
1626 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1628 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1629 /* Jump to fail tramp */
1630 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1633 mono_amd64_patch (labels [3], code);
1634 x86_breakpoint (code);
1636 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1637 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1638 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1639 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1640 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1641 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1643 emit_bytes (acfg, buf, code - buf);
1645 *tramp_size = code - buf + kSizeOfMove;
1646 #if defined(__native_client_codegen__)
1647 /* The tramp will be padded to the next kNaClAlignment bundle. */
1648 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1651 #if defined(__default_codegen__)
1653 #elif defined(__native_client_codegen__)
1657 #elif defined(TARGET_X86)
1659 #ifdef __native_client_codegen__
1662 guint8 *labels [16];
1664 #if defined(__default_codegen__)
1665 code = buf = g_malloc (256);
1666 #elif defined(__native_client_codegen__)
1667 buf_alloc = g_malloc (256 + kNaClAlignment);
1668 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1671 /* Allocate a temporary stack slot */
1672 x86_push_reg (code, X86_EAX);
1674 x86_push_reg (code, X86_EAX);
1676 /* Load mscorlib got address */
1677 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1679 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1682 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1684 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1687 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1689 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1692 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1693 x86_jump_code (code, labels [0]);
1696 mono_x86_patch (labels [2], code);
1697 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1698 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1699 /* Save the target address to the temporary stack location */
1700 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1702 x86_pop_reg (code, X86_EAX);
1703 /* Jump to the target address */
1707 mono_x86_patch (labels [1], code);
1708 /* Load fail tramp */
1709 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1710 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1712 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1713 /* Jump to fail tramp */
1714 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1715 x86_pop_reg (code, X86_EAX);
1719 mono_x86_patch (labels [3], code);
1720 x86_breakpoint (code);
1722 #ifdef __native_client_codegen__
1724 /* emit nops to next 32 byte alignment */
1725 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1726 while (code < (buf + a)) x86_nop(code);
1729 emit_bytes (acfg, buf, code - buf);
1731 *tramp_size = code - buf;
1733 #if defined(__default_codegen__)
1735 #elif defined(__native_client_codegen__)
1739 #elif defined(TARGET_ARM)
1741 guint8 *code, *code2, *labels [16];
1745 /* The IMT method is in v5 */
1747 /* Need at least two free registers, plus a slot for storing the pc */
1748 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1750 /* Load the parameter from the GOT */
1751 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1752 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1755 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1756 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1758 ARM_B_COND (code, ARMCOND_EQ, 0);
1760 /* End-of-loop check */
1761 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1763 ARM_B_COND (code, ARMCOND_EQ, 0);
1766 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1769 arm_patch (labels [4], labels [1]);
1772 arm_patch (labels [2], code);
1773 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1774 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1775 /* Save it to the third stack slot */
1776 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1777 /* Restore the registers and branch */
1778 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1781 arm_patch (labels [3], code);
1782 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1783 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1784 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1788 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1790 emit_bytes (acfg, buf, code - buf);
1791 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1793 *tramp_size = code - buf + 4;
1794 #elif defined(TARGET_POWERPC)
1796 guint8 *code, *labels [16];
1800 /* Load the mscorlib got address */
1801 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1802 /* Load the parameter from the GOT */
1803 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1804 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1806 /* Load and check key */
1808 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1809 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1811 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1813 /* End-of-loop check */
1814 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1816 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1819 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1822 mono_ppc_patch (labels [4], labels [1]);
1825 mono_ppc_patch (labels [2], code);
1826 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1827 /* r11 now contains the value of the vtable slot */
1828 /* this is not a function descriptor on ppc64 */
1829 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1830 ppc_mtctr (code, ppc_r11);
1831 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1834 mono_ppc_patch (labels [3], code);
1838 *tramp_size = code - buf;
1840 emit_bytes (acfg, buf, code - buf);
1842 g_assert_not_reached ();
1847 * arch_emit_gsharedvt_arg_trampoline:
1849 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1850 * two GOT slots which contain the argument, and the code to jump to.
1851 * TRAMP_SIZE is set to the size of the emitted trampoline.
1852 * These kinds of trampolines cannot be enumerated statically, since there could
1853 * be one trampoline per method instantiation, so we emit the same code for all
1854 * trampolines, and parameterize them using two GOT slots.
1857 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1859 #if defined(TARGET_X86)
1863 /* Similar to the PPC code above */
1865 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1868 /* Load mscorlib got address */
1869 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1871 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1872 /* Branch to the target address */
1873 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1875 #ifdef __native_client_codegen__
1877 /* emit nops to next 32 byte alignment */
1878 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1879 while (code < (buf + a)) x86_nop(code);
1883 emit_bytes (acfg, buf, code - buf);
1885 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1886 g_assert (code - buf == *tramp_size);
1887 #elif defined(TARGET_ARM)
1891 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1892 /* Similar to arch_emit_specific_trampoline () */
1895 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1896 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1897 /* Load the arg value from the GOT */
1898 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1899 /* Load the addr from the GOT */
1900 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1902 ARM_BX (code, ARMREG_R1);
1904 g_assert (code - buf == 20);
1907 emit_bytes (acfg, buf, code - buf);
1908 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1910 g_assert_not_reached ();
1915 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1917 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1918 /* Based on code generated by gcc */
1919 emit_unset_mode (acfg);
1922 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1923 ".section .ctors,\"aw\",@progbits\n"
1927 ".section .opd,\"aw\"\n"
1930 ".long .%s,.TOC.@tocbase32\n"
1933 ".type .%s,@function\n"
1935 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1937 ".section .ctors,\"aw\",@progbits\n"
1941 ".section .opd,\"aw\"\n"
1944 ".long .%1$s,.TOC.@tocbase32\n"
1945 ".size %1$s,.-%1$s\n"
1947 ".type .%1$s,@function\n"
1949 ".%1$s:\n", symbol);
1960 "lis 3, .Lglobals@h\n"
1961 "ori 3, 3, .Lglobals@l\n"
1962 "bl .mono_aot_register_module\n"
1970 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1972 ".size .%s,.-.%s\n", symbol, symbol);
1975 ".size .%1$s,.-.%1$s\n", symbol);
1981 /* END OF ARCH SPECIFIC CODE */
1984 mono_get_field_token (MonoClassField *field)
1986 MonoClass *klass = field->parent;
1989 for (i = 0; i < klass->field.count; ++i) {
1990 if (field == &klass->fields [i])
1991 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1994 g_assert_not_reached ();
1999 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2003 //printf ("ENCODE: %d 0x%x.\n", value, value);
2006 * Same encoding as the one used in the metadata, extended to handle values
2007 * greater than 0x1fffffff.
2009 if ((value >= 0) && (value <= 127))
2011 else if ((value >= 0) && (value <= 16383)) {
2012 p [0] = 0x80 | (value >> 8);
2013 p [1] = value & 0xff;
2015 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2016 p [0] = (value >> 24) | 0xc0;
2017 p [1] = (value >> 16) & 0xff;
2018 p [2] = (value >> 8) & 0xff;
2019 p [3] = value & 0xff;
2024 p [1] = (value >> 24) & 0xff;
2025 p [2] = (value >> 16) & 0xff;
2026 p [3] = (value >> 8) & 0xff;
2027 p [4] = value & 0xff;
2035 stream_init (MonoDynamicStream *sh)
2038 sh->alloc_size = 4096;
2039 sh->data = g_malloc (4096);
2041 /* So offsets are > 0 */
2047 make_room_in_stream (MonoDynamicStream *stream, int size)
2049 if (size <= stream->alloc_size)
2052 while (stream->alloc_size <= size) {
2053 if (stream->alloc_size < 4096)
2054 stream->alloc_size = 4096;
2056 stream->alloc_size *= 2;
2059 stream->data = g_realloc (stream->data, stream->alloc_size);
2063 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2067 make_room_in_stream (stream, stream->index + len);
2068 memcpy (stream->data + stream->index, data, len);
2069 idx = stream->index;
2070 stream->index += len;
2077 * Add data to the binary blob inside the aot image. Returns the offset inside the
2078 * blob where the data was stored.
2081 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2083 if (acfg->blob.alloc_size == 0)
2084 stream_init (&acfg->blob);
2086 return add_stream_data (&acfg->blob, (char*)data, data_len);
2090 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2095 if (acfg->blob.alloc_size == 0)
2096 stream_init (&acfg->blob);
2098 count = acfg->blob.index % align;
2100 /* we assume the stream data will be aligned */
2102 add_stream_data (&acfg->blob, buf, 4 - count);
2104 return add_stream_data (&acfg->blob, (char*)data, data_len);
2108 * emit_offset_table:
2110 * Emit a table of increasing offsets in a compact form using differential encoding.
2111 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2112 * group size, the more compact the table becomes, but the slower it becomes to compute
2113 * a given entry. Returns the size of the table.
2116 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2118 gint32 current_offset;
2119 int i, buf_size, ngroups, index_entry_size;
2121 guint32 *index_offsets;
2123 ngroups = (noffsets + (group_size - 1)) / group_size;
2125 index_offsets = g_new0 (guint32, ngroups);
2127 buf_size = noffsets * 4;
2128 p = buf = g_malloc0 (buf_size);
2131 for (i = 0; i < noffsets; ++i) {
2132 //printf ("D: %d -> %d\n", i, offsets [i]);
2133 if ((i % group_size) == 0) {
2134 index_offsets [i / group_size] = p - buf;
2135 /* Emit the full value for these entries */
2136 encode_value (offsets [i], p, &p);
2138 /* The offsets are allowed to be non-increasing */
2139 //g_assert (offsets [i] >= current_offset);
2140 encode_value (offsets [i] - current_offset, p, &p);
2142 current_offset = offsets [i];
2145 if (ngroups && index_offsets [ngroups - 1] < 65000)
2146 index_entry_size = 2;
2148 index_entry_size = 4;
2150 /* Emit the header */
2151 emit_int32 (acfg, noffsets);
2152 emit_int32 (acfg, group_size);
2153 emit_int32 (acfg, ngroups);
2154 emit_int32 (acfg, index_entry_size);
2156 /* Emit the index */
2157 for (i = 0; i < ngroups; ++i) {
2158 if (index_entry_size == 2)
2159 emit_int16 (acfg, index_offsets [i]);
2161 emit_int32 (acfg, index_offsets [i]);
2165 emit_bytes (acfg, buf, p - buf);
2167 return (int)(p - buf) + (ngroups * 4);
2171 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2175 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2179 index = g_hash_table_size (cfg->image_hash);
2180 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2181 g_ptr_array_add (cfg->image_table, image);
2187 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2190 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2192 /* FIXME: Search referenced images as well */
2193 if (!acfg->typespec_classes) {
2194 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2195 for (i = 0; i < len; ++i) {
2196 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2199 for (i = 0; i < len; ++i) {
2200 if (acfg->typespec_classes [i] == klass)
2205 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2211 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2214 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2217 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2220 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2223 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2228 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2232 if (klass->generic_class) {
2234 g_assert (klass->type_token);
2236 /* Find a typespec for a class if possible */
2237 token = find_typespec_for_class (acfg, klass);
2239 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2240 encode_value (token, p, &p);
2242 MonoClass *gclass = klass->generic_class->container_class;
2243 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2244 static int count = 0;
2247 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2248 encode_klass_ref (acfg, gclass, p, &p);
2249 encode_ginst (acfg, inst, p, &p);
2253 } else if (klass->type_token) {
2254 int iindex = get_image_index (acfg, klass->image);
2256 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2258 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2259 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2261 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2262 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2263 encode_value (get_image_index (acfg, klass->image), p, &p);
2265 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2266 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2267 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2269 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2270 encode_value (klass->byval_arg.type, p, &p);
2271 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2273 encode_value (container ? 1 : 0, p, &p);
2275 encode_value (container->is_method, p, &p);
2276 g_assert (par->serial == 0);
2277 if (container->is_method)
2278 encode_method_ref (acfg, container->owner.method, p, &p);
2280 encode_klass_ref (acfg, container->owner.klass, p, &p);
2282 encode_value (par->serial, p, &p);
2284 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2285 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2286 encode_type (acfg, &klass->byval_arg, p, &p);
2289 g_assert (klass->rank > 0);
2290 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2291 encode_value (klass->rank, p, &p);
2292 encode_klass_ref (acfg, klass->element_class, p, &p);
2300 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2301 * standard metadata encoding.
2304 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2306 gboolean shared = FALSE;
2309 * The encoding of generic instances is large so emit them only once.
2311 if (klass->generic_class) {
2313 g_assert (klass->type_token);
2315 /* Find a typespec for a class if possible */
2316 token = find_typespec_for_class (acfg, klass);
2319 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2324 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2328 buf2 = g_malloc (1024);
2331 encode_klass_ref_inner (acfg, klass, p, &p);
2332 g_assert (p - buf2 < 1024);
2334 offset = add_to_blob (acfg, buf2, p - buf2);
2337 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2343 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2344 encode_value (offset, p, &p);
2349 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2353 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2355 guint32 token = mono_get_field_token (field);
2358 encode_klass_ref (cfg, field->parent, p, &p);
2359 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2360 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2365 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2370 encode_value (inst->type_argc, p, &p);
2371 for (i = 0; i < inst->type_argc; ++i)
2372 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2377 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2380 MonoGenericInst *inst;
2382 inst = context->class_inst;
2384 g_assert (inst->type_argc);
2385 encode_ginst (acfg, inst, p, &p);
2387 encode_value (0, p, &p);
2389 inst = context->method_inst;
2391 g_assert (inst->type_argc);
2392 encode_ginst (acfg, inst, p, &p);
2394 encode_value (0, p, &p);
2400 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2404 g_assert (t->num_mods == 0);
2405 /* t->attrs can be ignored */
2406 //g_assert (t->attrs == 0);
2409 *p = MONO_TYPE_PINNED;
2413 *p = MONO_TYPE_BYREF;
2421 case MONO_TYPE_VOID:
2422 case MONO_TYPE_BOOLEAN:
2423 case MONO_TYPE_CHAR:
2436 case MONO_TYPE_STRING:
2437 case MONO_TYPE_OBJECT:
2438 case MONO_TYPE_TYPEDBYREF:
2440 case MONO_TYPE_VALUETYPE:
2441 case MONO_TYPE_CLASS:
2442 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2444 case MONO_TYPE_SZARRAY:
2445 encode_klass_ref (acfg, t->data.klass, p, &p);
2448 encode_type (acfg, t->data.type, p, &p);
2450 case MONO_TYPE_GENERICINST: {
2451 MonoClass *gclass = t->data.generic_class->container_class;
2452 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2454 encode_klass_ref (acfg, gclass, p, &p);
2455 encode_ginst (acfg, inst, p, &p);
2458 case MONO_TYPE_ARRAY: {
2459 MonoArrayType *array = t->data.array;
2462 encode_klass_ref (acfg, array->eklass, p, &p);
2463 encode_value (array->rank, p, &p);
2464 encode_value (array->numsizes, p, &p);
2465 for (i = 0; i < array->numsizes; ++i)
2466 encode_value (array->sizes [i], p, &p);
2467 encode_value (array->numlobounds, p, &p);
2468 for (i = 0; i < array->numlobounds; ++i)
2469 encode_value (array->lobounds [i], p, &p);
2473 case MONO_TYPE_MVAR:
2474 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2477 g_assert_not_reached ();
2484 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2490 /* Similar to the metadata encoding */
2491 if (sig->generic_param_count)
2495 if (sig->explicit_this)
2497 flags |= (sig->call_convention & 0x0F);
2501 if (sig->generic_param_count)
2502 encode_value (sig->generic_param_count, p, &p);
2503 encode_value (sig->param_count, p, &p);
2505 encode_type (acfg, sig->ret, p, &p);
2506 for (i = 0; i < sig->param_count; ++i) {
2507 if (sig->sentinelpos == i) {
2508 *p = MONO_TYPE_SENTINEL;
2511 encode_type (acfg, sig->params [i], p, &p);
2517 #define MAX_IMAGE_INDEX 250
2520 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2522 guint32 image_index = get_image_index (acfg, method->klass->image);
2523 guint32 token = method->token;
2524 MonoJumpInfoToken *ji;
2528 * The encoding for most methods is as follows:
2529 * - image index encoded as a leb128
2530 * - token index encoded as a leb128
2531 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2532 * types of method encodings.
2535 /* Mark methods which can't use aot trampolines because they need the further
2536 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2538 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2539 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2540 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2542 if (method->wrapper_type) {
2543 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2545 encode_value (method->wrapper_type, p, &p);
2547 switch (method->wrapper_type) {
2548 case MONO_WRAPPER_REMOTING_INVOKE:
2549 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2550 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2553 m = mono_marshal_method_from_wrapper (method);
2555 encode_method_ref (acfg, m, p, &p);
2558 case MONO_WRAPPER_PROXY_ISINST:
2559 case MONO_WRAPPER_LDFLD:
2560 case MONO_WRAPPER_LDFLDA:
2561 case MONO_WRAPPER_STFLD:
2562 case MONO_WRAPPER_ISINST: {
2563 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2564 encode_klass_ref (acfg, proxy_class, p, &p);
2567 case MONO_WRAPPER_LDFLD_REMOTE:
2568 case MONO_WRAPPER_STFLD_REMOTE:
2570 case MONO_WRAPPER_ALLOC: {
2571 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2573 /* The GC name is saved once in MonoAotFileInfo */
2574 g_assert (info->alloc_type != -1);
2575 encode_value (info->alloc_type, p, &p);
2578 case MONO_WRAPPER_WRITE_BARRIER:
2580 case MONO_WRAPPER_STELEMREF: {
2581 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2584 encode_value (info->subtype, p, &p);
2585 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2586 encode_value (info->d.virtual_stelemref.kind, p, &p);
2589 case MONO_WRAPPER_UNKNOWN: {
2590 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2593 encode_value (info->subtype, p, &p);
2594 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2595 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2596 encode_klass_ref (acfg, method->klass, p, &p);
2597 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2598 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2599 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2600 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2603 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2604 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2607 encode_value (info->subtype, p, &p);
2608 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2609 strcpy ((char*)p, method->name);
2610 p += strlen (method->name) + 1;
2611 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2612 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2614 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2615 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2619 case MONO_WRAPPER_SYNCHRONIZED: {
2622 m = mono_marshal_method_from_wrapper (method);
2624 g_assert (m != method);
2625 encode_method_ref (acfg, m, p, &p);
2628 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2629 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2632 encode_value (info->subtype, p, &p);
2634 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2635 encode_value (info->d.element_addr.rank, p, &p);
2636 encode_value (info->d.element_addr.elem_size, p, &p);
2637 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2638 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2640 g_assert_not_reached ();
2644 case MONO_WRAPPER_CASTCLASS: {
2645 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2648 encode_value (info->subtype, p, &p);
2651 case MONO_WRAPPER_RUNTIME_INVOKE: {
2652 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2655 encode_value (info->subtype, p, &p);
2656 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2657 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2658 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2659 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2662 case MONO_WRAPPER_DELEGATE_INVOKE:
2663 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2664 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2665 if (method->is_inflated) {
2666 /* These wrappers are identified by their class */
2667 encode_value (1, p, &p);
2668 encode_klass_ref (acfg, method->klass, p, &p);
2670 MonoMethodSignature *sig = mono_method_signature (method);
2672 encode_value (0, p, &p);
2673 encode_signature (acfg, sig, p, &p);
2677 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2678 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2681 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2682 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2686 g_assert_not_reached ();
2688 } else if (mono_method_signature (method)->is_inflated) {
2690 * This is a generic method, find the original token which referenced it and
2692 * Obtain the token from information recorded by the JIT.
2694 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2696 image_index = get_image_index (acfg, ji->image);
2697 g_assert (image_index < MAX_IMAGE_INDEX);
2700 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2701 encode_value (image_index, p, &p);
2702 encode_value (token, p, &p);
2704 MonoMethod *declaring;
2705 MonoGenericContext *context = mono_method_get_context (method);
2707 g_assert (method->is_inflated);
2708 declaring = ((MonoMethodInflated*)method)->declaring;
2711 * This might be a non-generic method of a generic instance, which
2712 * doesn't have a token since the reference is generated by the JIT
2713 * like Nullable:Box/Unbox, or by generic sharing.
2715 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2716 /* Encode the klass */
2717 encode_klass_ref (acfg, method->klass, p, &p);
2718 /* Encode the method */
2719 image_index = get_image_index (acfg, method->klass->image);
2720 g_assert (image_index < MAX_IMAGE_INDEX);
2721 g_assert (declaring->token);
2722 token = declaring->token;
2723 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2724 encode_value (image_index, p, &p);
2725 encode_value (token, p, &p);
2726 encode_generic_context (acfg, context, p, &p);
2728 } else if (token == 0) {
2729 /* This might be a method of a constructed type like int[,].Set */
2730 /* Obtain the token from information recorded by the JIT */
2731 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2733 image_index = get_image_index (acfg, ji->image);
2734 g_assert (image_index < MAX_IMAGE_INDEX);
2737 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2738 encode_value (image_index, p, &p);
2739 encode_value (token, p, &p);
2742 g_assert (method->klass->rank);
2744 /* Encode directly */
2745 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2746 encode_klass_ref (acfg, method->klass, p, &p);
2747 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2748 encode_value (0, p, &p);
2749 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2750 encode_value (1, p, &p);
2751 else if (!strcmp (method->name, "Get"))
2752 encode_value (2, p, &p);
2753 else if (!strcmp (method->name, "Address"))
2754 encode_value (3, p, &p);
2755 else if (!strcmp (method->name, "Set"))
2756 encode_value (4, p, &p);
2758 g_assert_not_reached ();
2761 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2763 if (image_index >= MONO_AOT_METHODREF_MIN) {
2764 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2765 encode_value (image_index, p, &p);
2766 encode_value (mono_metadata_token_index (token), p, &p);
2768 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2775 compare_patches (gconstpointer a, gconstpointer b)
2779 i = (*(MonoJumpInfo**)a)->ip.i;
2780 j = (*(MonoJumpInfo**)b)->ip.i;
2791 static G_GNUC_UNUSED char*
2792 patch_to_string (MonoJumpInfo *patch_info)
2796 str = g_string_new ("");
2798 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2800 switch (patch_info->type) {
2801 case MONO_PATCH_INFO_VTABLE:
2802 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2807 g_string_append_printf (str, ")");
2808 return g_string_free (str, FALSE);
2814 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2817 static inline gboolean
2818 is_plt_patch (MonoJumpInfo *patch_info)
2820 switch (patch_info->type) {
2821 case MONO_PATCH_INFO_METHOD:
2822 case MONO_PATCH_INFO_INTERNAL_METHOD:
2823 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2824 case MONO_PATCH_INFO_ICALL_ADDR:
2825 case MONO_PATCH_INFO_CLASS_INIT:
2826 case MONO_PATCH_INFO_RGCTX_FETCH:
2827 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2828 case MONO_PATCH_INFO_MONITOR_ENTER:
2829 case MONO_PATCH_INFO_MONITOR_EXIT:
2830 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2840 * Return the symbol identifying the plt entry PLT_OFFSET.
2843 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2847 * The Apple linker reorganizes object files, so it doesn't like branches to local
2848 * labels, since those have no relocations.
2850 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2852 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2859 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2861 static MonoPltEntry*
2862 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2866 if (!is_plt_patch (patch_info))
2869 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2871 // FIXME: This breaks the calculation of final_got_size
2872 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2874 * Allocate a separate PLT slot for each such patch, since some plt
2875 * entries will refer to the method itself, and some will refer to the
2882 MonoJumpInfo *new_ji;
2884 g_assert (!acfg->final_got_size);
2886 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2888 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2889 res->plt_offset = acfg->plt_offset;
2891 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2892 if (acfg->aot_opts.write_symbols)
2893 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2895 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2897 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2899 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2901 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2903 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2904 //mono_print_ji (patch_info); printf ("\n");
2905 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2907 acfg->plt_offset ++;
2916 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2917 * JI could be found if it exists, otherwise allocates a new one.
2920 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2924 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2926 return got_offset - 1;
2928 got_offset = acfg->got_offset;
2929 acfg->got_offset ++;
2931 if (acfg->final_got_size)
2932 g_assert (got_offset < acfg->final_got_size);
2934 acfg->stats.got_slots ++;
2935 acfg->stats.got_slot_types [ji->type] ++;
2937 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2938 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2939 g_ptr_array_add (acfg->got_patches, ji);
2944 /* Add a method to the list of methods which need to be emitted */
2946 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2949 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2950 g_ptr_array_add (acfg->methods, method);
2951 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2952 acfg->nmethods = acfg->methods->len + 1;
2955 if (method->wrapper_type || extra)
2956 g_ptr_array_add (acfg->extra_methods, method);
2960 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2962 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2970 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2974 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2978 index = acfg->method_index;
2979 add_method_with_index (acfg, method, index, extra);
2981 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2983 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2985 acfg->method_index ++;
2991 add_method (MonoAotCompile *acfg, MonoMethod *method)
2993 return add_method_full (acfg, method, FALSE, 0);
2997 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2999 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3000 method = mini_get_shared_method (method);
3002 if (acfg->aot_opts.log_generics)
3003 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3005 add_method_full (acfg, method, TRUE, depth);
3009 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3011 add_extra_method_with_depth (acfg, method, 0);
3015 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3017 MonoAotCompile *acfg = user_data;
3018 MonoJitICallInfo *callinfo = value;
3019 MonoMethod *wrapper;
3025 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3026 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3029 add_method (acfg, wrapper);
3033 get_runtime_invoke_sig (MonoMethodSignature *sig)
3035 MonoMethodBuilder *mb;
3038 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3039 m = mono_mb_create_method (mb, sig, 16);
3040 return mono_marshal_get_runtime_invoke (m, FALSE);
3044 can_marshal_struct (MonoClass *klass)
3046 MonoClassField *field;
3047 gboolean can_marshal = TRUE;
3048 gpointer iter = NULL;
3049 MonoMarshalType *info;
3052 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3055 info = mono_marshal_load_type_info (klass);
3057 /* Only allow a few field types to avoid asserts in the marshalling code */
3058 while ((field = mono_class_get_fields (klass, &iter))) {
3059 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3062 switch (field->type->type) {
3067 case MONO_TYPE_BOOLEAN:
3070 case MONO_TYPE_CHAR:
3078 case MONO_TYPE_STRING:
3080 case MONO_TYPE_VALUETYPE:
3081 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3082 can_marshal = FALSE;
3084 case MONO_TYPE_SZARRAY: {
3085 gboolean has_mspec = FALSE;
3088 for (i = 0; i < info->num_fields; ++i) {
3089 if (info->fields [i].field == field && info->fields [i].mspec)
3094 can_marshal = FALSE;
3098 can_marshal = FALSE;
3104 /* Its hard to compute whenever these can be marshalled or not */
3105 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3112 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3114 /* Create a vtype instantiation */
3115 MonoGenericContext shared_context;
3117 MonoGenericInst *inst;
3118 MonoGenericContainer *container;
3119 MonoClass **constraints;
3122 memset (ctx, 0, sizeof (MonoGenericContext));
3124 if (method->klass->generic_container) {
3125 shared_context = method->klass->generic_container->context;
3126 inst = shared_context.class_inst;
3128 args = g_new0 (MonoType*, inst->type_argc);
3129 for (i = 0; i < inst->type_argc; ++i) {
3130 args [i] = &mono_defaults.int_class->byval_arg;
3132 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3134 if (method->is_generic) {
3135 container = mono_method_get_generic_container (method);
3136 shared_context = container->context;
3137 inst = shared_context.method_inst;
3139 args = g_new0 (MonoType*, inst->type_argc);
3140 for (i = 0; i < container->type_argc; ++i) {
3141 MonoGenericParamInfo *info = &container->type_params [i].info;
3142 gboolean ref_only = FALSE;
3144 if (info && info->constraints) {
3145 constraints = info->constraints;
3147 while (*constraints) {
3148 MonoClass *cklass = *constraints;
3149 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3150 /* Inflaring the method with our vtype would not be valid */
3157 args [i] = &mono_defaults.object_class->byval_arg;
3159 args [i] = &mono_defaults.int_class->byval_arg;
3161 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3165 #define MONO_TYPE_IS_PRIMITIVE(t) ((!(t)->byref && ((((t)->type >= MONO_TYPE_BOOLEAN && (t)->type <= MONO_TYPE_R8) || ((t)->type >= MONO_TYPE_I && (t)->type <= MONO_TYPE_U)))))
3168 add_wrappers (MonoAotCompile *acfg)
3170 MonoMethod *method, *m;
3172 MonoMethodSignature *sig, *csig;
3176 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3177 * so there is only one wrapper of a given type, or inlining their contents into their
3182 * FIXME: This depends on the fact that different wrappers have different
3186 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3188 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3189 gboolean skip = FALSE;
3191 method = mono_get_method (acfg->image, token, NULL);
3193 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3194 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3195 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3198 if (method->is_generic || method->klass->generic_container)
3201 /* Skip methods which can not be handled by get_runtime_invoke () */
3202 sig = mono_method_signature (method);
3205 if ((sig->ret->type == MONO_TYPE_PTR) ||
3206 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3209 for (j = 0; j < sig->param_count; j++) {
3210 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3214 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3215 if (!mono_class_is_contextbound (method->klass)) {
3216 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3217 gboolean has_nullable = FALSE;
3219 for (j = 0; j < sig->param_count; j++) {
3220 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3221 has_nullable = TRUE;
3224 if (info && !has_nullable) {
3225 /* Supported by the dynamic runtime-invoke wrapper */
3233 //printf ("%s\n", mono_method_full_name (method, TRUE));
3234 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3238 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3239 MonoMethodDesc *desc;
3240 MonoMethod *orig_method;
3243 /* Runtime invoke wrappers */
3245 /* void runtime-invoke () [.cctor] */
3246 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3247 csig->ret = &mono_defaults.void_class->byval_arg;
3248 add_method (acfg, get_runtime_invoke_sig (csig));
3250 /* void runtime-invoke () [Finalize] */
3251 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3253 csig->ret = &mono_defaults.void_class->byval_arg;
3254 add_method (acfg, get_runtime_invoke_sig (csig));
3256 /* void runtime-invoke (string) [exception ctor] */
3257 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3259 csig->ret = &mono_defaults.void_class->byval_arg;
3260 csig->params [0] = &mono_defaults.string_class->byval_arg;
3261 add_method (acfg, get_runtime_invoke_sig (csig));
3263 /* void runtime-invoke (string, string) [exception ctor] */
3264 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3266 csig->ret = &mono_defaults.void_class->byval_arg;
3267 csig->params [0] = &mono_defaults.string_class->byval_arg;
3268 csig->params [1] = &mono_defaults.string_class->byval_arg;
3269 add_method (acfg, get_runtime_invoke_sig (csig));
3271 /* string runtime-invoke () [Exception.ToString ()] */
3272 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3274 csig->ret = &mono_defaults.string_class->byval_arg;
3275 add_method (acfg, get_runtime_invoke_sig (csig));
3277 /* void runtime-invoke (string, Exception) [exception ctor] */
3278 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3280 csig->ret = &mono_defaults.void_class->byval_arg;
3281 csig->params [0] = &mono_defaults.string_class->byval_arg;
3282 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3283 add_method (acfg, get_runtime_invoke_sig (csig));
3285 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3286 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3288 csig->ret = &(mono_class_from_name (
3289 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3290 csig->params [0] = &mono_defaults.string_class->byval_arg;
3291 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3292 add_method (acfg, get_runtime_invoke_sig (csig));
3294 /* runtime-invoke used by finalizers */
3295 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3297 /* This is used by mono_runtime_capture_context () */
3298 method = mono_get_context_capture_method ();
3300 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3302 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3303 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3306 /* JIT icall wrappers */
3307 /* FIXME: locking */
3308 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3311 add_method (acfg, mono_marshal_get_stelemref ());
3313 if (MONO_ARCH_HAVE_TLS_GET) {
3314 /* Managed Allocators */
3315 nallocators = mono_gc_get_managed_allocator_types ();
3316 for (i = 0; i < nallocators; ++i) {
3317 m = mono_gc_get_managed_allocator_by_type (i);
3319 add_method (acfg, m);
3322 /* Monitor Enter/Exit */
3323 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3324 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3325 /* This is a v4 method */
3327 method = mono_monitor_get_fast_path (orig_method);
3329 add_method (acfg, method);
3331 mono_method_desc_free (desc);
3333 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3334 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3335 g_assert (orig_method);
3336 mono_method_desc_free (desc);
3337 method = mono_monitor_get_fast_path (orig_method);
3339 add_method (acfg, method);
3342 /* Stelemref wrappers */
3344 MonoMethod **wrappers;
3347 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3348 for (i = 0; i < nwrappers; ++i)
3349 add_method (acfg, wrappers [i]);
3353 /* castclass_with_check wrapper */
3354 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3355 /* isinst_with_check wrapper */
3356 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3358 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3360 MonoMethodDesc *desc;
3363 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3364 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3365 mono_method_desc_free (desc);
3367 m = mono_monitor_get_fast_path (m);
3369 add_method (acfg, m);
3376 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3377 * we use the original method instead at runtime.
3378 * Since full-aot doesn't support remoting, this is not a problem.
3381 /* remoting-invoke wrappers */
3382 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3383 MonoMethodSignature *sig;
3385 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3386 method = mono_get_method (acfg->image, token, NULL);
3388 sig = mono_method_signature (method);
3390 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3391 m = mono_marshal_get_remoting_invoke_with_check (method);
3393 add_method (acfg, m);
3398 /* delegate-invoke wrappers */
3399 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3401 MonoCustomAttrInfo *cattr;
3403 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3404 klass = mono_class_get (acfg->image, token);
3407 mono_loader_clear_error ();
3411 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3414 if (!klass->generic_container) {
3415 method = mono_get_delegate_invoke (klass);
3417 m = mono_marshal_get_delegate_invoke (method, NULL);
3419 add_method (acfg, m);
3421 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3423 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3425 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3427 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3429 cattr = mono_custom_attrs_from_class (klass);
3434 for (j = 0; j < cattr->num_attrs; ++j)
3435 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3437 if (j < cattr->num_attrs)
3438 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3440 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3441 MonoGenericContext ctx;
3442 MonoMethod *inst, *gshared;
3445 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3448 method = mono_get_delegate_invoke (klass);
3449 create_gsharedvt_inst (acfg, method, &ctx);
3451 inst = mono_class_inflate_generic_method (method, &ctx);
3453 m = mono_marshal_get_delegate_invoke (inst, NULL);
3454 g_assert (m->is_inflated);
3456 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3457 add_extra_method (acfg, gshared);
3460 method = mono_get_delegate_begin_invoke (klass);
3461 create_gsharedvt_inst (acfg, method, &ctx);
3463 inst = mono_class_inflate_generic_method (method, &ctx);
3465 m = mono_marshal_get_delegate_begin_invoke (inst);
3466 g_assert (m->is_inflated);
3468 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3469 add_extra_method (acfg, gshared);
3472 method = mono_get_delegate_end_invoke (klass);
3473 create_gsharedvt_inst (acfg, method, &ctx);
3475 inst = mono_class_inflate_generic_method (method, &ctx);
3477 m = mono_marshal_get_delegate_end_invoke (inst);
3478 g_assert (m->is_inflated);
3480 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3481 add_extra_method (acfg, gshared);
3486 /* array access wrappers */
3487 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3490 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3491 klass = mono_class_get (acfg->image, token);
3494 mono_loader_clear_error ();
3498 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3499 MonoMethod *m, *wrapper;
3501 /* Add runtime-invoke wrappers too */
3503 m = mono_class_get_method_from_name (klass, "Get", -1);
3505 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3506 add_extra_method (acfg, wrapper);
3507 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3509 m = mono_class_get_method_from_name (klass, "Set", -1);
3511 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3512 add_extra_method (acfg, wrapper);
3513 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3517 /* Synchronized wrappers */
3518 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3519 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3520 method = mono_get_method (acfg->image, token, NULL);
3522 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3523 if (method->is_generic) {
3525 } else if (method->klass->generic_container) {
3526 MonoGenericContext ctx;
3527 MonoMethod *inst, *gshared, *m;
3530 * Create a generic wrapper for a generic instance, and AOT that.
3532 create_gsharedvt_inst (acfg, method, &ctx);
3533 inst = mono_class_inflate_generic_method (method, &ctx);
3534 m = mono_marshal_get_synchronized_wrapper (inst);
3535 g_assert (m->is_inflated);
3536 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3537 add_method (acfg, gshared);
3539 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3544 /* pinvoke wrappers */
3545 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3547 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3549 method = mono_get_method (acfg->image, token, NULL);
3551 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3552 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3553 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3557 /* native-to-managed wrappers */
3558 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3560 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3561 MonoCustomAttrInfo *cattr;
3564 method = mono_get_method (acfg->image, token, NULL);
3567 * Only generate native-to-managed wrappers for methods which have an
3568 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3569 * name to avoid defining a new assembly to contain it.
3571 cattr = mono_custom_attrs_from_method (method);
3574 for (j = 0; j < cattr->num_attrs; ++j)
3575 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3577 if (j < cattr->num_attrs) {
3578 MonoCustomAttrEntry *e = &cattr->attrs [j];
3579 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3580 const char *p = (const char*)e->data;
3582 int slen, num_named, named_type, data_type;
3586 char *export_name = NULL;
3587 MonoMethod *wrapper;
3589 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3590 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3591 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3592 mono_method_full_name (method, TRUE));
3596 g_assert (sig->param_count == 1);
3597 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3600 * Decode the cattr manually since we can't create objects
3601 * during aot compilation.
3607 /* From load_cattr_value () in reflection.c */
3608 slen = mono_metadata_decode_value (p, &p);
3609 n = g_memdup (p, slen + 1);
3611 t = mono_reflection_type_from_name (n, acfg->image);
3615 klass = mono_class_from_mono_type (t);
3616 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3620 num_named = read16 (p);
3623 g_assert (num_named < 2);
3624 if (num_named == 1) {
3627 MonoType *prop_type;
3629 /* parse ExportSymbol attribute */
3631 named_type = *named;
3636 name_len = mono_metadata_decode_blob_size (named, &named);
3637 name = g_malloc (name_len + 1);
3638 memcpy (name, named, name_len);
3639 name [name_len] = 0;
3642 g_assert (named_type == 0x54);
3643 g_assert (!strcmp (name, "ExportSymbol"));
3645 prop_type = &mono_defaults.string_class->byval_arg;
3647 /* load_cattr_value (), string case */
3648 g_assert (*named != (char)0xff);
3649 slen = mono_metadata_decode_value (named, &named);
3650 export_name = g_malloc (slen + 1);
3651 memcpy (export_name, named, slen);
3652 export_name [slen] = 0;
3656 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3657 add_method (acfg, wrapper);
3659 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3663 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3664 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3665 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3669 /* StructureToPtr/PtrToStructure wrappers */
3670 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3673 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3674 klass = mono_class_get (acfg->image, token);
3677 mono_loader_clear_error ();
3681 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3682 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3683 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3684 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3690 has_type_vars (MonoClass *klass)
3692 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3695 return has_type_vars (klass->element_class);
3696 if (klass->generic_class) {
3697 MonoGenericContext *context = &klass->generic_class->context;
3698 if (context->class_inst) {
3701 for (i = 0; i < context->class_inst->type_argc; ++i)
3702 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3710 is_vt_inst (MonoGenericInst *inst)
3714 for (i = 0; i < inst->type_argc; ++i) {
3715 MonoType *t = inst->type_argv [i];
3716 if (t->type == MONO_TYPE_VALUETYPE)
3723 method_has_type_vars (MonoMethod *method)
3725 if (has_type_vars (method->klass))
3728 if (method->is_inflated) {
3729 MonoGenericContext *context = mono_method_get_context (method);
3730 if (context->method_inst) {
3733 for (i = 0; i < context->method_inst->type_argc; ++i)
3734 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3741 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3744 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3746 /* This might lead to a huge code blowup so only do it if neccesary */
3747 if (!acfg->aot_opts.full_aot && !force)
3750 add_generic_class_with_depth (acfg, klass, 0, ref);
3754 check_type_depth (MonoType *t, int depth)
3762 case MONO_TYPE_GENERICINST: {
3763 MonoGenericClass *gklass = t->data.generic_class;
3764 MonoGenericInst *ginst = gklass->context.class_inst;
3767 for (i = 0; i < ginst->type_argc; ++i) {
3768 if (check_type_depth (ginst->type_argv [i], depth + 1))
3782 * add_generic_class:
3784 * Add all methods of a generic class.
3787 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3790 MonoClassField *field;
3792 gboolean use_gsharedvt = FALSE;
3794 if (!acfg->ginst_hash)
3795 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3797 mono_class_init (klass);
3799 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3802 if (has_type_vars (klass))
3805 if (!klass->generic_class && !klass->rank)
3808 if (klass->exception_type)
3811 if (!acfg->ginst_hash)
3812 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3814 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3817 if (check_type_depth (&klass->byval_arg, 0))
3820 if (acfg->aot_opts.log_generics)
3821 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3823 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3826 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3827 * Enable this only for some classes since gsharedvt might not support all methods.
3829 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) && (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1")))
3830 use_gsharedvt = TRUE;
3833 while ((method = mono_class_get_methods (klass, &iter))) {
3834 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt))
3838 if (method->is_generic)
3843 * FIXME: Instances which are referenced by these methods are not added,
3844 * for example Array.Resize<int> for List<int>.Add ().
3846 add_extra_method_with_depth (acfg, method, depth + 1);
3850 while ((field = mono_class_get_fields (klass, &iter))) {
3851 if (field->type->type == MONO_TYPE_GENERICINST)
3852 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3855 if (klass->delegate) {
3856 method = mono_get_delegate_invoke (klass);
3858 method = mono_marshal_get_delegate_invoke (method, NULL);
3860 if (acfg->aot_opts.log_generics)
3861 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3863 add_method (acfg, method);
3866 /* Add superclasses */
3868 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3871 * For ICollection<T>, add instances of the helper methods
3872 * in Array, since a T[] could be cast to ICollection<T>.
3874 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3875 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1") || !strcmp (klass->name, "IReadOnlyList`1"))) {
3876 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3877 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3881 if (!strcmp (klass->name, "IEnumerator`1"))
3882 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3884 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3886 /* Add the T[]/InternalEnumerator class */
3887 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3891 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3892 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3896 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3897 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3901 while ((method = mono_class_get_methods (array_class, &iter))) {
3902 if (strstr (method->name, name_prefix)) {
3903 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3905 add_extra_method_with_depth (acfg, m, depth);
3909 g_free (name_prefix);
3912 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3913 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3914 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3915 MonoClass *icomparable, *gcomparer;
3916 MonoGenericContext ctx;
3917 MonoType *args [16];
3919 memset (&ctx, 0, sizeof (ctx));
3921 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3922 g_assert (icomparable);
3923 args [0] = &tclass->byval_arg;
3924 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3926 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3927 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3928 g_assert (gcomparer);
3929 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3933 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3934 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3935 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3936 MonoClass *iface, *gcomparer;
3937 MonoGenericContext ctx;
3938 MonoType *args [16];
3940 memset (&ctx, 0, sizeof (ctx));
3942 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3944 args [0] = &tclass->byval_arg;
3945 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3947 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3948 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3949 g_assert (gcomparer);
3950 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3956 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3959 MonoGenericContext ctx;
3960 MonoType *args [16];
3962 if (acfg->aot_opts.no_instances)
3965 memset (&ctx, 0, sizeof (ctx));
3967 for (i = 0; i < ninsts; ++i) {
3968 args [0] = insts [i];
3969 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3970 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3975 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3977 MonoMethodHeader *header;
3978 MonoMethodSignature *sig;
3981 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3983 sig = mono_method_signature (method);
3986 for (j = 0; j < sig->param_count; ++j)
3987 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3988 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3991 header = mono_method_get_header (method);
3994 for (j = 0; j < header->num_locals; ++j)
3995 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3996 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4001 * add_generic_instances:
4003 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4006 add_generic_instances (MonoAotCompile *acfg)
4011 MonoGenericContext *context;
4013 if (acfg->aot_opts.no_instances)
4016 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4017 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4018 method = mono_get_method (acfg->image, token, NULL);
4023 if (method->klass->image != acfg->image)
4026 context = mono_method_get_context (method);
4028 if (context && ((context->class_inst && context->class_inst->is_open)))
4032 * For open methods, create an instantiation which can be passed to the JIT.
4033 * FIXME: Handle class_inst as well.
4035 if (context && context->method_inst && context->method_inst->is_open) {
4036 MonoGenericContext shared_context;
4037 MonoGenericInst *inst;
4038 MonoType **type_argv;
4040 MonoMethod *declaring_method;
4041 gboolean supported = TRUE;
4043 /* Check that the context doesn't contain open constructed types */
4044 if (context->class_inst) {
4045 inst = context->class_inst;
4046 for (i = 0; i < inst->type_argc; ++i) {
4047 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)
4049 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4053 if (context->method_inst) {
4054 inst = context->method_inst;
4055 for (i = 0; i < inst->type_argc; ++i) {
4056 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)
4058 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4066 memset (&shared_context, 0, sizeof (MonoGenericContext));
4068 inst = context->class_inst;
4070 type_argv = g_new0 (MonoType*, inst->type_argc);
4071 for (i = 0; i < inst->type_argc; ++i) {
4072 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)
4073 type_argv [i] = &mono_defaults.object_class->byval_arg;
4075 type_argv [i] = inst->type_argv [i];
4078 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4082 inst = context->method_inst;
4084 type_argv = g_new0 (MonoType*, inst->type_argc);
4085 for (i = 0; i < inst->type_argc; ++i) {
4086 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)
4087 type_argv [i] = &mono_defaults.object_class->byval_arg;
4089 type_argv [i] = inst->type_argv [i];
4092 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4096 if (method->is_generic || method->klass->generic_container)
4097 declaring_method = method;
4099 declaring_method = mono_method_get_declaring_generic_method (method);
4101 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4105 * If the method is fully sharable, it was already added in place of its
4106 * generic definition.
4108 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4112 * FIXME: Partially shared methods are not shared here, so we end up with
4113 * many identical methods.
4115 add_extra_method (acfg, method);
4118 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4121 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4123 klass = mono_class_get (acfg->image, token);
4124 if (!klass || klass->rank) {
4125 mono_loader_clear_error ();
4129 add_generic_class (acfg, klass, FALSE, "typespec");
4132 /* Add types of args/locals */
4133 for (i = 0; i < acfg->methods->len; ++i) {
4134 method = g_ptr_array_index (acfg->methods, i);
4135 add_types_from_method_header (acfg, method);
4138 if (acfg->image == mono_defaults.corlib) {
4140 MonoType *insts [256];
4143 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4144 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4145 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4146 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4147 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4148 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4149 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4150 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4151 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4152 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4153 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4154 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4156 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4157 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4159 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4160 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4162 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4164 /* Add instances of the array generic interfaces for primitive types */
4165 /* This will add instances of the InternalArray_ helper methods in Array too */
4166 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4168 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4169 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4171 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4172 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4174 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4177 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4178 * used for all instances of GetGenericValueImpl by the AOT runtime.
4181 MonoGenericContext ctx;
4182 MonoType *args [16];
4183 MonoMethod *get_method;
4184 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4186 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4189 memset (&ctx, 0, sizeof (ctx));
4190 args [0] = &mono_defaults.object_class->byval_arg;
4191 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4192 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4196 /* Same for CompareExchange<T>/Exchange<T> */
4198 MonoGenericContext ctx;
4199 MonoType *args [16];
4201 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4202 gpointer iter = NULL;
4204 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4205 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4206 memset (&ctx, 0, sizeof (ctx));
4207 args [0] = &mono_defaults.object_class->byval_arg;
4208 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4209 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4214 /* Same for Volatile.Read/Write<T> */
4216 MonoGenericContext ctx;
4217 MonoType *args [16];
4219 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4220 gpointer iter = NULL;
4222 if (volatile_klass) {
4223 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4224 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4225 memset (&ctx, 0, sizeof (ctx));
4226 args [0] = &mono_defaults.object_class->byval_arg;
4227 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4228 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4237 * is_direct_callable:
4239 * Return whenever the method identified by JI is directly callable without
4240 * going through the PLT.
4243 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4245 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4246 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4248 gboolean direct_callable = TRUE;
4250 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4251 direct_callable = FALSE;
4252 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4253 // FIXME: Maybe call the wrapper directly ?
4254 direct_callable = FALSE;
4256 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4257 /* Disable this so all calls go through load_method (), see the
4258 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4259 * mono_debugger_agent_init ().
4261 direct_callable = FALSE;
4264 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4265 /* sgen does some initialization when the allocator method is created */
4266 direct_callable = FALSE;
4268 if (direct_callable)
4271 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4272 if (acfg->aot_opts.direct_pinvoke)
4274 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4275 if (acfg->aot_opts.direct_icalls)
4284 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4286 MonoImage *image = method->klass->image;
4287 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4288 MonoTableInfo *tables = image->tables;
4289 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4290 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4291 guint32 im_cols [MONO_IMPLMAP_SIZE];
4294 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4298 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4301 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4303 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4306 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4308 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4314 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4316 if (a->native_offset == b->native_offset)
4317 return a->il_offset - b->il_offset;
4319 return a->native_offset - b->native_offset;
4323 * compute_line_numbers:
4325 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4328 static MonoDebugSourceLocation**
4329 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4331 MonoDebugMethodInfo *minfo;
4332 MonoDebugLineNumberEntry *ln_array;
4333 MonoDebugSourceLocation *loc;
4334 int i, prev_line, prev_il_offset;
4335 int *native_to_il_offset = NULL;
4336 MonoDebugSourceLocation **res;
4339 minfo = mono_debug_lookup_method (method);
4342 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4343 if (debug_info->code_size != code_size)
4346 g_assert (code_size);
4348 /* Compute the native->IL offset mapping */
4350 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4351 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4353 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4355 native_to_il_offset = g_new0 (int, code_size + 1);
4357 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4359 MonoDebugLineNumberEntry *lne = &ln_array [i];
4362 for (j = 0; j < lne->native_offset; ++j)
4363 native_to_il_offset [j] = -1;
4366 if (i < debug_info->num_line_numbers - 1) {
4367 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4369 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4370 native_to_il_offset [j] = lne->il_offset;
4372 for (j = lne->native_offset; j < code_size; ++j)
4373 native_to_il_offset [j] = lne->il_offset;
4378 /* Compute the native->line number mapping */
4379 res = g_new0 (MonoDebugSourceLocation*, code_size);
4380 prev_il_offset = -1;
4383 for (i = 0; i < code_size; ++i) {
4384 int il_offset = native_to_il_offset [i];
4386 if (il_offset == -1 || il_offset == prev_il_offset)
4388 prev_il_offset = il_offset;
4389 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4390 if (!(loc && loc->source_file))
4392 if (loc->row == prev_line) {
4393 mono_debug_symfile_free_location (loc);
4396 prev_line = loc->row;
4397 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4399 /* This will cover the prolog too */
4409 get_file_index (MonoAotCompile *acfg, const char *source_file)
4413 // FIXME: Free these
4414 if (!acfg->dwarf_ln_filenames)
4415 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4416 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4418 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4419 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4420 emit_unset_mode (acfg);
4421 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4427 * emit_and_reloc_code:
4429 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4430 * is true, calls are made through the GOT too. This is used for emitting trampolines
4431 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4432 * since trampolines are needed to make PTL work.
4435 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4437 int i, pindex, start_index, method_index;
4439 MonoJumpInfo *patch_info;
4440 MonoMethodHeader *header;
4441 MonoDebugSourceLocation **locs = NULL;
4442 gboolean skip, direct_call, external_call;
4444 const char *direct_call_target = 0;
4445 const char *direct_pinvoke;
4448 header = mono_method_get_header (method);
4450 method_index = get_method_index (acfg, method);
4453 if (acfg->gas_line_numbers && method && debug_info) {
4454 locs = compute_line_numbers (method, code_len, debug_info);
4456 int findex = get_file_index (acfg, "<unknown>");
4457 emit_unset_mode (acfg);
4458 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4462 /* Collect and sort relocations */
4463 patches = g_ptr_array_new ();
4464 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4465 g_ptr_array_add (patches, patch_info);
4466 g_ptr_array_sort (patches, compare_patches);
4469 for (i = 0; i < code_len; i++) {
4471 for (pindex = start_index; pindex < patches->len; ++pindex) {
4472 patch_info = g_ptr_array_index (patches, pindex);
4473 if (patch_info->ip.i >= i)
4477 if (locs && locs [i]) {
4478 MonoDebugSourceLocation *loc = locs [i];
4481 findex = get_file_index (acfg, loc->source_file);
4482 emit_unset_mode (acfg);
4483 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4484 mono_debug_symfile_free_location (loc);
4487 #ifdef MONO_ARCH_AOT_SUPPORTED
4489 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4490 start_index = pindex;
4492 switch (patch_info->type) {
4493 case MONO_PATCH_INFO_NONE:
4495 case MONO_PATCH_INFO_GOT_OFFSET: {
4498 arch_emit_got_offset (acfg, code + i, &code_size);
4501 patch_info->type = MONO_PATCH_INFO_NONE;
4506 * If this patch is a call, try emitting a direct call instead of
4507 * through a PLT entry. This is possible if the called method is in
4508 * the same assembly and requires no initialization.
4510 direct_call = FALSE;
4511 external_call = FALSE;
4512 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4513 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4514 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4515 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4517 direct_call_target = callee_cfg->asm_symbol;
4518 patch_info->type = MONO_PATCH_INFO_NONE;
4519 acfg->stats.direct_calls ++;
4522 acfg->stats.all_calls ++;
4523 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4524 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4525 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4526 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4528 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4529 if (direct_pinvoke) {
4531 g_assert (strlen (direct_pinvoke) < 1000);
4532 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4535 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4536 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4537 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4538 /* Call to a C function implementing a jit icall */
4540 external_call = TRUE;
4541 g_assert (strlen (sym) < 1000);
4542 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4544 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4545 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4546 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4547 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4548 /* Call to a jit icall without a wrapper */
4550 external_call = TRUE;
4551 g_assert (strlen (sym) < 1000);
4552 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4557 patch_info->type = MONO_PATCH_INFO_NONE;
4558 acfg->stats.direct_calls ++;
4561 if (!got_only && !direct_call) {
4562 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4564 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4566 direct_call_target = plt_entry->symbol;
4568 /* Nullify the patch */
4569 patch_info->type = MONO_PATCH_INFO_NONE;
4570 plt_entry->jit_used = TRUE;
4577 arch_emit_direct_call (acfg, direct_call_target, external_call, &call_size);
4582 got_slot = get_got_offset (acfg, patch_info);
4584 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4591 #endif /* MONO_ARCH_AOT_SUPPORTED */
4594 /* Find next patch */
4596 for (pindex = start_index; pindex < patches->len; ++pindex) {
4597 patch_info = g_ptr_array_index (patches, pindex);
4598 if (patch_info->ip.i >= i)
4602 /* Try to emit multiple bytes at once */
4603 if (pindex < patches->len && patch_info->ip.i > i) {
4606 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4607 if (locs && locs [limit])
4611 emit_bytes (acfg, code + i, limit - i);
4614 emit_bytes (acfg, code + i, 1);
4625 * Modify SYMBOL so it only includes characters permissible in symbols.
4628 sanitize_symbol (char *symbol)
4630 int i, len = strlen (symbol);
4632 for (i = 0; i < len; ++i)
4633 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4638 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4640 char *name1, *name2, *cached;
4641 int i, j, len, count;
4644 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4645 if (!prefix || !*prefix)
4649 name1 = mono_method_full_name (method, TRUE);
4650 len = strlen (name1);
4651 name2 = malloc (strlen (prefix) + len + 16);
4652 memcpy (name2, prefix, strlen (prefix));
4653 j = strlen (prefix);
4654 for (i = 0; i < len; ++i) {
4655 if (isalnum (name1 [i])) {
4656 name2 [j ++] = name1 [i];
4657 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4659 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4662 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4671 while (g_hash_table_lookup (cache, name2)) {
4672 sprintf (name2 + j, "_%d", count);
4676 cached = g_strdup (name2);
4677 g_hash_table_insert (cache, cached, cached);
4683 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4688 char *debug_sym = NULL;
4689 char *symbol = NULL;
4690 int func_alignment = AOT_FUNC_ALIGNMENT;
4691 MonoMethodHeader *header;
4694 method = cfg->orig_method;
4695 code = cfg->native_code;
4696 header = cfg->header;
4698 method_index = get_method_index (acfg, method);
4699 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4702 /* Make the labels local */
4703 emit_section_change (acfg, ".text", 0);
4704 emit_alignment (acfg, func_alignment);
4706 if (acfg->global_symbols && acfg->need_no_dead_strip)
4707 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4709 emit_label (acfg, cfg->asm_symbol);
4711 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4713 * Write a C style symbol for every method, this has two uses:
4714 * - it works on platforms where the dwarf debugging info is not
4716 * - it allows the setting of breakpoints of aot-ed methods.
4718 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4720 if (acfg->need_no_dead_strip)
4721 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4722 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4723 emit_label (acfg, debug_sym);
4726 export_name = g_hash_table_lookup (acfg->export_names, method);
4728 /* Emit a global symbol for the method */
4729 emit_global_inner (acfg, export_name, TRUE);
4730 emit_label (acfg, export_name);
4733 if (cfg->verbose_level > 0)
4734 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4736 acfg->stats.code_size += cfg->code_len;
4738 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4740 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
4744 if (acfg->aot_opts.write_symbols) {
4745 emit_symbol_size (acfg, debug_sym, ".");
4749 emit_label (acfg, symbol);
4756 * Encode PATCH_INFO into its disk representation.
4759 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4763 switch (patch_info->type) {
4764 case MONO_PATCH_INFO_NONE:
4766 case MONO_PATCH_INFO_IMAGE:
4767 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4769 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4770 case MONO_PATCH_INFO_JIT_TLS_ID:
4771 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4772 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4774 case MONO_PATCH_INFO_METHOD_REL:
4775 encode_value ((gint)patch_info->data.offset, p, &p);
4777 case MONO_PATCH_INFO_SWITCH: {
4778 gpointer *table = (gpointer *)patch_info->data.table->table;
4781 encode_value (patch_info->data.table->table_size, p, &p);
4782 for (k = 0; k < patch_info->data.table->table_size; k++)
4783 encode_value ((int)(gssize)table [k], p, &p);
4786 case MONO_PATCH_INFO_METHODCONST:
4787 case MONO_PATCH_INFO_METHOD:
4788 case MONO_PATCH_INFO_METHOD_JUMP:
4789 case MONO_PATCH_INFO_ICALL_ADDR:
4790 case MONO_PATCH_INFO_METHOD_RGCTX:
4791 encode_method_ref (acfg, patch_info->data.method, p, &p);
4793 case MONO_PATCH_INFO_INTERNAL_METHOD:
4794 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4795 guint32 len = strlen (patch_info->data.name);
4797 encode_value (len, p, &p);
4799 memcpy (p, patch_info->data.name, len);
4804 case MONO_PATCH_INFO_LDSTR: {
4805 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4806 guint32 token = patch_info->data.token->token;
4807 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4808 encode_value (image_index, p, &p);
4809 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4812 case MONO_PATCH_INFO_RVA:
4813 case MONO_PATCH_INFO_DECLSEC:
4814 case MONO_PATCH_INFO_LDTOKEN:
4815 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4816 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4817 encode_value (patch_info->data.token->token, p, &p);
4818 encode_value (patch_info->data.token->has_context, p, &p);
4819 if (patch_info->data.token->has_context)
4820 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4822 case MONO_PATCH_INFO_EXC_NAME: {
4823 MonoClass *ex_class;
4826 mono_class_from_name (mono_defaults.exception_class->image,
4827 "System", patch_info->data.target);
4828 g_assert (ex_class);
4829 encode_klass_ref (acfg, ex_class, p, &p);
4832 case MONO_PATCH_INFO_R4:
4833 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4835 case MONO_PATCH_INFO_R8:
4836 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4837 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4839 case MONO_PATCH_INFO_VTABLE:
4840 case MONO_PATCH_INFO_CLASS:
4841 case MONO_PATCH_INFO_IID:
4842 case MONO_PATCH_INFO_ADJUSTED_IID:
4843 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4845 case MONO_PATCH_INFO_CLASS_INIT:
4846 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4847 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4849 case MONO_PATCH_INFO_FIELD:
4850 case MONO_PATCH_INFO_SFLDA:
4851 encode_field_info (acfg, patch_info->data.field, p, &p);
4853 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4855 case MONO_PATCH_INFO_RGCTX_FETCH: {
4856 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4861 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4862 * reference the same method, so encode the method only once.
4864 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4866 buf2 = g_malloc (1024);
4869 encode_method_ref (acfg, entry->method, p2, &p2);
4870 g_assert (p2 - buf2 < 1024);
4872 offset = add_to_blob (acfg, buf2, p2 - buf2);
4875 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4880 encode_value (offset, p, &p);
4881 g_assert ((int)entry->info_type < 256);
4882 g_assert (entry->data->type < 256);
4883 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4884 encode_patch (acfg, entry->data, p, &p);
4887 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4888 case MONO_PATCH_INFO_MONITOR_ENTER:
4889 case MONO_PATCH_INFO_MONITOR_EXIT:
4890 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4892 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4893 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4894 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4896 case MONO_PATCH_INFO_SIGNATURE:
4897 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4899 case MONO_PATCH_INFO_TLS_OFFSET:
4900 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
4902 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4903 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4904 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4906 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
4907 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
4910 encode_method_ref (acfg, info->method, p, &p);
4911 encode_value (info->entries->len, p, &p);
4912 for (i = 0; i < info->entries->len; ++i) {
4913 MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
4915 encode_value (template->info_type, p, &p);
4916 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
4917 case MONO_PATCH_INFO_CLASS:
4918 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
4920 case MONO_PATCH_INFO_FIELD:
4921 encode_field_info (acfg, template->data, p, &p);
4924 g_assert_not_reached ();
4931 g_warning ("unable to handle jump info %d", patch_info->type);
4932 g_assert_not_reached ();
4939 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4942 guint32 pindex, offset;
4943 MonoJumpInfo *patch_info;
4945 encode_value (n_patches, p, &p);
4947 for (pindex = 0; pindex < patches->len; ++pindex) {
4948 patch_info = g_ptr_array_index (patches, pindex);
4950 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4954 offset = get_got_offset (acfg, patch_info);
4955 encode_value (offset, p, &p);
4962 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4966 int pindex, buf_size, n_patches;
4968 MonoJumpInfo *patch_info;
4969 MonoMethodHeader *header;
4970 guint32 method_index;
4972 guint32 first_got_offset;
4974 method = cfg->orig_method;
4975 header = mono_method_get_header (method);
4977 method_index = get_method_index (acfg, method);
4979 /* Sort relocations */
4980 patches = g_ptr_array_new ();
4981 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4982 g_ptr_array_add (patches, patch_info);
4983 g_ptr_array_sort (patches, compare_patches);
4985 first_got_offset = acfg->cfgs [method_index]->got_offset;
4987 /**********************/
4988 /* Encode method info */
4989 /**********************/
4991 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4992 p = buf = g_malloc (buf_size);
4994 if (mono_class_get_cctor (method->klass))
4995 encode_klass_ref (acfg, method->klass, p, &p);
4997 /* Not needed when loading the method */
4998 encode_value (0, p, &p);
5001 if (cfg->opt & MONO_OPT_SHARED) {
5002 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5003 for (l = cfg->ldstr_list; l; l = l->next) {
5004 encode_value ((long)l->data, p, &p);
5008 /* Used only in shared mode */
5009 g_assert (!cfg->ldstr_list);
5012 for (pindex = 0; pindex < patches->len; ++pindex) {
5013 patch_info = g_ptr_array_index (patches, pindex);
5015 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5016 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5017 patch_info->type = MONO_PATCH_INFO_NONE;
5022 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5023 /* Stored in a GOT slot initialized at module load time */
5024 patch_info->type = MONO_PATCH_INFO_NONE;
5028 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5029 /* Stored in a GOT slot initialized at module load time */
5030 patch_info->type = MONO_PATCH_INFO_NONE;
5034 if (is_plt_patch (patch_info)) {
5035 /* Calls are made through the PLT */
5036 patch_info->type = MONO_PATCH_INFO_NONE;
5044 g_assert (cfg->has_got_slots);
5046 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5048 acfg->stats.info_size += p - buf;
5050 g_assert (p - buf < buf_size);
5052 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5057 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5059 guint32 cache_index;
5062 /* Reuse the unwind module to canonize and store unwind info entries */
5063 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5065 /* Use +/- 1 to distinguish 0s from missing entries */
5066 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5074 * It would be easier to use assembler symbols, but the caller needs an
5077 offset = acfg->unwind_info_offset;
5078 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5079 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5082 encode_value (encoded_len, p, &p);
5084 acfg->unwind_info_offset += encoded_len + (p - buf);
5090 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5093 int i, k, buf_size, method_index;
5094 guint32 debug_info_size;
5096 MonoMethodHeader *header;
5097 guint8 *p, *buf, *debug_info;
5098 MonoJitInfo *jinfo = cfg->jit_info;
5100 gboolean use_unwind_ops = FALSE;
5101 MonoSeqPointInfo *seq_points;
5103 method = cfg->orig_method;
5104 code = cfg->native_code;
5105 header = cfg->header;
5107 method_index = get_method_index (acfg, method);
5109 if (!acfg->aot_opts.nodebug) {
5110 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5113 debug_info_size = 0;
5116 seq_points = cfg->seq_point_info;
5118 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
5119 p = buf = g_malloc (buf_size);
5121 #ifdef MONO_ARCH_HAVE_XP_UNWIND
5122 use_unwind_ops = cfg->unwind_ops != NULL;
5125 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);
5127 encode_value (flags, p, &p);
5129 if (use_unwind_ops) {
5130 guint32 encoded_len;
5134 * This is a duplicate of the data in the .debug_frame section, but that
5135 * section cannot be accessed using the dl interface.
5137 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5138 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5141 encode_value (jinfo->used_regs, p, &p);
5144 /*Encode the number of holes before the number of clauses to make decoding easier*/
5145 if (jinfo->has_try_block_holes) {
5146 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5147 encode_value (table->num_holes, p, &p);
5150 /* Exception table */
5151 if (cfg->compile_llvm) {
5153 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5154 * since the information is only available to llc. Instead, we let llc save the data
5155 * into the LSDA, and read it from there at runtime.
5157 /* The assembly might be CIL stripped so emit the data ourselves */
5158 if (header->num_clauses)
5159 encode_value (header->num_clauses, p, &p);
5161 for (k = 0; k < header->num_clauses; ++k) {
5162 MonoExceptionClause *clause;
5164 clause = &header->clauses [k];
5166 encode_value (clause->flags, p, &p);
5167 if (clause->data.catch_class) {
5168 encode_value (1, p, &p);
5169 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5171 encode_value (0, p, &p);
5174 /* Emit a list of nesting clauses */
5175 for (i = 0; i < header->num_clauses; ++i) {
5177 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5179 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5181 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5182 encode_value (i, p, &p);
5184 encode_value (-1, p, &p);
5187 if (jinfo->num_clauses)
5188 encode_value (jinfo->num_clauses, p, &p);
5190 for (k = 0; k < jinfo->num_clauses; ++k) {
5191 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5193 encode_value (ei->flags, p, &p);
5194 encode_value (ei->exvar_offset, p, &p);
5196 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5197 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5199 if (ei->data.catch_class) {
5200 encode_value (1, p, &p);
5201 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
5203 encode_value (0, p, &p);
5207 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5208 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5209 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5213 if (jinfo->has_generic_jit_info) {
5214 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5215 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5219 encode_value (gi->nlocs, p, &p);
5221 for (i = 0; i < gi->nlocs; ++i) {
5222 MonoDwarfLocListEntry *entry = &gi->locations [i];
5224 encode_value (entry->is_reg ? 1 : 0, p, &p);
5225 encode_value (entry->reg, p, &p);
5227 encode_value (entry->offset, p, &p);
5229 g_assert (entry->from == 0);
5231 encode_value (entry->from, p, &p);
5232 encode_value (entry->to, p, &p);
5235 if (!cfg->compile_llvm) {
5236 encode_value (gi->has_this ? 1 : 0, p, &p);
5237 encode_value (gi->this_reg, p, &p);
5238 encode_value (gi->this_offset, p, &p);
5243 * Need to encode jinfo->method too, since it is not equal to 'method'
5244 * when using generic sharing.
5246 encode_method_ref (acfg, jinfo->method, p, &p);
5248 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5249 MonoMethodInflated *inflated;
5250 MonoGenericContext *context;
5251 MonoGenericInst *inst;
5253 g_assert (jinfo->method->is_inflated);
5254 inflated = (MonoMethodInflated*)jinfo->method;
5255 context = &inflated->context;
5257 encode_value (1, p, &p);
5258 if (context->class_inst) {
5259 inst = context->class_inst;
5261 encode_value (inst->type_argc, p, &p);
5262 for (i = 0; i < inst->type_argc; ++i)
5263 encode_value (gsctx->var_is_vt [i], p, &p);
5265 encode_value (0, p, &p);
5267 if (context->method_inst) {
5268 inst = context->method_inst;
5270 encode_value (inst->type_argc, p, &p);
5271 for (i = 0; i < inst->type_argc; ++i)
5272 encode_value (gsctx->mvar_is_vt [i], p, &p);
5274 encode_value (0, p, &p);
5277 encode_value (0, p, &p);
5281 if (jinfo->has_try_block_holes) {
5282 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5283 for (i = 0; i < table->num_holes; ++i) {
5284 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5285 encode_value (hole->clause, p, &p);
5286 encode_value (hole->length, p, &p);
5287 encode_value (hole->offset, p, &p);
5291 if (jinfo->has_arch_eh_info) {
5292 MonoArchEHJitInfo *eh_info;
5294 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5295 encode_value (eh_info->stack_size, p, &p);
5299 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5301 encode_value (seq_points->len, p, &p);
5302 last_il_offset = last_native_offset = 0;
5303 for (i = 0; i < seq_points->len; ++i) {
5304 SeqPoint *sp = &seq_points->seq_points [i];
5305 il_offset = sp->il_offset;
5306 native_offset = sp->native_offset;
5307 encode_value (il_offset - last_il_offset, p, &p);
5308 encode_value (native_offset - last_native_offset, p, &p);
5309 last_il_offset = il_offset;
5310 last_native_offset = native_offset;
5312 encode_value (sp->next_len, p, &p);
5313 for (j = 0; j < sp->next_len; ++j)
5314 encode_value (sp->next [j], p, &p);
5318 g_assert (debug_info_size < buf_size);
5320 encode_value (debug_info_size, p, &p);
5321 if (debug_info_size) {
5322 memcpy (p, debug_info, debug_info_size);
5323 p += debug_info_size;
5324 g_free (debug_info);
5329 encode_value (cfg->gc_map_size, p, &p);
5330 /* The GC map requires 4 bytes of alignment */
5331 while ((gsize)p % 4)
5333 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5334 p += cfg->gc_map_size;
5337 acfg->stats.ex_info_size += p - buf;
5339 g_assert (p - buf < buf_size);
5342 /* The GC Map requires 4 byte alignment */
5343 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5348 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5350 MonoClass *klass = mono_class_get (acfg->image, token);
5352 int i, buf_size, res;
5353 gboolean no_special_static, cant_encode;
5354 gpointer iter = NULL;
5357 mono_loader_clear_error ();
5361 p = buf = g_malloc (buf_size);
5363 /* Mark as unusable */
5364 encode_value (-1, p, &p);
5366 res = add_to_blob (acfg, buf, p - buf);
5372 buf_size = 10240 + (klass->vtable_size * 16);
5373 p = buf = g_malloc (buf_size);
5377 mono_class_init (klass);
5379 mono_class_get_nested_types (klass, &iter);
5380 g_assert (klass->nested_classes_inited);
5382 mono_class_setup_vtable (klass);
5385 * Emit all the information which is required for creating vtables so
5386 * the runtime does not need to create the MonoMethod structures which
5387 * take up a lot of space.
5390 no_special_static = !mono_class_has_special_static_fields (klass);
5392 /* Check whenever we have enough info to encode the vtable */
5393 cant_encode = FALSE;
5394 for (i = 0; i < klass->vtable_size; ++i) {
5395 MonoMethod *cm = klass->vtable [i];
5397 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5401 mono_class_has_finalizer (klass);
5403 if (klass->generic_container || cant_encode) {
5404 encode_value (-1, p, &p);
5406 encode_value (klass->vtable_size, p, &p);
5407 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);
5408 if (klass->has_cctor)
5409 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5410 if (klass->has_finalize)
5411 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5413 encode_value (klass->instance_size, p, &p);
5414 encode_value (mono_class_data_size (klass), p, &p);
5415 encode_value (klass->packing_size, p, &p);
5416 encode_value (klass->min_align, p, &p);
5418 for (i = 0; i < klass->vtable_size; ++i) {
5419 MonoMethod *cm = klass->vtable [i];
5422 encode_method_ref (acfg, cm, p, &p);
5424 encode_value (0, p, &p);
5428 acfg->stats.class_info_size += p - buf;
5430 g_assert (p - buf < buf_size);
5431 res = add_to_blob (acfg, buf, p - buf);
5438 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5440 char *debug_sym = NULL;
5443 case MONO_PATCH_INFO_METHOD:
5444 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5446 case MONO_PATCH_INFO_INTERNAL_METHOD:
5447 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5449 case MONO_PATCH_INFO_CLASS_INIT:
5450 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5451 sanitize_symbol (debug_sym);
5453 case MONO_PATCH_INFO_RGCTX_FETCH:
5454 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5456 case MONO_PATCH_INFO_ICALL_ADDR: {
5457 char *s = get_debug_sym (ji->data.method, "", cache);
5459 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5463 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5464 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5466 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5467 debug_sym = g_strdup_printf ("plt__generic_class_init");
5477 * Calls made from AOTed code are routed through a table of jumps similar to the
5478 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5479 * control to the AOT runtime through a trampoline.
5482 emit_plt (MonoAotCompile *acfg)
5488 sprintf (symbol, "plt");
5490 emit_section_change (acfg, ".text", 0);
5491 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5492 emit_label (acfg, symbol);
5493 emit_label (acfg, acfg->plt_symbol);
5495 for (i = 0; i < acfg->plt_offset; ++i) {
5496 char *debug_sym = NULL;
5497 MonoPltEntry *plt_entry = NULL;
5502 * The first plt entry is unused.
5506 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5511 * If the target is directly callable, alias the plt symbol to point to
5513 * FIXME: Use this to simplify emit_and_reloc_code ().
5514 * FIXME: Avoid the got slot.
5515 * FIXME: Add support to the binary writer.
5517 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5518 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5521 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5522 /* LLVM calls the PLT entries using bl, so emit a stub */
5523 emit_set_thumb_mode (acfg);
5524 fprintf (acfg->fp, "\n.thumb_func\n");
5525 emit_label (acfg, plt_entry->llvm_symbol);
5526 fprintf (acfg->fp, "bx pc\n");
5527 fprintf (acfg->fp, "nop\n");
5528 emit_set_arm_mode (acfg);
5529 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5531 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5538 debug_sym = plt_entry->debug_sym;
5540 if (acfg->thumb_mixed && !plt_entry->jit_used)
5541 /* Emit only a thumb version */
5544 if (acfg->llvm && !acfg->thumb_mixed)
5545 emit_label (acfg, plt_entry->llvm_symbol);
5548 if (acfg->need_no_dead_strip) {
5549 emit_unset_mode (acfg);
5550 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5552 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5553 emit_label (acfg, debug_sym);
5556 emit_label (acfg, plt_entry->symbol);
5558 arch_emit_plt_entry (acfg, i);
5561 emit_symbol_size (acfg, debug_sym, ".");
5564 if (acfg->thumb_mixed) {
5565 /* Make sure the ARM symbols don't alias the thumb ones */
5566 emit_zero_bytes (acfg, 16);
5569 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5572 for (i = 0; i < acfg->plt_offset; ++i) {
5573 char *debug_sym = NULL;
5574 MonoPltEntry *plt_entry = NULL;
5580 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5583 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5586 /* Skip plt entries not actually called by LLVM code */
5587 if (!plt_entry->llvm_used)
5590 if (acfg->aot_opts.write_symbols) {
5591 if (plt_entry->debug_sym)
5592 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5596 #if defined(TARGET_MACH)
5597 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5598 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5600 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5601 emit_label (acfg, debug_sym);
5603 fprintf (acfg->fp, "\n.thumb_func\n");
5605 emit_label (acfg, plt_entry->llvm_symbol);
5607 arch_emit_llvm_plt_entry (acfg, i);
5610 emit_symbol_size (acfg, debug_sym, ".");
5616 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5618 sprintf (symbol, "plt_end");
5619 emit_label (acfg, symbol);
5623 * emit_trampoline_full:
5625 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5626 * create_jit_info_for_trampoline ().
5628 static G_GNUC_UNUSED void
5629 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5631 char start_symbol [256];
5632 char end_symbol [256];
5634 guint32 buf_size, info_offset;
5635 MonoJumpInfo *patch_info;
5646 code_size = info->code_size;
5648 unwind_ops = info->unwind_ops;
5650 #ifdef __native_client_codegen__
5651 mono_nacl_fix_patches (code, ji);
5656 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5658 emit_section_change (acfg, ".text", 0);
5659 emit_global (acfg, start_symbol, TRUE);
5660 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5661 emit_label (acfg, start_symbol);
5663 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5664 emit_label (acfg, symbol);
5667 * The code should access everything through the GOT, so we pass
5670 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5672 emit_symbol_size (acfg, start_symbol, ".");
5675 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5676 emit_label (acfg, end_symbol);
5681 /* Sort relocations */
5682 patches = g_ptr_array_new ();
5683 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5684 if (patch_info->type != MONO_PATCH_INFO_NONE)
5685 g_ptr_array_add (patches, patch_info);
5686 g_ptr_array_sort (patches, compare_patches);
5688 buf_size = patches->len * 128 + 128;
5689 buf = g_malloc (buf_size);
5692 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5693 g_assert (p - buf < buf_size);
5695 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5697 info_offset = add_to_blob (acfg, buf, p - buf);
5699 emit_section_change (acfg, RODATA_SECT, 0);
5700 emit_global (acfg, symbol, FALSE);
5701 emit_label (acfg, symbol);
5703 emit_int32 (acfg, info_offset);
5707 guint32 encoded_len;
5711 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5713 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5714 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5717 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5718 emit_int32 (acfg, uw_offset);
5721 /* Emit debug info */
5725 sprintf (symbol, "%s", name);
5726 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5729 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5733 static G_GNUC_UNUSED void
5734 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5736 emit_trampoline_full (acfg, got_offset, info, FALSE);
5740 emit_trampolines (MonoAotCompile *acfg)
5743 char end_symbol [256];
5744 int i, tramp_got_offset;
5745 MonoAotTrampoline ntype;
5746 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5750 if (!acfg->aot_opts.full_aot)
5753 g_assert (acfg->image->assembly);
5755 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5756 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5757 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5758 MonoTrampInfo *info;
5761 * Emit the generic trampolines.
5763 * We could save some code by treating the generic trampolines as a wrapper
5764 * method, but that approach has its own complexities, so we choose the simpler
5767 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5768 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5769 #ifdef DISABLE_REMOTING
5770 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5773 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5774 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5777 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5778 emit_trampoline (acfg, acfg->got_offset, info);
5781 mono_arch_get_nullified_class_init_trampoline (&info);
5782 emit_trampoline (acfg, acfg->got_offset, info);
5783 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5784 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5785 emit_trampoline (acfg, acfg->got_offset, info);
5786 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5787 emit_trampoline (acfg, acfg->got_offset, info);
5790 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5791 emit_trampoline (acfg, acfg->got_offset, info);
5793 /* Emit the exception related code pieces */
5794 mono_arch_get_restore_context (&info, TRUE);
5795 emit_trampoline (acfg, acfg->got_offset, info);
5796 mono_arch_get_call_filter (&info, TRUE);
5797 emit_trampoline (acfg, acfg->got_offset, info);
5798 mono_arch_get_throw_exception (&info, TRUE);
5799 emit_trampoline (acfg, acfg->got_offset, info);
5800 mono_arch_get_rethrow_exception (&info, TRUE);
5801 emit_trampoline (acfg, acfg->got_offset, info);
5802 mono_arch_get_throw_corlib_exception (&info, TRUE);
5803 emit_trampoline (acfg, acfg->got_offset, info);
5805 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5806 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5808 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5810 /* Create a separate out trampoline for more information in stack traces */
5811 info->name = g_strdup ("gsharedvt_out_trampoline");
5812 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5816 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5818 GSList *l = mono_arch_get_trampolines (TRUE);
5821 MonoTrampInfo *info = l->data;
5823 emit_trampoline (acfg, acfg->got_offset, info);
5829 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5832 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5833 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5834 emit_trampoline (acfg, acfg->got_offset, info);
5836 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5837 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5838 emit_trampoline (acfg, acfg->got_offset, info);
5841 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5842 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5843 emit_trampoline (acfg, acfg->got_offset, info);
5849 /* delegate_invoke_impl trampolines */
5850 l = mono_arch_get_delegate_invoke_impls ();
5852 MonoTrampInfo *info = l->data;
5854 emit_trampoline (acfg, acfg->got_offset, info);
5859 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5861 /* Emit trampolines which are numerous */
5864 * These include the following:
5865 * - specific trampolines
5866 * - static rgctx invoke trampolines
5868 * These trampolines have the same code, they are parameterized by GOT
5870 * They are defined in this file, in the arch_... routines instead of
5871 * in tramp-<ARCH>.c, since it is easier to do it this way.
5875 * When running in aot-only mode, we can't create specific trampolines at
5876 * runtime, so we create a few, and save them in the AOT file.
5877 * Normal trampolines embed their argument as a literal inside the
5878 * trampoline code, we can't do that here, so instead we embed an offset
5879 * which needs to be added to the trampoline address to get the address of
5880 * the GOT slot which contains the argument value.
5881 * The generated trampolines jump to the generic trampolines using another
5882 * GOT slot, which will be setup by the AOT loader to point to the
5883 * generic trampoline code of the given type.
5887 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5891 emit_section_change (acfg, ".text", 0);
5893 tramp_got_offset = acfg->got_offset;
5895 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5897 case MONO_AOT_TRAMP_SPECIFIC:
5898 sprintf (symbol, "specific_trampolines");
5900 case MONO_AOT_TRAMP_STATIC_RGCTX:
5901 sprintf (symbol, "static_rgctx_trampolines");
5903 case MONO_AOT_TRAMP_IMT_THUNK:
5904 sprintf (symbol, "imt_thunks");
5906 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5907 sprintf (symbol, "gsharedvt_arg_trampolines");
5910 g_assert_not_reached ();
5913 sprintf (end_symbol, "%s_e", symbol);
5915 if (acfg->aot_opts.write_symbols)
5916 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5918 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5919 emit_label (acfg, symbol);
5921 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5923 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5927 case MONO_AOT_TRAMP_SPECIFIC:
5928 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5929 tramp_got_offset += 2;
5931 case MONO_AOT_TRAMP_STATIC_RGCTX:
5932 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5933 tramp_got_offset += 2;
5935 case MONO_AOT_TRAMP_IMT_THUNK:
5936 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5937 tramp_got_offset += 1;
5939 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5940 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
5941 tramp_got_offset += 2;
5944 g_assert_not_reached ();
5946 #ifdef __native_client_codegen__
5947 /* align to avoid 32-byte boundary crossings */
5948 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5951 if (!acfg->trampoline_size [ntype]) {
5952 g_assert (tramp_size);
5953 acfg->trampoline_size [ntype] = tramp_size;
5957 emit_label (acfg, end_symbol);
5960 arch_emit_specific_trampoline_pages (acfg);
5962 /* Reserve some entries at the end of the GOT for our use */
5963 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5966 acfg->got_offset += acfg->num_trampoline_got_entries;
5970 str_begins_with (const char *str1, const char *str2)
5972 int len = strlen (str2);
5973 return strncmp (str1, str2, len) == 0;
5977 mono_aot_readonly_field_override (MonoClassField *field)
5980 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5981 char *p = rdv->name;
5983 len = strlen (field->parent->name_space);
5984 if (strncmp (p, field->parent->name_space, len))
5989 len = strlen (field->parent->name);
5990 if (strncmp (p, field->parent->name, len))
5995 if (strcmp (p, field->name))
5997 switch (rdv->type) {
5999 return &rdv->value.i1;
6001 return &rdv->value.i2;
6003 return &rdv->value.i4;
6012 add_readonly_value (MonoAotOptions *opts, const char *val)
6017 /* the format of val is:
6018 * namespace.typename.fieldname=type/value
6019 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6021 fval = strrchr (val, '/');
6023 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6026 tval = strrchr (val, '=');
6028 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6031 rdv = g_new0 (ReadOnlyValue, 1);
6032 rdv->name = g_malloc0 (tval - val + 1);
6033 memcpy (rdv->name, val, tval - val);
6036 if (strncmp (tval, "i1", 2) == 0) {
6037 rdv->value.i1 = atoi (fval);
6038 rdv->type = MONO_TYPE_I1;
6039 } else if (strncmp (tval, "i2", 2) == 0) {
6040 rdv->value.i2 = atoi (fval);
6041 rdv->type = MONO_TYPE_I2;
6042 } else if (strncmp (tval, "i4", 2) == 0) {
6043 rdv->value.i4 = atoi (fval);
6044 rdv->type = MONO_TYPE_I4;
6046 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6049 rdv->next = readonly_values;
6050 readonly_values = rdv;
6054 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6056 gchar **args, **ptr;
6058 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6059 for (ptr = args; ptr && *ptr; ptr ++) {
6060 const char *arg = *ptr;
6062 if (str_begins_with (arg, "outfile=")) {
6063 opts->outfile = g_strdup (arg + strlen ("outfile="));
6064 } else if (str_begins_with (arg, "save-temps")) {
6065 opts->save_temps = TRUE;
6066 } else if (str_begins_with (arg, "keep-temps")) {
6067 opts->save_temps = TRUE;
6068 } else if (str_begins_with (arg, "write-symbols")) {
6069 opts->write_symbols = TRUE;
6070 } else if (str_begins_with (arg, "no-write-symbols")) {
6071 opts->write_symbols = FALSE;
6072 } else if (str_begins_with (arg, "metadata-only")) {
6073 opts->metadata_only = TRUE;
6074 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6075 opts->bind_to_runtime_version = TRUE;
6076 } else if (str_begins_with (arg, "full")) {
6077 opts->full_aot = TRUE;
6078 } else if (str_begins_with (arg, "threads=")) {
6079 opts->nthreads = atoi (arg + strlen ("threads="));
6080 } else if (str_begins_with (arg, "static")) {
6081 opts->static_link = TRUE;
6082 opts->no_dlsym = TRUE;
6083 } else if (str_begins_with (arg, "asmonly")) {
6084 opts->asm_only = TRUE;
6085 } else if (str_begins_with (arg, "asmwriter")) {
6086 opts->asm_writer = TRUE;
6087 } else if (str_begins_with (arg, "nodebug")) {
6088 opts->nodebug = TRUE;
6089 } else if (str_begins_with (arg, "dwarfdebug")) {
6090 opts->dwarf_debug = TRUE;
6091 } else if (str_begins_with (arg, "nopagetrampolines")) {
6092 opts->use_trampolines_page = FALSE;
6093 } else if (str_begins_with (arg, "ntrampolines=")) {
6094 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6095 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6096 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6097 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6098 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6099 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6100 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6101 } else if (str_begins_with (arg, "autoreg")) {
6102 opts->autoreg = TRUE;
6103 } else if (str_begins_with (arg, "tool-prefix=")) {
6104 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6105 } else if (str_begins_with (arg, "soft-debug")) {
6106 opts->soft_debug = TRUE;
6107 } else if (str_begins_with (arg, "direct-pinvoke")) {
6108 opts->direct_pinvoke = TRUE;
6109 } else if (str_begins_with (arg, "direct-icalls")) {
6110 opts->direct_icalls = TRUE;
6111 #if defined(TARGET_ARM)
6112 } else if (str_begins_with (arg, "iphone-abi")) {
6113 // older full-aot users did depend on this.
6115 } else if (str_begins_with (arg, "no-direct-calls")) {
6116 opts->no_direct_calls = TRUE;
6117 } else if (str_begins_with (arg, "print-skipped")) {
6118 opts->print_skipped_methods = TRUE;
6119 } else if (str_begins_with (arg, "stats")) {
6121 } else if (str_begins_with (arg, "no-instances")) {
6122 opts->no_instances = TRUE;
6123 } else if (str_begins_with (arg, "log-generics")) {
6124 opts->log_generics = TRUE;
6125 } else if (str_begins_with (arg, "mtriple=")) {
6126 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6127 } else if (str_begins_with (arg, "llvm-path=")) {
6128 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6129 } else if (str_begins_with (arg, "readonly-value=")) {
6130 add_readonly_value (opts, arg + strlen ("readonly-value="));
6131 } else if (str_begins_with (arg, "info")) {
6132 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6134 } else if (str_begins_with (arg, "gc-maps")) {
6135 mini_gc_enable_gc_maps_for_aot ();
6136 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6137 printf ("Supported options for --aot:\n");
6138 printf (" outfile=\n");
6139 printf (" save-temps\n");
6140 printf (" keep-temps\n");
6141 printf (" write-symbols\n");
6142 printf (" metadata-only\n");
6143 printf (" bind-to-runtime-version\n");
6145 printf (" threads=\n");
6146 printf (" static\n");
6147 printf (" asmonly\n");
6148 printf (" asmwriter\n");
6149 printf (" nodebug\n");
6150 printf (" dwarfdebug\n");
6151 printf (" ntrampolines=\n");
6152 printf (" nrgctx-trampolines=\n");
6153 printf (" nimt-trampolines=\n");
6154 printf (" ngsharedvt-trampolines=\n");
6155 printf (" autoreg\n");
6156 printf (" tool-prefix=\n");
6157 printf (" readonly-value=\n");
6158 printf (" soft-debug\n");
6159 printf (" gc-maps\n");
6160 printf (" print-skipped\n");
6161 printf (" no-instances\n");
6162 printf (" stats\n");
6164 printf (" help/?\n");
6167 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6172 if (opts->use_trampolines_page) {
6173 opts->ntrampolines = 0;
6174 opts->nrgctx_trampolines = 0;
6175 opts->nimt_trampolines = 0;
6176 opts->ngsharedvt_arg_trampolines = 0;
6182 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6184 MonoMethod *method = (MonoMethod*)key;
6185 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6186 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6187 MonoAotCompile *acfg = user_data;
6189 new_ji->image = ji->image;
6190 new_ji->token = ji->token;
6191 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6195 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6197 if (klass->type_token)
6199 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6202 return can_encode_class (acfg, klass->element_class);
6207 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6209 if (method->wrapper_type) {
6210 switch (method->wrapper_type) {
6211 case MONO_WRAPPER_NONE:
6212 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6213 case MONO_WRAPPER_XDOMAIN_INVOKE:
6214 case MONO_WRAPPER_STFLD:
6215 case MONO_WRAPPER_LDFLD:
6216 case MONO_WRAPPER_LDFLDA:
6217 case MONO_WRAPPER_LDFLD_REMOTE:
6218 case MONO_WRAPPER_STFLD_REMOTE:
6219 case MONO_WRAPPER_STELEMREF:
6220 case MONO_WRAPPER_ISINST:
6221 case MONO_WRAPPER_PROXY_ISINST:
6222 case MONO_WRAPPER_ALLOC:
6223 case MONO_WRAPPER_REMOTING_INVOKE:
6224 case MONO_WRAPPER_UNKNOWN:
6225 case MONO_WRAPPER_WRITE_BARRIER:
6226 case MONO_WRAPPER_DELEGATE_INVOKE:
6227 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6228 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6229 case MONO_WRAPPER_SYNCHRONIZED:
6231 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6232 case MONO_WRAPPER_CASTCLASS: {
6233 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6242 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6246 if (!method->token) {
6247 /* The method is part of a constructed type like Int[,].Set (). */
6248 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6249 if (method->klass->rank)
6259 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6261 switch (patch_info->type) {
6262 case MONO_PATCH_INFO_METHOD:
6263 case MONO_PATCH_INFO_METHODCONST: {
6264 MonoMethod *method = patch_info->data.method;
6266 return can_encode_method (acfg, method);
6268 case MONO_PATCH_INFO_VTABLE:
6269 case MONO_PATCH_INFO_CLASS_INIT:
6270 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6271 case MONO_PATCH_INFO_CLASS:
6272 case MONO_PATCH_INFO_IID:
6273 case MONO_PATCH_INFO_ADJUSTED_IID:
6274 if (!can_encode_class (acfg, patch_info->data.klass)) {
6275 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6279 case MONO_PATCH_INFO_RGCTX_FETCH: {
6280 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6282 if (!can_encode_method (acfg, entry->method))
6284 if (!can_encode_patch (acfg, entry->data))
6298 * AOT compile a given method.
6299 * This function might be called by multiple threads, so it must be thread-safe.
6302 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6305 MonoJumpInfo *patch_info;
6308 MonoMethod *wrapped;
6310 if (acfg->aot_opts.metadata_only)
6313 mono_acfg_lock (acfg);
6314 index = get_method_index (acfg, method);
6315 mono_acfg_unlock (acfg);
6317 /* fixme: maybe we can also precompile wrapper methods */
6318 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6319 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6320 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6321 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6325 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6328 wrapped = mono_marshal_method_from_wrapper (method);
6329 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6330 // FIXME: The wrapper should be generic too, but it is not
6333 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6336 InterlockedIncrement (&acfg->stats.mcount);
6339 if (method->is_generic || method->klass->generic_container) {
6340 InterlockedIncrement (&acfg->stats.genericcount);
6345 //acfg->aot_opts.print_skipped_methods = TRUE;
6348 * Since these methods are the only ones which are compiled with
6349 * AOT support, and they are not used by runtime startup/shutdown code,
6350 * the runtime will not see AOT methods during AOT compilation,so it
6351 * does not need to support them by creating a fake GOT etc.
6353 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6354 mono_loader_clear_error ();
6356 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6357 if (acfg->aot_opts.print_skipped_methods)
6358 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6359 InterlockedIncrement (&acfg->stats.genericcount);
6362 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6363 if (acfg->aot_opts.print_skipped_methods)
6364 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6365 /* Let the exception happen at runtime */
6369 if (cfg->disable_aot) {
6370 if (acfg->aot_opts.print_skipped_methods)
6371 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6372 InterlockedIncrement (&acfg->stats.ocount);
6373 mono_destroy_compile (cfg);
6376 cfg->method_index = index;
6378 /* Nullify patches which need no aot processing */
6379 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6380 switch (patch_info->type) {
6381 case MONO_PATCH_INFO_LABEL:
6382 case MONO_PATCH_INFO_BB:
6383 patch_info->type = MONO_PATCH_INFO_NONE;
6390 /* Collect method->token associations from the cfg */
6391 mono_acfg_lock (acfg);
6392 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6393 mono_acfg_unlock (acfg);
6396 * Check for absolute addresses.
6399 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6400 switch (patch_info->type) {
6401 case MONO_PATCH_INFO_ABS:
6402 /* unable to handle this */
6411 if (acfg->aot_opts.print_skipped_methods)
6412 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6413 InterlockedIncrement (&acfg->stats.abscount);
6414 mono_destroy_compile (cfg);
6418 /* Lock for the rest of the code */
6419 mono_acfg_lock (acfg);
6422 * Check for methods/klasses we can't encode.
6425 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6426 if (!can_encode_patch (acfg, patch_info))
6431 if (acfg->aot_opts.print_skipped_methods)
6432 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6433 acfg->stats.ocount++;
6434 mono_destroy_compile (cfg);
6435 mono_acfg_unlock (acfg);
6439 /* Adds generic instances referenced by this method */
6441 * The depth is used to avoid infinite loops when generic virtual recursion is
6444 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6445 if (!acfg->aot_opts.no_instances && depth < 32) {
6446 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6447 switch (patch_info->type) {
6448 case MONO_PATCH_INFO_METHOD: {
6449 MonoMethod *m = patch_info->data.method;
6450 if (m->is_inflated) {
6451 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6452 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6453 !method_has_type_vars (m)) {
6454 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6455 if (acfg->aot_opts.full_aot)
6456 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6458 add_extra_method_with_depth (acfg, m, depth + 1);
6459 add_types_from_method_header (acfg, m);
6462 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6464 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6465 add_extra_method_with_depth (acfg, m, depth + 1);
6468 case MONO_PATCH_INFO_VTABLE: {
6469 MonoClass *klass = patch_info->data.klass;
6471 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6472 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6475 case MONO_PATCH_INFO_SFLDA: {
6476 MonoClass *klass = patch_info->data.field->parent;
6478 /* The .cctor needs to run at runtime. */
6479 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6480 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6489 /* Determine whenever the method has GOT slots */
6490 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6491 switch (patch_info->type) {
6492 case MONO_PATCH_INFO_GOT_OFFSET:
6493 case MONO_PATCH_INFO_NONE:
6494 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6496 case MONO_PATCH_INFO_IMAGE:
6497 /* The assembly is stored in GOT slot 0 */
6498 if (patch_info->data.image != acfg->image)
6499 cfg->has_got_slots = TRUE;
6502 if (!is_plt_patch (patch_info))
6503 cfg->has_got_slots = TRUE;
6508 if (!cfg->has_got_slots)
6509 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6512 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6514 /* Make a copy of the patch info which is in the mempool */
6516 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6518 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6519 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6522 patches = new_patch_info;
6524 patches_end->next = new_patch_info;
6525 patches_end = new_patch_info;
6527 cfg->patch_info = patches;
6529 /* Make a copy of the unwind info */
6531 GSList *l, *unwind_ops;
6535 for (l = cfg->unwind_ops; l; l = l->next) {
6536 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6537 memcpy (op, l->data, sizeof (MonoUnwindOp));
6538 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6540 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6542 /* Make a copy of the argument/local info */
6544 MonoInst **args, **locals;
6545 MonoMethodSignature *sig;
6546 MonoMethodHeader *header;
6549 sig = mono_method_signature (method);
6550 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6551 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6552 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6553 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6557 header = mono_method_get_header (method);
6558 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6559 for (i = 0; i < header->num_locals; ++i) {
6560 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6561 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6563 cfg->locals = locals;
6566 /* Free some fields used by cfg to conserve memory */
6567 mono_mempool_destroy (cfg->mempool);
6568 cfg->mempool = NULL;
6569 g_free (cfg->varinfo);
6570 cfg->varinfo = NULL;
6574 mono_regstate_free (cfg->rs);
6578 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6580 while (index >= acfg->cfgs_size) {
6581 MonoCompile **new_cfgs;
6584 new_size = acfg->cfgs_size * 2;
6585 new_cfgs = g_new0 (MonoCompile*, new_size);
6586 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6587 g_free (acfg->cfgs);
6588 acfg->cfgs = new_cfgs;
6589 acfg->cfgs_size = new_size;
6591 acfg->cfgs [index] = cfg;
6593 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6596 if (cfg->orig_method->wrapper_type)
6597 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6600 mono_acfg_unlock (acfg);
6602 InterlockedIncrement (&acfg->stats.ccount);
6606 compile_thread_main (gpointer *user_data)
6608 MonoDomain *domain = user_data [0];
6609 MonoAotCompile *acfg = user_data [1];
6610 GPtrArray *methods = user_data [2];
6613 mono_thread_attach (domain);
6615 for (i = 0; i < methods->len; ++i)
6616 compile_method (acfg, g_ptr_array_index (methods, i));
6620 load_profile_files (MonoAotCompile *acfg)
6624 int file_index, res, method_index, i;
6627 GList *unordered, *l;
6632 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6634 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6639 infile = fopen (tmp, "r");
6642 printf ("Using profile data file '%s'\n", tmp);
6647 res = fscanf (infile, "%32s\n", ver);
6648 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6649 printf ("Profile file has wrong version or invalid.\n");
6656 MonoMethodDesc *desc;
6659 if (fgets (name, 1023, infile) == NULL)
6662 /* Kill the newline */
6663 if (strlen (name) > 0)
6664 name [strlen (name) - 1] = '\0';
6666 desc = mono_method_desc_new (name, TRUE);
6668 method = mono_method_desc_search_in_image (desc, acfg->image);
6670 if (method && mono_method_get_token (method)) {
6671 token = mono_method_get_token (method);
6672 method_index = mono_metadata_token_index (token) - 1;
6675 for (i = 0; i < acfg->method_order->len; ++i) {
6676 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6682 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6684 //printf ("No method found matching '%s'.\n", name);
6690 /* Add missing methods */
6692 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6694 for (i = 0; i < acfg->method_order->len; ++i) {
6695 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6701 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6703 unordered = g_list_reverse (unordered);
6704 for (l = unordered; l; l = l->next)
6705 g_ptr_array_add (acfg->method_order, l->data);
6708 /* Used by the LLVM backend */
6710 mono_aot_get_got_offset (MonoJumpInfo *ji)
6712 return get_got_offset (llvm_acfg, ji);
6716 mono_aot_get_method_name (MonoCompile *cfg)
6718 if (llvm_acfg->aot_opts.static_link)
6719 /* Include the assembly name too to avoid duplicate symbol errors */
6720 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6722 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6726 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6728 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6729 MonoPltEntry *plt_entry;
6732 ji->data.target = data;
6734 if (!can_encode_patch (llvm_acfg, ji))
6737 plt_entry = get_plt_entry (llvm_acfg, ji);
6738 plt_entry->llvm_used = TRUE;
6740 #if defined(TARGET_MACH)
6741 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6743 return g_strdup_printf (plt_entry->llvm_symbol);
6748 mono_aot_get_method_index (MonoMethod *method)
6750 g_assert (llvm_acfg);
6751 return get_method_index (llvm_acfg, method);
6755 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6759 mono_acfg_lock (llvm_acfg);
6760 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6761 mono_acfg_unlock (llvm_acfg);
6771 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6775 emit_llvm_file (MonoAotCompile *acfg)
6777 char *command, *opts, *tempbc;
6779 MonoJumpInfo *patch_info;
6782 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6786 /* Compute the final size of the got */
6787 for (i = 0; i < acfg->nmethods; ++i) {
6788 if (acfg->cfgs [i]) {
6789 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6790 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6791 if (!is_plt_patch (patch_info))
6792 get_got_offset (acfg, patch_info);
6794 get_plt_entry (acfg, patch_info);
6800 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6802 if (acfg->aot_opts.full_aot) {
6806 * Need to add the got entries used by the trampolines.
6807 * This is only a conservative approximation.
6809 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6810 /* For the generic + rgctx trampolines */
6811 acfg->final_got_size += 400;
6812 /* For the specific trampolines */
6813 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6814 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6819 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6820 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6824 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6825 * a lot of time, and doesn't seem to save much space.
6826 * The following optimizations cannot be enabled:
6828 * - 'jump-threading' changes our blockaddress references to int constants.
6829 * - 'basiccg' fails because it contains:
6830 * if (CS && !isa<IntrinsicInst>(II)) {
6831 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6832 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6833 * The opt list below was produced by taking the output of:
6834 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6835 * then removing tailcallelim + the global opts, and adding a second gvn.
6837 opts = g_strdup ("-instcombine -simplifycfg");
6838 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");
6840 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6841 printf ("Executing opt: %s\n", command);
6842 if (system (command) != 0) {
6848 if (!acfg->llc_args)
6849 acfg->llc_args = g_string_new ("");
6851 /* Verbose asm slows down llc greatly */
6852 g_string_append (acfg->llc_args, " -asm-verbose=false");
6854 if (acfg->aot_opts.mtriple)
6855 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6857 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6858 /* ios requires PIC code now */
6859 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6861 if (llvm_acfg->aot_opts.static_link)
6862 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6864 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6866 unlink (acfg->tmpfname);
6868 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);
6870 printf ("Executing llc: %s\n", command);
6872 if (system (command) != 0) {
6879 emit_code (MonoAotCompile *acfg)
6881 int oindex, i, prev_index;
6883 char end_symbol [256];
6885 #if defined(TARGET_POWERPC64)
6886 sprintf (symbol, ".Lgot_addr");
6887 emit_section_change (acfg, ".text", 0);
6888 emit_alignment (acfg, 8);
6889 emit_label (acfg, symbol);
6890 emit_pointer (acfg, acfg->got_symbol);
6894 * This global symbol is used to compute the address of each method using the
6895 * code_offsets array. It is also used to compute the memory ranges occupied by
6896 * AOT code, so it must be equal to the address of the first emitted method.
6898 sprintf (symbol, "methods");
6899 emit_section_change (acfg, ".text", 0);
6900 emit_alignment (acfg, 8);
6902 for (i = 0; i < acfg->nmethods; ++i) {
6903 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6904 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6908 if (i == acfg->nmethods)
6909 /* No LLVM compiled methods */
6910 emit_label (acfg, symbol);
6912 emit_label (acfg, symbol);
6916 * Emit some padding so the local symbol for the first method doesn't have the
6917 * same address as 'methods'.
6919 #if defined(__default_codegen__)
6920 emit_zero_bytes (acfg, 16);
6921 #elif defined(__native_client_codegen__)
6923 const int kPaddingSize = 16;
6924 guint8 pad_buffer[kPaddingSize];
6925 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6926 emit_bytes (acfg, pad_buffer, kPaddingSize);
6930 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6934 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6936 cfg = acfg->cfgs [i];
6941 method = cfg->orig_method;
6943 /* Emit unbox trampoline */
6944 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6945 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6947 emit_section_change (acfg, ".text", 0);
6948 #ifdef __native_client_codegen__
6949 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6952 if (acfg->thumb_mixed && cfg->compile_llvm) {
6953 emit_set_thumb_mode (acfg);
6954 fprintf (acfg->fp, "\n.thumb_func\n");
6957 emit_label (acfg, symbol);
6959 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6961 if (acfg->thumb_mixed && cfg->compile_llvm) {
6962 emit_set_arm_mode (acfg);
6966 if (cfg->compile_llvm)
6967 acfg->stats.llvm_count ++;
6969 emit_method_code (acfg, cfg);
6972 sprintf (symbol, "methods_end");
6973 emit_section_change (acfg, ".text", 0);
6974 emit_alignment (acfg, 8);
6975 emit_label (acfg, symbol);
6976 /* To distinguish it from the next symbol */
6977 emit_int32 (acfg, 0);
6980 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6981 * from optimizing them away, since it doesn't see that code_offsets references them.
6982 * JITted methods don't need this since they are referenced using assembler local
6984 * FIXME: This is why write-symbols doesn't work on OSX ?
6986 if (acfg->llvm && acfg->need_no_dead_strip) {
6987 fprintf (acfg->fp, "\n");
6988 for (i = 0; i < acfg->nmethods; ++i) {
6989 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6990 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6995 if (acfg->direct_method_addresses) {
6996 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6999 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7000 * This is PIE code, and the linker can update it if needed.
7002 sprintf (symbol, "method_addresses");
7003 emit_section_change (acfg, ".text", 1);
7004 emit_alignment (acfg, 8);
7005 emit_label (acfg, symbol);
7006 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7007 emit_unset_mode (acfg);
7008 if (acfg->need_no_dead_strip)
7009 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7011 for (i = 0; i < acfg->nmethods; ++i) {
7012 if (acfg->cfgs [i]) {
7013 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
7014 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
7016 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
7018 fprintf (acfg->fp, "\tbl method_addresses\n");
7022 sprintf (symbol, "method_addresses_end");
7023 emit_label (acfg, symbol);
7026 sprintf (symbol, "code_offsets");
7027 emit_section_change (acfg, RODATA_SECT, 1);
7028 emit_alignment (acfg, 8);
7029 emit_label (acfg, symbol);
7030 emit_int32 (acfg, 0);
7032 sprintf (symbol, "code_offsets");
7033 emit_section_change (acfg, RODATA_SECT, 1);
7034 emit_alignment (acfg, 8);
7035 emit_label (acfg, symbol);
7037 acfg->stats.offsets_size += acfg->nmethods * 4;
7039 sprintf (end_symbol, "methods");
7040 for (i = 0; i < acfg->nmethods; ++i) {
7041 if (acfg->cfgs [i]) {
7042 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
7044 emit_int32 (acfg, 0xffffffff);
7049 sprintf (symbol, "code_offsets");
7050 emit_section_change (acfg, RODATA_SECT, 1);
7051 emit_alignment (acfg, 8);
7052 emit_label (acfg, symbol);
7054 acfg->stats.offsets_size += acfg->nmethods * 4;
7056 sprintf (end_symbol, "methods");
7057 for (i = 0; i < acfg->nmethods; ++i) {
7058 if (acfg->cfgs [i]) {
7059 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
7061 emit_int32 (acfg, 0xffffffff);
7067 /* Emit a sorted table mapping methods to their unbox trampolines */
7068 sprintf (symbol, "unbox_trampolines");
7069 if (acfg->direct_method_addresses)
7070 emit_section_change (acfg, ".text", 0);
7072 emit_section_change (acfg, RODATA_SECT, 0);
7073 emit_alignment (acfg, 8);
7074 emit_label (acfg, symbol);
7076 sprintf (end_symbol, "methods");
7078 for (i = 0; i < acfg->nmethods; ++i) {
7083 cfg = acfg->cfgs [i];
7087 method = cfg->orig_method;
7089 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7090 index = get_method_index (acfg, method);
7091 sprintf (symbol, "ut_%d", index);
7093 emit_int32 (acfg, index);
7094 if (acfg->direct_method_addresses) {
7095 emit_unset_mode (acfg);
7096 if (acfg->thumb_mixed && cfg->compile_llvm)
7097 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7099 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7101 emit_symbol_diff (acfg, symbol, end_symbol, 0);
7103 /* Make sure the table is sorted by index */
7104 g_assert (index > prev_index);
7108 sprintf (symbol, "unbox_trampolines_end");
7109 emit_label (acfg, symbol);
7113 emit_info (MonoAotCompile *acfg)
7119 offsets = g_new0 (gint32, acfg->nmethods);
7121 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7122 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7124 if (acfg->cfgs [i]) {
7125 emit_method_info (acfg, acfg->cfgs [i]);
7126 offsets [i] = acfg->cfgs [i]->method_info_offset;
7132 sprintf (symbol, "method_info_offsets");
7133 emit_section_change (acfg, RODATA_SECT, 1);
7134 emit_alignment (acfg, 8);
7135 emit_label (acfg, symbol);
7137 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7142 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7144 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7145 #define mix(a,b,c) { \
7146 a -= c; a ^= rot(c, 4); c += b; \
7147 b -= a; b ^= rot(a, 6); a += c; \
7148 c -= b; c ^= rot(b, 8); b += a; \
7149 a -= c; a ^= rot(c,16); c += b; \
7150 b -= a; b ^= rot(a,19); a += c; \
7151 c -= b; c ^= rot(b, 4); b += a; \
7153 #define final(a,b,c) { \
7154 c ^= b; c -= rot(b,14); \
7155 a ^= c; a -= rot(c,11); \
7156 b ^= a; b -= rot(a,25); \
7157 c ^= b; c -= rot(b,16); \
7158 a ^= c; a -= rot(c,4); \
7159 b ^= a; b -= rot(a,14); \
7160 c ^= b; c -= rot(b,24); \
7164 mono_aot_type_hash (MonoType *t1)
7166 guint hash = t1->type;
7168 hash |= t1->byref << 6; /* do not collide with t1->type values */
7170 case MONO_TYPE_VALUETYPE:
7171 case MONO_TYPE_CLASS:
7172 case MONO_TYPE_SZARRAY:
7173 /* check if the distribution is good enough */
7174 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7176 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7177 case MONO_TYPE_ARRAY:
7178 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7179 case MONO_TYPE_GENERICINST:
7180 return ((hash << 5) - hash) ^ 0;
7187 * mono_aot_method_hash:
7189 * Return a hash code for methods which only depends on metadata.
7192 mono_aot_method_hash (MonoMethod *method)
7194 MonoMethodSignature *sig;
7198 guint32 *hashes_start, *hashes;
7200 MonoGenericInst *ginst = NULL;
7202 /* Similar to the hash in mono_method_get_imt_slot () */
7204 sig = mono_method_signature (method);
7206 if (method->is_inflated)
7207 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7209 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7210 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7211 hashes = hashes_start;
7213 /* Some wrappers are assigned to random classes */
7214 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7215 klass = method->klass;
7217 klass = mono_defaults.object_class;
7219 if (!method->wrapper_type) {
7220 char *full_name = mono_type_full_name (&klass->byval_arg);
7222 hashes [0] = mono_metadata_str_hash (full_name);
7226 hashes [0] = mono_metadata_str_hash (klass->name);
7227 hashes [1] = mono_metadata_str_hash (klass->name_space);
7229 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7230 /* The method name includes a stringified pointer */
7233 hashes [2] = mono_metadata_str_hash (method->name);
7234 hashes [3] = method->wrapper_type;
7235 hashes [4] = mono_aot_type_hash (sig->ret);
7237 for (i = 0; i < sig->param_count; i++) {
7238 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7241 for (i = 0; i < ginst->type_argc; ++i)
7242 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7244 g_assert (hindex == hashes_count);
7246 /* Setup internal state */
7247 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7249 /* Handle most of the hashes */
7250 while (hashes_count > 3) {
7259 /* Handle the last 3 hashes (all the case statements fall through) */
7260 switch (hashes_count) {
7261 case 3 : c += hashes [2];
7262 case 2 : b += hashes [1];
7263 case 1 : a += hashes [0];
7265 case 0: /* nothing left to add */
7269 free (hashes_start);
7278 * mono_aot_get_array_helper_from_wrapper;
7280 * Get the helper method in Array called by an array wrapper method.
7283 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7287 MonoGenericContext ctx;
7288 MonoType *args [16];
7289 char *mname, *iname, *s, *s2, *helper_name = NULL;
7291 prefix = "System.Collections.Generic";
7292 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7293 s2 = strstr (s, "`1.");
7299 //printf ("X: %s %s\n", iname, mname);
7301 if (!strcmp (iname, "IList"))
7302 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7304 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7305 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7307 g_free (helper_name);
7310 if (m->is_generic) {
7311 memset (&ctx, 0, sizeof (ctx));
7312 args [0] = &method->klass->element_class->byval_arg;
7313 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7314 m = mono_class_inflate_generic_method (m, &ctx);
7320 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7322 typedef struct HashEntry {
7323 guint32 key, value, index;
7324 struct HashEntry *next;
7328 * emit_extra_methods:
7330 * Emit methods which are not in the METHOD table, like wrappers.
7333 emit_extra_methods (MonoAotCompile *acfg)
7335 int i, table_size, buf_size;
7338 guint32 *info_offsets;
7341 HashEntry *entry, *new_entry;
7342 int nmethods, max_chain_length;
7345 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7347 /* Emit method info */
7349 for (i = 0; i < acfg->extra_methods->len; ++i) {
7350 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7351 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7357 p = buf = g_malloc (buf_size);
7361 method = cfg->method_to_register;
7363 encode_method_ref (acfg, method, p, &p);
7365 g_assert ((p - buf) < buf_size);
7367 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7372 * Construct a chained hash table for mapping indexes in extra_method_info to
7375 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7376 table = g_ptr_array_sized_new (table_size);
7377 for (i = 0; i < table_size; ++i)
7378 g_ptr_array_add (table, NULL);
7379 chain_lengths = g_new0 (int, table_size);
7380 max_chain_length = 0;
7381 for (i = 0; i < acfg->extra_methods->len; ++i) {
7382 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7383 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7389 key = info_offsets [i];
7390 value = get_method_index (acfg, method);
7392 hash = mono_aot_method_hash (method) % table_size;
7393 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7395 chain_lengths [hash] ++;
7396 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7398 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7399 new_entry->key = key;
7400 new_entry->value = value;
7402 entry = g_ptr_array_index (table, hash);
7403 if (entry == NULL) {
7404 new_entry->index = hash;
7405 g_ptr_array_index (table, hash) = new_entry;
7408 entry = entry->next;
7410 entry->next = new_entry;
7411 new_entry->index = table->len;
7412 g_ptr_array_add (table, new_entry);
7416 //printf ("MAX: %d\n", max_chain_length);
7418 /* Emit the table */
7419 sprintf (symbol, "extra_method_table");
7420 emit_section_change (acfg, RODATA_SECT, 0);
7421 emit_alignment (acfg, 8);
7422 emit_label (acfg, symbol);
7424 emit_int32 (acfg, table_size);
7425 for (i = 0; i < table->len; ++i) {
7426 HashEntry *entry = g_ptr_array_index (table, i);
7428 if (entry == NULL) {
7429 emit_int32 (acfg, 0);
7430 emit_int32 (acfg, 0);
7431 emit_int32 (acfg, 0);
7433 //g_assert (entry->key > 0);
7434 emit_int32 (acfg, entry->key);
7435 emit_int32 (acfg, entry->value);
7437 emit_int32 (acfg, entry->next->index);
7439 emit_int32 (acfg, 0);
7444 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7445 * This is used by mono_aot_find_jit_info ().
7447 sprintf (symbol, "extra_method_info_offsets");
7448 emit_section_change (acfg, RODATA_SECT, 0);
7449 emit_alignment (acfg, 8);
7450 emit_label (acfg, symbol);
7452 emit_int32 (acfg, acfg->extra_methods->len);
7453 for (i = 0; i < acfg->extra_methods->len; ++i) {
7454 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7456 emit_int32 (acfg, get_method_index (acfg, method));
7457 emit_int32 (acfg, info_offsets [i]);
7462 emit_exception_info (MonoAotCompile *acfg)
7468 offsets = g_new0 (gint32, acfg->nmethods);
7469 for (i = 0; i < acfg->nmethods; ++i) {
7470 if (acfg->cfgs [i]) {
7471 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7472 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7478 sprintf (symbol, "ex_info_offsets");
7479 emit_section_change (acfg, RODATA_SECT, 1);
7480 emit_alignment (acfg, 8);
7481 emit_label (acfg, symbol);
7483 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7488 emit_unwind_info (MonoAotCompile *acfg)
7494 * The unwind info contains a lot of duplicates so we emit each unique
7495 * entry once, and only store the offset from the start of the table in the
7499 sprintf (symbol, "unwind_info");
7500 emit_section_change (acfg, RODATA_SECT, 1);
7501 emit_alignment (acfg, 8);
7502 emit_label (acfg, symbol);
7504 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7505 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7506 guint8 *unwind_info;
7507 guint32 unwind_info_len;
7511 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7514 encode_value (unwind_info_len, p, &p);
7515 emit_bytes (acfg, buf, p - buf);
7516 emit_bytes (acfg, unwind_info, unwind_info_len);
7518 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7523 emit_class_info (MonoAotCompile *acfg)
7529 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7530 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7531 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7533 sprintf (symbol, "class_info_offsets");
7534 emit_section_change (acfg, RODATA_SECT, 1);
7535 emit_alignment (acfg, 8);
7536 emit_label (acfg, symbol);
7538 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7542 typedef struct ClassNameTableEntry {
7543 guint32 token, index;
7544 struct ClassNameTableEntry *next;
7545 } ClassNameTableEntry;
7548 emit_class_name_table (MonoAotCompile *acfg)
7551 guint32 token, hash;
7556 ClassNameTableEntry *entry, *new_entry;
7559 * Construct a chained hash table for mapping class names to typedef tokens.
7561 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7562 table = g_ptr_array_sized_new (table_size);
7563 for (i = 0; i < table_size; ++i)
7564 g_ptr_array_add (table, NULL);
7565 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7566 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7567 klass = mono_class_get (acfg->image, token);
7569 mono_loader_clear_error ();
7572 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7573 hash = mono_metadata_str_hash (full_name) % table_size;
7576 /* FIXME: Allocate from the mempool */
7577 new_entry = g_new0 (ClassNameTableEntry, 1);
7578 new_entry->token = token;
7580 entry = g_ptr_array_index (table, hash);
7581 if (entry == NULL) {
7582 new_entry->index = hash;
7583 g_ptr_array_index (table, hash) = new_entry;
7586 entry = entry->next;
7588 entry->next = new_entry;
7589 new_entry->index = table->len;
7590 g_ptr_array_add (table, new_entry);
7594 /* Emit the table */
7595 sprintf (symbol, "class_name_table");
7596 emit_section_change (acfg, RODATA_SECT, 0);
7597 emit_alignment (acfg, 8);
7598 emit_label (acfg, symbol);
7600 /* FIXME: Optimize memory usage */
7601 g_assert (table_size < 65000);
7602 emit_int16 (acfg, table_size);
7603 g_assert (table->len < 65000);
7604 for (i = 0; i < table->len; ++i) {
7605 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7607 if (entry == NULL) {
7608 emit_int16 (acfg, 0);
7609 emit_int16 (acfg, 0);
7611 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7613 emit_int16 (acfg, entry->next->index);
7615 emit_int16 (acfg, 0);
7621 emit_image_table (MonoAotCompile *acfg)
7627 * The image table is small but referenced in a lot of places.
7628 * So we emit it at once, and reference its elements by an index.
7631 sprintf (symbol, "image_table");
7632 emit_section_change (acfg, RODATA_SECT, 1);
7633 emit_alignment (acfg, 8);
7634 emit_label (acfg, symbol);
7636 emit_int32 (acfg, acfg->image_table->len);
7637 for (i = 0; i < acfg->image_table->len; i++) {
7638 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7639 MonoAssemblyName *aname = &image->assembly->aname;
7641 /* FIXME: Support multi-module assemblies */
7642 g_assert (image->assembly->image == image);
7644 emit_string (acfg, image->assembly_name);
7645 emit_string (acfg, image->guid);
7646 emit_string (acfg, aname->culture ? aname->culture : "");
7647 emit_string (acfg, (const char*)aname->public_key_token);
7649 emit_alignment (acfg, 8);
7650 emit_int32 (acfg, aname->flags);
7651 emit_int32 (acfg, aname->major);
7652 emit_int32 (acfg, aname->minor);
7653 emit_int32 (acfg, aname->build);
7654 emit_int32 (acfg, aname->revision);
7659 emit_got_info (MonoAotCompile *acfg)
7662 int i, first_plt_got_patch, buf_size;
7664 guint32 *got_info_offsets;
7666 /* Add the patches needed by the PLT to the GOT */
7667 acfg->plt_got_offset_base = acfg->got_offset;
7668 first_plt_got_patch = acfg->got_patches->len;
7669 for (i = 1; i < acfg->plt_offset; ++i) {
7670 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7672 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7674 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7677 acfg->got_offset += acfg->plt_offset;
7681 * - optimize offsets table.
7682 * - reduce number of exported symbols.
7683 * - emit info for a klass only once.
7684 * - determine when a method uses a GOT slot which is guaranteed to be already
7686 * - clean up and document the code.
7687 * - use String.Empty in class libs.
7690 /* Encode info required to decode shared GOT entries */
7691 buf_size = acfg->got_patches->len * 128;
7692 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7693 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7694 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7696 if (acfg->plt_offset)
7697 acfg->plt_got_info_offsets [0] = 0;
7698 for (i = 0; i < acfg->got_patches->len; ++i) {
7699 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7704 encode_value (ji->type, p, &p);
7706 encode_patch (acfg, ji, p, &p);
7707 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7708 g_assert (p - buf <= buf_size);
7709 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7711 if (i >= first_plt_got_patch)
7712 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7713 acfg->stats.got_info_size += p - buf;
7716 /* Emit got_info_offsets table */
7717 sprintf (symbol, "got_info_offsets");
7718 emit_section_change (acfg, RODATA_SECT, 1);
7719 emit_alignment (acfg, 8);
7720 emit_label (acfg, symbol);
7722 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7723 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7727 emit_got (MonoAotCompile *acfg)
7732 /* Don't make GOT global so accesses to it don't need relocations */
7733 sprintf (symbol, "%s", acfg->got_symbol);
7734 emit_section_change (acfg, ".bss", 0);
7735 emit_alignment (acfg, 8);
7736 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7737 emit_label (acfg, symbol);
7738 if (acfg->got_offset > 0)
7739 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7741 sprintf (symbol, "got_end");
7742 emit_label (acfg, symbol);
7746 typedef struct GlobalsTableEntry {
7747 guint32 value, index;
7748 struct GlobalsTableEntry *next;
7749 } GlobalsTableEntry;
7752 emit_globals (MonoAotCompile *acfg)
7758 GlobalsTableEntry *entry, *new_entry;
7760 if (!acfg->aot_opts.static_link)
7764 * When static linking, we emit a table containing our globals.
7768 * Construct a chained hash table for mapping global names to their index in
7769 * the globals table.
7771 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7772 table = g_ptr_array_sized_new (table_size);
7773 for (i = 0; i < table_size; ++i)
7774 g_ptr_array_add (table, NULL);
7775 for (i = 0; i < acfg->globals->len; ++i) {
7776 char *name = g_ptr_array_index (acfg->globals, i);
7778 hash = mono_metadata_str_hash (name) % table_size;
7780 /* FIXME: Allocate from the mempool */
7781 new_entry = g_new0 (GlobalsTableEntry, 1);
7782 new_entry->value = i;
7784 entry = g_ptr_array_index (table, hash);
7785 if (entry == NULL) {
7786 new_entry->index = hash;
7787 g_ptr_array_index (table, hash) = new_entry;
7790 entry = entry->next;
7792 entry->next = new_entry;
7793 new_entry->index = table->len;
7794 g_ptr_array_add (table, new_entry);
7798 /* Emit the table */
7799 sprintf (symbol, ".Lglobals_hash");
7800 emit_section_change (acfg, RODATA_SECT, 0);
7801 emit_alignment (acfg, 8);
7802 emit_label (acfg, symbol);
7804 /* FIXME: Optimize memory usage */
7805 g_assert (table_size < 65000);
7806 emit_int16 (acfg, table_size);
7807 for (i = 0; i < table->len; ++i) {
7808 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7810 if (entry == NULL) {
7811 emit_int16 (acfg, 0);
7812 emit_int16 (acfg, 0);
7814 emit_int16 (acfg, entry->value + 1);
7816 emit_int16 (acfg, entry->next->index);
7818 emit_int16 (acfg, 0);
7822 /* Emit the names */
7823 for (i = 0; i < acfg->globals->len; ++i) {
7824 char *name = g_ptr_array_index (acfg->globals, i);
7826 sprintf (symbol, "name_%d", i);
7827 emit_section_change (acfg, RODATA_SECT, 1);
7829 emit_alignment (acfg, 4);
7831 emit_label (acfg, symbol);
7832 emit_string (acfg, name);
7835 /* Emit the globals table */
7836 sprintf (symbol, "globals");
7837 emit_section_change (acfg, ".data", 0);
7838 /* This is not a global, since it is accessed by the init function */
7839 emit_alignment (acfg, 8);
7840 emit_label (acfg, symbol);
7842 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7843 emit_pointer (acfg, symbol);
7845 for (i = 0; i < acfg->globals->len; ++i) {
7846 char *name = g_ptr_array_index (acfg->globals, i);
7848 sprintf (symbol, "name_%d", i);
7849 emit_pointer (acfg, symbol);
7851 sprintf (symbol, "%s", name);
7852 emit_pointer (acfg, symbol);
7854 /* Null terminate the table */
7855 emit_int32 (acfg, 0);
7856 emit_int32 (acfg, 0);
7860 emit_autoreg (MonoAotCompile *acfg)
7865 * Emit a function into the .ctor section which will be called by the ELF
7866 * loader to register this module with the runtime.
7868 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7871 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7873 arch_emit_autoreg (acfg, symbol);
7879 emit_mem_end (MonoAotCompile *acfg)
7883 sprintf (symbol, "mem_end");
7884 emit_section_change (acfg, ".text", 1);
7885 emit_alignment (acfg, 8);
7886 emit_label (acfg, symbol);
7890 * Emit a structure containing all the information not stored elsewhere.
7893 emit_file_info (MonoAotCompile *acfg)
7898 const char *gc_name;
7901 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7903 if (acfg->aot_opts.bind_to_runtime_version) {
7904 build_info = mono_get_runtime_build_info ();
7905 emit_string_symbol (acfg, "runtime_version", build_info);
7906 g_free (build_info);
7908 emit_string_symbol (acfg, "runtime_version", "");
7911 /* Emit a string holding the assembly name */
7912 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7915 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7918 gc_name = mono_gc_get_gc_name ();
7919 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7921 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
7922 emit_section_change (acfg, ".data", 0);
7923 emit_alignment (acfg, 8);
7924 emit_label (acfg, symbol);
7925 if (!acfg->aot_opts.static_link)
7926 emit_global (acfg, symbol, FALSE);
7928 /* The data emitted here must match MonoAotFileInfo. */
7930 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7931 emit_int32 (acfg, 0);
7934 * We emit pointers to our data structures instead of emitting global symbols which
7935 * point to them, to reduce the number of globals, and because using globals leads to
7936 * various problems (i.e. arm/thumb).
7938 emit_pointer (acfg, acfg->got_symbol);
7939 emit_pointer (acfg, "methods");
7942 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7944 emit_pointer (acfg, "mono_eh_frame");
7946 emit_pointer (acfg, NULL);
7948 emit_pointer (acfg, "blob");
7949 emit_pointer (acfg, "class_name_table");
7950 emit_pointer (acfg, "class_info_offsets");
7951 emit_pointer (acfg, "method_info_offsets");
7952 emit_pointer (acfg, "ex_info_offsets");
7953 emit_pointer (acfg, "code_offsets");
7954 if (acfg->direct_method_addresses)
7955 emit_pointer (acfg, "method_addresses");
7957 emit_pointer (acfg, NULL);
7958 emit_pointer (acfg, "extra_method_info_offsets");
7959 emit_pointer (acfg, "extra_method_table");
7960 emit_pointer (acfg, "got_info_offsets");
7961 emit_pointer (acfg, "methods_end");
7962 emit_pointer (acfg, "unwind_info");
7963 emit_pointer (acfg, "mem_end");
7964 emit_pointer (acfg, "image_table");
7965 emit_pointer (acfg, "plt");
7966 emit_pointer (acfg, "plt_end");
7967 emit_pointer (acfg, "assembly_guid");
7968 emit_pointer (acfg, "runtime_version");
7969 if (acfg->num_trampoline_got_entries) {
7970 emit_pointer (acfg, "specific_trampolines");
7971 emit_pointer (acfg, "static_rgctx_trampolines");
7972 emit_pointer (acfg, "imt_thunks");
7973 emit_pointer (acfg, "gsharedvt_arg_trampolines");
7975 emit_pointer (acfg, NULL);
7976 emit_pointer (acfg, NULL);
7977 emit_pointer (acfg, NULL);
7978 emit_pointer (acfg, NULL);
7980 if (acfg->thumb_mixed) {
7981 emit_pointer (acfg, "thumb_end");
7983 emit_pointer (acfg, NULL);
7985 if (acfg->aot_opts.static_link) {
7986 emit_pointer (acfg, "globals");
7988 emit_pointer (acfg, NULL);
7990 emit_pointer (acfg, "assembly_name");
7991 emit_pointer (acfg, "unbox_trampolines");
7992 emit_pointer (acfg, "unbox_trampolines_end");
7994 emit_int32 (acfg, acfg->plt_got_offset_base);
7995 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7996 emit_int32 (acfg, acfg->plt_offset);
7997 emit_int32 (acfg, acfg->nmethods);
7998 emit_int32 (acfg, acfg->flags);
7999 emit_int32 (acfg, acfg->opts);
8000 emit_int32 (acfg, acfg->simd_opts);
8001 emit_int32 (acfg, gc_name_offset);
8003 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8004 emit_int32 (acfg, acfg->num_trampolines [i]);
8005 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8006 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8007 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8008 emit_int32 (acfg, acfg->trampoline_size [i]);
8009 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8011 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8016 memset (&t, 0, sizeof (MonoType));
8017 t.type = MONO_TYPE_R8;
8018 mono_type_size (&t, &align);
8019 emit_int32 (acfg, align);
8021 memset (&t, 0, sizeof (MonoType));
8022 t.type = MONO_TYPE_I8;
8023 mono_type_size (&t, &align);
8025 emit_int32 (acfg, align);
8028 emit_int32 (acfg, __alignof__ (double));
8029 emit_int32 (acfg, __alignof__ (gint64));
8031 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8033 if (acfg->aot_opts.static_link) {
8037 * Emit a global symbol which can be passed by an embedding app to
8038 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8041 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8043 /* Get rid of characters which cannot occur in symbols */
8045 for (p = symbol; *p; ++p) {
8046 if (!(isalnum (*p) || *p == '_'))
8049 acfg->static_linking_symbol = g_strdup (symbol);
8050 emit_global_inner (acfg, symbol, FALSE);
8051 emit_label (acfg, symbol);
8052 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8057 emit_blob (MonoAotCompile *acfg)
8061 sprintf (symbol, "blob");
8062 emit_section_change (acfg, RODATA_SECT, 1);
8063 emit_alignment (acfg, 8);
8064 emit_label (acfg, symbol);
8066 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8070 emit_dwarf_info (MonoAotCompile *acfg)
8072 #ifdef EMIT_DWARF_INFO
8076 /* DIEs for methods */
8077 for (i = 0; i < acfg->nmethods; ++i) {
8078 MonoCompile *cfg = acfg->cfgs [i];
8083 // FIXME: LLVM doesn't define .Lme_...
8084 if (cfg->compile_llvm)
8087 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8089 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 ()));
8095 collect_methods (MonoAotCompile *acfg)
8098 MonoImage *image = acfg->image;
8100 /* Collect methods */
8101 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8103 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8105 method = mono_get_method (acfg->image, token, NULL);
8108 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8112 /* Load all methods eagerly to skip the slower lazy loading code */
8113 mono_class_setup_methods (method->klass);
8115 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8116 /* Compile the wrapper instead */
8117 /* We do this here instead of add_wrappers () because it is easy to do it here */
8118 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8122 /* FIXME: Some mscorlib methods don't have debug info */
8124 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8125 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8126 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8127 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8128 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8129 if (!mono_debug_lookup_method (method)) {
8130 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8137 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8138 add_method_with_index (acfg, method, i, FALSE);
8139 acfg->method_index ++;
8142 /* gsharedvt methods */
8143 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8145 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8147 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8150 method = mono_get_method (acfg->image, token, NULL);
8154 if (strcmp (method->name, "gshared2"))
8158 if (!strstr (method->klass->image->name, "mini"))
8161 if (method->is_generic || method->klass->generic_container) {
8162 MonoMethod *gshared;
8164 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8165 add_extra_method (acfg, gshared);
8169 add_generic_instances (acfg);
8171 if (acfg->aot_opts.full_aot)
8172 add_wrappers (acfg);
8176 compile_methods (MonoAotCompile *acfg)
8180 if (acfg->aot_opts.nthreads > 0) {
8185 gpointer *user_data;
8186 MonoMethod **methods;
8188 methods_len = acfg->methods->len;
8190 len = acfg->methods->len / acfg->aot_opts.nthreads;
8193 * Partition the list of methods into fragments, and hand it to threads to
8196 threads = g_ptr_array_new ();
8197 /* Make a copy since acfg->methods is modified by compile_method () */
8198 methods = g_new0 (MonoMethod*, methods_len);
8199 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8200 for (i = 0; i < methods_len; ++i)
8201 methods [i] = g_ptr_array_index (acfg->methods, i);
8203 while (i < methods_len) {
8204 frag = g_ptr_array_new ();
8205 for (j = 0; j < len; ++j) {
8206 if (i < methods_len) {
8207 g_ptr_array_add (frag, methods [i]);
8212 user_data = g_new0 (gpointer, 3);
8213 user_data [0] = mono_domain_get ();
8214 user_data [1] = acfg;
8215 user_data [2] = frag;
8217 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
8218 g_ptr_array_add (threads, handle);
8222 for (i = 0; i < threads->len; ++i) {
8223 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8229 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8230 for (i = methods_len; i < acfg->methods->len; ++i) {
8231 /* This can new methods to acfg->methods */
8232 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8237 compile_asm (MonoAotCompile *acfg)
8239 char *command, *objfile;
8240 char *outfile_name, *tmp_outfile_name;
8241 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8243 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8244 #define AS_OPTIONS "--64"
8245 #elif defined(TARGET_POWERPC64)
8246 #define AS_OPTIONS "-a64 -mppc64"
8247 #define LD_OPTIONS "-m elf64ppc"
8248 #elif defined(sparc) && SIZEOF_VOID_P == 8
8249 #define AS_OPTIONS "-xarch=v9"
8250 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8251 #define AS_OPTIONS "-arch i386 -W"
8253 #define AS_OPTIONS ""
8256 #ifdef __native_client_codegen__
8257 #if defined(TARGET_AMD64)
8258 #define AS_NAME "nacl64-as"
8260 #define AS_NAME "nacl-as"
8263 #define AS_NAME "as"
8267 #define LD_OPTIONS ""
8270 #define EH_LD_OPTIONS ""
8272 if (acfg->aot_opts.asm_only) {
8273 printf ("Output file: '%s'.\n", acfg->tmpfname);
8274 if (acfg->aot_opts.static_link)
8275 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8279 if (acfg->aot_opts.static_link) {
8280 if (acfg->aot_opts.outfile)
8281 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8283 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8285 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8287 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);
8288 printf ("Executing the native assembler: %s\n", command);
8289 if (system (command) != 0) {
8297 if (acfg->aot_opts.static_link) {
8298 printf ("Output file: '%s'.\n", objfile);
8299 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8304 if (acfg->aot_opts.outfile)
8305 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8307 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8309 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8312 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8313 #elif defined(__ppc__) && defined(TARGET_MACH)
8314 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8315 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8316 command = g_strdup_printf ("gcc --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8317 #elif defined(HOST_WIN32)
8318 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8319 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8320 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8322 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8324 printf ("Executing the native linker: %s\n", command);
8325 if (system (command) != 0) {
8326 g_free (tmp_outfile_name);
8327 g_free (outfile_name);
8335 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8336 printf ("Stripping the binary: %s\n", com);
8340 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8342 * gas generates 'mapping symbols' each time code and data is mixed, which
8343 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8345 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8346 printf ("Stripping the binary: %s\n", command);
8347 if (system (command) != 0) {
8348 g_free (tmp_outfile_name);
8349 g_free (outfile_name);
8356 rename (tmp_outfile_name, outfile_name);
8358 #if defined(TARGET_MACH)
8359 command = g_strdup_printf ("dsymutil %s", outfile_name);
8360 printf ("Generating debug symbols: %s\n", command);
8361 if (system (command) != 0) {
8366 if (!acfg->aot_opts.save_temps)
8369 g_free (tmp_outfile_name);
8370 g_free (outfile_name);
8373 if (acfg->aot_opts.save_temps)
8374 printf ("Retained input file.\n");
8376 unlink (acfg->tmpfname);
8381 static MonoAotCompile*
8382 acfg_create (MonoAssembly *ass, guint32 opts)
8384 MonoImage *image = ass->image;
8385 MonoAotCompile *acfg;
8388 acfg = g_new0 (MonoAotCompile, 1);
8389 acfg->methods = g_ptr_array_new ();
8390 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8391 acfg->method_depth = g_hash_table_new (NULL, NULL);
8392 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8393 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8394 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8395 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8396 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8397 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8398 acfg->got_patches = g_ptr_array_new ();
8399 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8400 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8401 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8402 acfg->image_hash = g_hash_table_new (NULL, NULL);
8403 acfg->image_table = g_ptr_array_new ();
8404 acfg->globals = g_ptr_array_new ();
8405 acfg->image = image;
8407 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8408 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8409 acfg->mempool = mono_mempool_new ();
8410 acfg->extra_methods = g_ptr_array_new ();
8411 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8412 acfg->unwind_ops = g_ptr_array_new ();
8413 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8414 acfg->method_order = g_ptr_array_new ();
8415 acfg->export_names = g_hash_table_new (NULL, NULL);
8416 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8417 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8418 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8419 InitializeCriticalSection (&acfg->mutex);
8425 acfg_free (MonoAotCompile *acfg)
8429 img_writer_destroy (acfg->w);
8430 for (i = 0; i < acfg->nmethods; ++i)
8432 g_free (acfg->cfgs [i]);
8433 g_free (acfg->cfgs);
8434 g_free (acfg->static_linking_symbol);
8435 g_free (acfg->got_symbol);
8436 g_free (acfg->plt_symbol);
8437 g_ptr_array_free (acfg->methods, TRUE);
8438 g_ptr_array_free (acfg->got_patches, TRUE);
8439 g_ptr_array_free (acfg->image_table, TRUE);
8440 g_ptr_array_free (acfg->globals, TRUE);
8441 g_ptr_array_free (acfg->unwind_ops, TRUE);
8442 g_hash_table_destroy (acfg->method_indexes);
8443 g_hash_table_destroy (acfg->method_depth);
8444 g_hash_table_destroy (acfg->plt_offset_to_entry);
8445 g_hash_table_destroy (acfg->patch_to_plt_entry);
8446 g_hash_table_destroy (acfg->patch_to_got_offset);
8447 g_hash_table_destroy (acfg->method_to_cfg);
8448 g_hash_table_destroy (acfg->token_info_hash);
8449 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8450 g_hash_table_destroy (acfg->image_hash);
8451 g_hash_table_destroy (acfg->unwind_info_offsets);
8452 g_hash_table_destroy (acfg->method_label_hash);
8453 g_hash_table_destroy (acfg->export_names);
8454 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8455 g_hash_table_destroy (acfg->klass_blob_hash);
8456 g_hash_table_destroy (acfg->method_blob_hash);
8457 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8458 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8459 g_free (acfg->patch_to_got_offset_by_type);
8460 mono_mempool_destroy (acfg->mempool);
8465 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8467 MonoImage *image = ass->image;
8469 MonoAotCompile *acfg;
8470 char *outfile_name, *tmp_outfile_name, *p;
8471 char llvm_stats_msg [256];
8475 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
8476 opts &= ~MONO_OPT_GSHAREDVT;
8479 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8481 acfg = acfg_create (ass, opts);
8483 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8484 acfg->aot_opts.write_symbols = TRUE;
8485 acfg->aot_opts.ntrampolines = 1024;
8486 acfg->aot_opts.nrgctx_trampolines = 1024;
8487 acfg->aot_opts.nimt_trampolines = 128;
8488 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8489 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8490 acfg->aot_opts.llvm_path = g_strdup ("");
8492 acfg->aot_opts.use_trampolines_page = TRUE;
8495 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8497 if (acfg->aot_opts.static_link)
8498 acfg->aot_opts.autoreg = TRUE;
8500 //acfg->aot_opts.print_skipped_methods = TRUE;
8502 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8503 if (acfg->aot_opts.full_aot) {
8504 printf ("--aot=full is not supported on this platform.\n");
8509 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8510 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8514 if (acfg->aot_opts.static_link)
8515 acfg->aot_opts.asm_writer = TRUE;
8517 if (acfg->aot_opts.soft_debug) {
8518 MonoDebugOptions *opt = mini_get_debug_options ();
8520 opt->mdb_optimizations = TRUE;
8521 opt->gen_seq_points = TRUE;
8523 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8524 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8527 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8530 if (mono_use_llvm) {
8532 acfg->aot_opts.asm_writer = TRUE;
8533 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8535 if (acfg->aot_opts.soft_debug) {
8536 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8541 if (acfg->aot_opts.full_aot)
8542 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8544 load_profile_files (acfg);
8546 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8547 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8548 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8550 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8551 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8552 if (acfg->opts & MONO_OPT_GSHAREDVT)
8553 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8556 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8560 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8561 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8562 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8564 /* Get rid of characters which cannot occur in symbols */
8565 for (p = acfg->got_symbol_base; *p; ++p) {
8566 if (!(isalnum (*p) || *p == '_'))
8569 for (p = acfg->plt_symbol; *p; ++p) {
8570 if (!(isalnum (*p) || *p == '_'))
8573 for (p = acfg->assembly_name_sym; *p; ++p) {
8574 if (!(isalnum (*p) || *p == '_'))
8578 acfg->method_index = 1;
8582 if (acfg->aot_opts.full_aot)
8583 mono_set_partial_sharing_supported (TRUE);
8586 collect_methods (acfg);
8588 acfg->cfgs_size = acfg->methods->len + 32;
8589 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8591 /* PLT offset 0 is reserved for the PLT trampoline */
8592 acfg->plt_offset = 1;
8597 mono_llvm_create_aot_module (acfg->got_symbol_base);
8601 /* GOT offset 0 is reserved for the address of the current assembly */
8605 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8606 ji->type = MONO_PATCH_INFO_IMAGE;
8607 ji->data.image = acfg->image;
8609 get_got_offset (acfg, ji);
8611 /* Slot 1 is reserved for the mscorlib got addr */
8612 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8613 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8614 get_got_offset (acfg, ji);
8616 /* This is very common */
8617 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8618 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8619 get_got_offset (acfg, ji);
8621 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8622 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8623 get_got_offset (acfg, ji);
8628 compile_methods (acfg);
8632 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8638 if (acfg->aot_opts.asm_only) {
8639 if (acfg->aot_opts.outfile)
8640 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8642 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8644 acfg->tmpfname = g_strdup ("temp.s");
8647 emit_llvm_file (acfg);
8651 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8652 if (acfg->aot_opts.outfile)
8653 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8655 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8658 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8659 * it might be in another file system so the rename () won't work.
8661 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8663 acfg->fp = fopen (tmp_outfile_name, "w");
8665 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8669 acfg->w = img_writer_create (acfg->fp, TRUE);
8670 acfg->use_bin_writer = TRUE;
8673 /* Append to the .s file created by llvm */
8674 /* FIXME: Use multiple files instead */
8675 acfg->fp = fopen (acfg->tmpfname, "a+");
8677 if (acfg->aot_opts.asm_only) {
8678 if (acfg->aot_opts.outfile)
8679 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8681 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8682 acfg->fp = fopen (acfg->tmpfname, "w+");
8684 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8685 acfg->fp = fdopen (i, "w+");
8687 if (acfg->fp == 0) {
8688 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8692 acfg->w = img_writer_create (acfg->fp, FALSE);
8694 tmp_outfile_name = NULL;
8695 outfile_name = NULL;
8698 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8700 /* Compute symbols for methods */
8701 for (i = 0; i < acfg->nmethods; ++i) {
8702 if (acfg->cfgs [i]) {
8703 MonoCompile *cfg = acfg->cfgs [i];
8704 int method_index = get_method_index (acfg, cfg->orig_method);
8706 if (COMPILE_LLVM (cfg))
8707 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8708 else if (acfg->global_symbols)
8709 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8711 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8715 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8717 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8719 acfg->gas_line_numbers = TRUE;
8722 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8723 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8724 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8727 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8730 img_writer_emit_start (acfg->w);
8733 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8735 if (acfg->thumb_mixed) {
8738 * This global symbol marks the end of THUMB code, and the beginning of ARM
8739 * code generated by our JIT.
8741 sprintf (symbol, "thumb_end");
8742 emit_section_change (acfg, ".text", 0);
8743 emit_alignment (acfg, 8);
8744 emit_label (acfg, symbol);
8745 emit_zero_bytes (acfg, 16);
8747 fprintf (acfg->fp, ".arm\n");
8754 emit_extra_methods (acfg);
8756 emit_trampolines (acfg);
8758 emit_class_name_table (acfg);
8760 emit_got_info (acfg);
8762 emit_exception_info (acfg);
8764 emit_unwind_info (acfg);
8766 emit_class_info (acfg);
8770 emit_image_table (acfg);
8774 emit_file_info (acfg);
8778 emit_globals (acfg);
8780 emit_autoreg (acfg);
8783 emit_dwarf_info (acfg);
8784 mono_dwarf_writer_close (acfg->dwarf);
8787 emit_mem_end (acfg);
8789 if (acfg->need_pt_gnu_stack) {
8790 /* This is required so the .so doesn't have an executable stack */
8791 /* The bin writer already emits this */
8792 if (!acfg->use_bin_writer)
8793 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8798 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8801 g_assert (acfg->got_offset <= acfg->final_got_size);
8804 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8806 strcpy (llvm_stats_msg, "");
8807 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);
8808 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8809 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8811 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8812 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8813 if (acfg->stats.genericcount)
8814 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8815 if (acfg->stats.abscount)
8816 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8817 if (acfg->stats.lmfcount)
8818 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8819 if (acfg->stats.ocount)
8820 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8823 res = img_writer_emit_writeout (acfg->w);
8828 if (acfg->use_bin_writer) {
8829 int err = rename (tmp_outfile_name, outfile_name);
8832 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8836 res = compile_asm (acfg);
8843 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8845 if (acfg->aot_opts.stats) {
8848 printf ("GOT slot distribution:\n");
8849 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8850 if (acfg->stats.got_slot_types [i])
8851 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8854 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);
8866 mono_aot_readonly_field_override (MonoClassField *field)
8872 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)