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/abi-details.h>
47 #include <mono/metadata/tabledefs.h>
48 #include <mono/metadata/class.h>
49 #include <mono/metadata/object.h>
50 #include <mono/metadata/tokentype.h>
51 #include <mono/metadata/appdomain.h>
52 #include <mono/metadata/debug-helpers.h>
53 #include <mono/metadata/assembly.h>
54 #include <mono/metadata/metadata-internals.h>
55 #include <mono/metadata/marshal.h>
56 #include <mono/metadata/gc-internal.h>
57 #include <mono/metadata/monitor.h>
58 #include <mono/metadata/mempool-internals.h>
59 #include <mono/metadata/mono-endian.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/utils/mono-logger-internal.h>
62 #include <mono/utils/mono-compiler.h>
63 #include <mono/utils/mono-time.h>
64 #include <mono/utils/mono-mmap.h>
67 #include "image-writer.h"
68 #include "dwarfwriter.h"
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
73 #if defined(__linux__) || defined(__native_client_codegen__)
74 #define RODATA_SECT ".rodata"
75 #elif defined(TARGET_MACH)
76 #define RODATA_SECT ".section __TEXT, __const"
78 #define RODATA_SECT ".text"
81 #define TV_DECLARE(name) gint64 name
82 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
83 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
86 #define SHARED_EXT ".dll"
87 #elif defined(__ppc__) && defined(TARGET_MACH)
88 #define SHARED_EXT ".dylib"
89 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
90 #define SHARED_EXT ".dylib"
91 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
92 #define SHARED_EXT ".dylib"
94 #define SHARED_EXT ".so"
97 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
98 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
99 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
101 /* predefined values for static readonly fields without needed to run the .cctor */
102 typedef struct _ReadOnlyValue ReadOnlyValue;
103 struct _ReadOnlyValue {
106 int type; /* to be used later for typechecking to prevent user errors */
115 static ReadOnlyValue *readonly_values;
117 typedef struct MonoAotOptions {
120 gboolean write_symbols;
121 gboolean metadata_only;
122 gboolean bind_to_runtime_version;
125 gboolean static_link;
129 gboolean dwarf_debug;
131 gboolean log_generics;
132 gboolean log_instances;
133 gboolean direct_pinvoke;
134 gboolean direct_icalls;
135 gboolean no_direct_calls;
136 gboolean use_trampolines_page;
137 gboolean no_instances;
141 int nrgctx_trampolines;
142 int nimt_trampolines;
143 int ngsharedvt_arg_trampolines;
144 int nrgctx_fetch_trampolines;
145 gboolean print_skipped_methods;
151 char *instances_logfile_path;
154 typedef struct MonoAotStats {
155 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
156 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
157 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
158 int got_slots, offsets_size;
159 int got_slot_types [MONO_PATCH_INFO_NONE];
160 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
161 int jit_time, gen_time, link_time;
164 typedef struct MonoAotCompile {
167 GHashTable *method_indexes;
168 GHashTable *method_depth;
171 GHashTable **patch_to_plt_entry;
172 GHashTable *plt_offset_to_entry;
173 GHashTable *patch_to_got_offset;
174 GHashTable **patch_to_got_offset_by_type;
175 GPtrArray *got_patches;
176 GHashTable *image_hash;
177 GHashTable *method_to_cfg;
178 GHashTable *token_info_hash;
179 GHashTable *method_to_pinvoke_import;
180 GPtrArray *extra_methods;
181 GPtrArray *image_table;
183 GPtrArray *method_order;
184 GHashTable *export_names;
185 /* Maps MonoClass* -> blob offset */
186 GHashTable *klass_blob_hash;
187 /* Maps MonoMethod* -> blob offset */
188 GHashTable *method_blob_hash;
189 guint32 *plt_got_info_offsets;
190 guint32 got_offset, plt_offset, plt_got_offset_base;
191 guint32 final_got_size;
192 /* Number of GOT entries reserved for trampolines */
193 guint32 num_trampoline_got_entries;
194 guint32 tramp_page_size;
196 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
197 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
198 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
199 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
201 MonoAotOptions aot_opts;
205 MonoMemPool *mempool;
208 char *static_linking_symbol;
210 gboolean use_bin_writer;
211 gboolean gas_line_numbers;
213 MonoDwarfWriter *dwarf;
218 GHashTable *unwind_info_offsets;
219 GPtrArray *unwind_ops;
220 guint32 unwind_info_offset;
221 char *got_symbol_base;
224 char *methods_symbol;
225 GHashTable *method_label_hash;
226 const char *temp_prefix;
227 const char *user_symbol_prefix;
228 const char *llvm_label_prefix;
229 const char *inst_directive;
230 guint32 label_generator;
232 MonoAotFileFlags flags;
233 MonoDynamicStream blob;
234 MonoClass **typespec_classes;
237 char *assembly_name_sym;
238 GHashTable *plt_entry_debug_sym_cache;
239 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
240 GHashTable *ginst_hash;
241 GHashTable *dwarf_ln_filenames;
242 gboolean global_symbols;
243 gboolean direct_method_addresses;
244 int objc_selector_index, objc_selector_index_2;
245 GPtrArray *objc_selectors;
246 GHashTable *objc_selector_to_index;
247 FILE *instances_logfile;
252 char *symbol, *llvm_symbol, *debug_sym;
254 gboolean jit_used, llvm_used;
257 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
258 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
260 /* This points to the current acfg in LLVM mode */
261 static MonoAotCompile *llvm_acfg;
263 #ifdef HAVE_ARRAY_ELEM_INIT
264 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
265 #define MSGSTRFIELD1(line) str##line
266 static const struct msgstr_t {
267 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
268 #include "patch-info.h"
271 #define PATCH_INFO(a,b) b,
272 #include "patch-info.h"
275 static const gint16 opidx [] = {
276 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
277 #include "patch-info.h"
281 static G_GNUC_UNUSED const char*
282 get_patch_name (int info)
284 return (const char*)&opstr + opidx [info];
288 #define PATCH_INFO(a,b) b,
289 static const char* const
290 patch_types [MONO_PATCH_INFO_NUM + 1] = {
291 #include "patch-info.h"
295 static G_GNUC_UNUSED const char*
296 get_patch_name (int info)
298 return patch_types [info];
304 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
306 /* Wrappers around the image writer functions */
309 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
311 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
315 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
317 img_writer_emit_push_section (acfg->w, section_name, subsection);
321 emit_pop_section (MonoAotCompile *acfg)
323 img_writer_emit_pop_section (acfg->w);
327 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
329 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
333 emit_label (MonoAotCompile *acfg, const char *name)
335 img_writer_emit_label (acfg->w, name);
339 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
341 img_writer_emit_bytes (acfg->w, buf, size);
345 emit_string (MonoAotCompile *acfg, const char *value)
347 img_writer_emit_string (acfg->w, value);
351 emit_line (MonoAotCompile *acfg)
353 img_writer_emit_line (acfg->w);
357 emit_alignment (MonoAotCompile *acfg, int size)
359 img_writer_emit_alignment (acfg->w, size);
363 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
365 img_writer_emit_pointer_unaligned (acfg->w, target);
369 emit_pointer (MonoAotCompile *acfg, const char *target)
371 img_writer_emit_pointer (acfg->w, target);
375 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
377 if (prefix [0] != '\0') {
378 char *s = g_strdup_printf ("%s%s", prefix, target);
379 img_writer_emit_pointer (acfg->w, s);
382 img_writer_emit_pointer (acfg->w, target);
387 emit_int16 (MonoAotCompile *acfg, int value)
389 img_writer_emit_int16 (acfg->w, value);
393 emit_int32 (MonoAotCompile *acfg, int value)
395 img_writer_emit_int32 (acfg->w, value);
399 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
401 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
405 emit_zero_bytes (MonoAotCompile *acfg, int num)
407 img_writer_emit_zero_bytes (acfg->w, num);
411 emit_byte (MonoAotCompile *acfg, guint8 val)
413 img_writer_emit_byte (acfg->w, val);
416 #ifdef __native_client_codegen__
418 emit_nacl_call_alignment (MonoAotCompile *acfg)
420 img_writer_emit_nacl_call_alignment (acfg->w);
424 static G_GNUC_UNUSED void
425 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
427 img_writer_emit_global (acfg->w, name, func);
431 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
433 if (acfg->aot_opts.no_dlsym) {
434 g_ptr_array_add (acfg->globals, g_strdup (name));
435 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
437 img_writer_emit_global (acfg->w, name, func);
442 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
444 img_writer_emit_symbol_size (acfg->w, name, end_label);
448 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
450 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
452 /* On apple, all symbols need to be aligned to avoid warnings from ld */
453 emit_alignment (acfg, 4);
455 img_writer_emit_label (acfg->w, name);
456 img_writer_emit_string (acfg->w, value);
459 static G_GNUC_UNUSED void
460 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
463 guint8 b = value & 0x7f;
465 if (value != 0) /* more bytes to come */
471 static G_GNUC_UNUSED void
472 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
475 gboolean negative = (value < 0);
482 /* the following is unnecessary if the
483 * implementation of >>= uses an arithmetic rather
484 * than logical shift for a signed left operand
488 value |= - ((gint64)1 <<(size - 7));
489 /* sign bit of byte is second high order bit (0x40) */
490 if ((value == 0 && !(byte & 0x40)) ||
491 (value == -1 && (byte & 0x40)))
495 emit_byte (acfg, byte);
499 static G_GNUC_UNUSED void
500 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
505 guint8 b = value & 0x7f;
507 if (value != 0) /* more bytes to come */
515 static G_GNUC_UNUSED void
516 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
519 gboolean negative = (value < 0);
527 /* the following is unnecessary if the
528 * implementation of >>= uses an arithmetic rather
529 * than logical shift for a signed left operand
533 value |= - (1 <<(size - 7));
534 /* sign bit of byte is second high order bit (0x40) */
535 if ((value == 0 && !(byte & 0x40)) ||
536 (value == -1 && (byte & 0x40)))
547 emit_unset_mode (MonoAotCompile *acfg)
549 img_writer_emit_unset_mode (acfg->w);
552 static G_GNUC_UNUSED void
553 emit_set_thumb_mode (MonoAotCompile *acfg)
555 emit_unset_mode (acfg);
556 fprintf (acfg->fp, ".code 16\n");
559 static G_GNUC_UNUSED void
560 emit_set_arm_mode (MonoAotCompile *acfg)
562 emit_unset_mode (acfg);
563 fprintf (acfg->fp, ".code 32\n");
567 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
572 g_assert (size % 4 == 0);
573 emit_unset_mode (acfg);
574 for (i = 0; i < size; i += 4)
575 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
577 emit_bytes (acfg, buf, size);
581 /* ARCHITECTURE SPECIFIC CODE */
583 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
584 #define EMIT_DWARF_INFO 1
587 #if defined(TARGET_ARM)
588 #define AOT_FUNC_ALIGNMENT 4
590 #define AOT_FUNC_ALIGNMENT 16
592 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
593 #undef AOT_FUNC_ALIGNMENT
594 #define AOT_FUNC_ALIGNMENT 32
597 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
598 #define PPC_LD_OP "ld"
599 #define PPC_LDX_OP "ldx"
601 #define PPC_LD_OP "lwz"
602 #define PPC_LDX_OP "lwzx"
606 #define AOT_TARGET_STR "AMD64"
611 #define AOT_TARGET_STR "ARM (MACH)"
613 #define AOT_TARGET_STR "ARM (!MACH)"
619 #define AOT_TARGET_STR "ARM64 (MACH)"
621 #define AOT_TARGET_STR "ARM64 (!MACH)"
625 #ifdef TARGET_POWERPC64
626 #ifdef __mono_ilp32__
627 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
629 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
632 #ifdef TARGET_POWERPC
633 #ifdef __mono_ilp32__
634 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
636 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
643 #define AOT_TARGET_STR "X86 (WIN32)"
644 #elif defined(__native_client_codegen__)
645 #define AOT_TARGET_STR "X86 (native client codegen)"
647 #define AOT_TARGET_STR "X86 (!native client codegen)"
651 #ifndef AOT_TARGET_STR
652 #define AOT_TARGET_STR ""
656 arch_init (MonoAotCompile *acfg)
658 acfg->llc_args = g_string_new ("");
659 acfg->as_args = g_string_new ("");
662 * The prefix LLVM likes to put in front of symbol names on darwin.
663 * The mach-os specs require this for globals, but LLVM puts them in front of all
664 * symbols. We need to handle this, since we need to refer to LLVM generated
667 acfg->llvm_label_prefix = "";
668 acfg->user_symbol_prefix = "";
670 #if defined(TARGET_AMD64)
671 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
675 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
676 g_string_append (acfg->llc_args, "-mattr=+v6");
679 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
680 g_string_append (acfg->as_args, " -mfpu=vfp3");
682 g_string_append (acfg->llc_args, " -soft-float");
685 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
686 acfg->thumb_mixed = TRUE;
688 if (acfg->aot_opts.mtriple)
689 mono_arch_set_target (acfg->aot_opts.mtriple);
693 acfg->inst_directive = ".inst";
694 if (acfg->aot_opts.mtriple)
695 mono_arch_set_target (acfg->aot_opts.mtriple);
699 acfg->user_symbol_prefix = "_";
700 acfg->llvm_label_prefix = "_";
701 acfg->inst_directive = ".word";
702 acfg->need_no_dead_strip = TRUE;
703 acfg->aot_opts.gnu_asm = TRUE;
706 #if defined(__linux__) && !defined(TARGET_ARM)
707 acfg->need_pt_gnu_stack = TRUE;
711 acfg->direct_method_addresses = TRUE;
712 acfg->global_symbols = TRUE;
718 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
722 #ifdef MONO_ARCH_AOT_SUPPORTED
724 * arch_emit_direct_call:
726 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
730 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
732 #if defined(TARGET_X86) || defined(TARGET_AMD64)
733 /* Need to make sure this is exactly 5 bytes long */
734 if (external && !acfg->use_bin_writer) {
735 emit_unset_mode (acfg);
736 fprintf (acfg->fp, "call %s\n", target);
738 emit_byte (acfg, '\xe8');
739 emit_symbol_diff (acfg, target, ".", -4);
742 #elif defined(TARGET_ARM)
743 if (acfg->use_bin_writer) {
750 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
751 emit_bytes (acfg, buf, 4);
753 emit_unset_mode (acfg);
755 fprintf (acfg->fp, "blx %s\n", target);
757 fprintf (acfg->fp, "bl %s\n", target);
760 #elif defined(TARGET_ARM64)
761 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
762 #elif defined(TARGET_POWERPC)
763 if (acfg->use_bin_writer) {
764 g_assert_not_reached ();
766 emit_unset_mode (acfg);
767 fprintf (acfg->fp, "bl %s\n", target);
771 g_assert_not_reached ();
778 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
780 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
781 * in in the 2. slot of every GOT, and require every method to place the GOT
782 * address in r30, even when it doesn't access the GOT otherwise. This way,
783 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
788 * PPC64 uses function descriptors which greatly complicate all code, since
789 * these are used very inconsistently in the runtime. Some functions like
790 * mono_compile_method () return ftn descriptors, while others like the
791 * trampoline creation functions do not.
792 * We assume that all GOT slots contain function descriptors, and create
793 * descriptors in aot-runtime.c when needed.
794 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
795 * from function descriptors, we could do the same, but it would require
796 * rewriting all the ppc/aot code to handle function descriptors properly.
797 * So instead, we use the same approach as on PPC32.
798 * This is a horrible mess, but fixing it would probably lead to an even bigger
804 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
807 #ifdef MONO_ARCH_AOT_SUPPORTED
809 * arch_emit_got_offset:
811 * The memory pointed to by CODE should hold native code for computing the GOT
812 * address. Emit this code while patching it with the offset between code and
813 * the GOT. CODE_SIZE is set to the number of bytes emitted.
816 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
818 #if defined(TARGET_POWERPC64)
819 g_assert (!acfg->use_bin_writer);
820 emit_unset_mode (acfg);
822 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
823 * unsupported relocations. So we store the got address into the .Lgot_addr
824 * symbol which is in the text segment, compute its address, and load it.
826 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
827 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
828 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
829 fprintf (acfg->fp, "add 30, 30, 0\n");
830 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
831 acfg->label_generator ++;
833 #elif defined(TARGET_POWERPC)
834 g_assert (!acfg->use_bin_writer);
835 emit_unset_mode (acfg);
836 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
837 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
838 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
839 acfg->label_generator ++;
842 guint32 offset = mono_arch_get_patch_offset (code);
843 emit_bytes (acfg, code, offset);
844 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
846 *code_size = offset + 4;
851 * arch_emit_got_access:
853 * The memory pointed to by CODE should hold native code for loading a GOT
854 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
855 * CODE_SIZE is set to the number of bytes emitted.
858 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
860 /* Emit beginning of instruction */
861 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
863 /* Emit the offset */
865 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
866 *code_size = mono_arch_get_patch_offset (code) + 4;
867 #elif defined(TARGET_X86)
868 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
869 *code_size = mono_arch_get_patch_offset (code) + 4;
870 #elif defined(TARGET_ARM)
871 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
872 *code_size = mono_arch_get_patch_offset (code) + 4;
873 #elif defined(TARGET_ARM64)
874 arm64_emit_got_access (acfg, code, got_slot, code_size);
875 #elif defined(TARGET_POWERPC)
881 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
882 g_assert (code - buf == 8);
883 emit_bytes (acfg, buf, code - buf);
884 *code_size = code - buf;
887 g_assert_not_reached ();
893 #ifdef MONO_ARCH_AOT_SUPPORTED
895 * arch_emit_objc_selector_ref:
897 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
900 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
902 #if defined(TARGET_ARM)
905 int lindex = acfg->objc_selector_index_2 ++;
908 emit_bytes (acfg, code, 8);
910 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
911 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
913 emit_label (acfg, symbol1);
914 img_writer_emit_unset_mode (acfg->w);
915 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
918 #elif defined(TARGET_ARM64)
919 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
921 g_assert_not_reached ();
927 * arch_emit_plt_entry:
929 * Emit code for the PLT entry with index INDEX.
932 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
934 #if defined(TARGET_X86)
935 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
936 #if defined(__default_codegen__)
937 /* jmp *<offset>(%ebx) */
938 emit_byte (acfg, 0xff);
939 emit_byte (acfg, 0xa3);
940 emit_int32 (acfg, offset);
941 /* Used by mono_aot_get_plt_info_offset */
942 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
943 #elif defined(__native_client_codegen__)
944 const guint8 kSizeOfNaClJmp = 11;
945 guint8 bytes[kSizeOfNaClJmp];
946 guint8 *pbytes = &bytes[0];
948 x86_jump_membase32 (pbytes, X86_EBX, offset);
949 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
950 /* four bytes of data, used by mono_arch_patch_plt_entry */
951 /* For Native Client, make this work with data embedded in push. */
952 emit_byte (acfg, 0x68); /* hide data in a push */
953 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
954 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
955 #endif /*__native_client_codegen__*/
956 #elif defined(TARGET_AMD64)
957 #if defined(__default_codegen__)
959 * We can't emit jumps because they are 32 bits only so they can't be patched.
960 * So we make indirect calls through GOT entries which are patched by the AOT
961 * loader to point to .Lpd entries.
963 /* jmpq *<offset>(%rip) */
964 emit_byte (acfg, '\xff');
965 emit_byte (acfg, '\x25');
966 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
967 /* Used by mono_aot_get_plt_info_offset */
968 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
969 acfg->stats.plt_size += 10;
970 #elif defined(__native_client_codegen__)
972 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
973 guint8 *code = buf_aligned;
975 /* mov <OFFSET>(%rip), %r11d */
976 emit_byte (acfg, '\x45');
977 emit_byte (acfg, '\x8b');
978 emit_byte (acfg, '\x1d');
979 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
981 amd64_jump_reg (code, AMD64_R11);
982 /* This should be constant for the plt patch */
983 g_assert ((size_t)(code-buf_aligned) == 10);
984 emit_bytes (acfg, buf_aligned, code - buf_aligned);
986 /* Hide data in a push imm32 so it passes validation */
987 emit_byte (acfg, 0x68); /* push */
988 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
989 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
990 #endif /*__native_client_codegen__*/
991 #elif defined(TARGET_ARM)
996 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
997 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
998 emit_bytes (acfg, buf, code - buf);
999 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
1000 /* Used by mono_aot_get_plt_info_offset */
1001 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1002 #elif defined(TARGET_ARM64)
1003 arm64_emit_plt_entry (acfg, index);
1004 #elif defined(TARGET_POWERPC)
1005 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
1007 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1008 g_assert (!acfg->use_bin_writer);
1009 emit_unset_mode (acfg);
1010 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1011 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1012 fprintf (acfg->fp, "add 11, 11, 30\n");
1013 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1014 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1015 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1016 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1018 fprintf (acfg->fp, "mtctr 11\n");
1019 fprintf (acfg->fp, "bctr\n");
1020 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1022 g_assert_not_reached ();
1027 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
1029 #if defined(TARGET_ARM)
1031 /* LLVM calls the PLT entries using bl, so emit a stub */
1032 /* FIXME: Too much overhead on every call */
1033 fprintf (acfg->fp, ".thumb_func\n");
1034 fprintf (acfg->fp, "bx pc\n");
1035 fprintf (acfg->fp, "nop\n");
1036 fprintf (acfg->fp, ".arm\n");
1038 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1039 /* The caller already transitioned to thumb */
1040 /* The code below should be 12 bytes long */
1041 /* clang has trouble encoding these instructions, so emit the binary */
1043 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1044 /* thumb can't encode ld pc, [pc, ip] */
1045 fprintf (acfg->fp, "add ip, pc, ip\n");
1046 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1047 fprintf (acfg->fp, "bx ip\n");
1049 emit_set_thumb_mode (acfg);
1050 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1051 fprintf (acfg->fp, ".2byte 0x44fc\n");
1052 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1053 fprintf (acfg->fp, ".2byte 0x4760\n");
1054 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1055 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1056 emit_unset_mode (acfg);
1057 emit_set_arm_mode (acfg);
1059 g_assert_not_reached ();
1064 * arch_emit_specific_trampoline_pages:
1066 * Emits a page full of trampolines: each trampoline uses its own address to
1067 * lookup both the generic trampoline code and the data argument.
1068 * This page can be remapped in process multiple times so we can get an
1069 * unlimited number of trampolines.
1070 * Specifically this implementation uses the following trick: two memory pages
1071 * are allocated, with the first containing the data and the second containing the trampolines.
1072 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1073 * implementation does all the lifting.
1074 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1075 * on the arm 32 bit system.
1078 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1080 #if defined(TARGET_ARM)
1083 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1085 #define COMMON_TRAMP_SIZE 16
1086 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1087 int imm8, rot_amount;
1090 if (!acfg->aot_opts.use_trampolines_page)
1093 acfg->tramp_page_size = mono_pagesize ();
1095 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1096 emit_alignment (acfg, mono_pagesize ());
1097 emit_global (acfg, symbol, TRUE);
1098 emit_label (acfg, symbol);
1100 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1102 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1103 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1104 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1105 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1107 g_assert (code - buf == COMMON_TRAMP_SIZE);
1110 emit_bytes (acfg, buf, code - buf);
1112 for (i = 0; i < count; ++i) {
1114 ARM_PUSH (code, 0x5fff);
1116 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1117 g_assert (code - buf == 8);
1118 emit_bytes (acfg, buf, code - buf);
1121 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1122 * the instruction pointer address, so the generic trampoline at the start of the page
1123 * subtracts 4096 to get to the data page and loads the values
1124 * We again fit the generic trampiline in 16 bytes.
1126 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1127 emit_global (acfg, symbol, TRUE);
1128 emit_label (acfg, symbol);
1130 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1131 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1132 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1133 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1135 g_assert (code - buf == COMMON_TRAMP_SIZE);
1138 emit_bytes (acfg, buf, code - buf);
1140 for (i = 0; i < count; ++i) {
1142 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1144 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1145 g_assert (code - buf == 8);
1146 emit_bytes (acfg, buf, code - buf);
1150 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1152 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1153 emit_global (acfg, symbol, TRUE);
1154 emit_label (acfg, symbol);
1156 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1157 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1158 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1159 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1160 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1161 g_assert (code - buf == COMMON_TRAMP_SIZE);
1163 emit_bytes (acfg, buf, code - buf);
1165 for (i = 0; i < count; ++i) {
1167 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1169 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1170 g_assert (code - buf == 8);
1171 emit_bytes (acfg, buf, code - buf);
1174 /* now the imt trampolines: each specific trampolines puts in the ip register
1175 * the instruction pointer address, so the generic trampoline at the start of the page
1176 * subtracts 4096 to get to the data page and loads the values
1177 * We again fit the generic trampiline in 16 bytes.
1179 #define IMT_TRAMP_SIZE 72
1180 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1181 emit_global (acfg, symbol, TRUE);
1182 emit_label (acfg, symbol);
1184 /* Need at least two free registers, plus a slot for storing the pc */
1185 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1187 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1188 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1189 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1191 /* The IMT method is in v5, r0 has the imt array address */
1194 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1195 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1196 imt_found_check = code;
1197 ARM_B_COND (code, ARMCOND_EQ, 0);
1199 /* End-of-loop check */
1200 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1201 loop_end_check = code;
1202 ARM_B_COND (code, ARMCOND_EQ, 0);
1205 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1206 loop_branch_back = code;
1208 arm_patch (loop_branch_back, loop_start);
1211 arm_patch (imt_found_check, code);
1212 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1213 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1214 /* Save it to the third stack slot */
1215 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1216 /* Restore the registers and branch */
1217 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1220 arm_patch (loop_end_check, code);
1221 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1222 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1223 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1227 g_assert (code - buf == IMT_TRAMP_SIZE);
1228 emit_bytes (acfg, buf, code - buf);
1230 for (i = 0; i < count; ++i) {
1232 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1234 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1235 g_assert (code - buf == 8);
1236 emit_bytes (acfg, buf, code - buf);
1238 #elif defined(TARGET_ARM64)
1239 arm64_emit_specific_trampoline_pages (acfg);
1244 * arch_emit_specific_trampoline:
1246 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1247 * two GOT slots which contain the generic trampoline address and the trampoline
1248 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1251 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1254 * The trampolines created here are variations of the specific
1255 * trampolines created in mono_arch_create_specific_trampoline (). The
1257 * - the generic trampoline address is taken from a got slot.
1258 * - the offset of the got slot where the trampoline argument is stored
1259 * is embedded in the instruction stream, and the generic trampoline
1260 * can load the argument by loading the offset, adding it to the
1261 * address of the trampoline to get the address of the got slot, and
1262 * loading the argument from there.
1263 * - all the trampolines should be of the same length.
1265 #if defined(TARGET_AMD64)
1266 #if defined(__default_codegen__)
1267 /* This should be exactly 16 bytes long */
1269 /* call *<offset>(%rip) */
1270 emit_byte (acfg, '\x41');
1271 emit_byte (acfg, '\xff');
1272 emit_byte (acfg, '\x15');
1273 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1274 /* This should be relative to the start of the trampoline */
1275 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1276 emit_zero_bytes (acfg, 5);
1277 #elif defined(__native_client_codegen__)
1279 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1280 guint8 *code = buf_aligned;
1285 /* Emit this call in 'code' so we can find out how long it is. */
1286 amd64_call_reg (code, AMD64_R11);
1287 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1288 call_len = code - call_start;
1290 /* The tramp_size is twice the NaCl alignment because it starts with */
1291 /* a call which needs to be aligned to the end of the boundary. */
1292 *tramp_size = kNaClAlignment*2;
1294 /* Emit nops to align call site below which is 7 bytes plus */
1295 /* the length of the call sequence emitted above. */
1296 /* Note: this requires the specific trampoline starts on a */
1297 /* kNaclAlignedment aligned address, which it does because */
1298 /* it's its own function that is aligned. */
1299 guint8 nop_buf[256];
1300 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1301 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1302 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1304 /* The trampoline is stored at the offset'th pointer, the -4 is */
1305 /* present because RIP relative addressing starts at the end of */
1306 /* the current instruction, while the label "." is relative to */
1307 /* the beginning of the current asm location, which in this case */
1308 /* is not the mov instruction, but the offset itself, due to the */
1309 /* way the bytes and ints are emitted here. */
1310 got_offset = (offset * sizeof(gpointer)) - 4;
1312 /* mov <OFFSET>(%rip), %r11d */
1313 emit_byte (acfg, '\x45');
1314 emit_byte (acfg, '\x8b');
1315 emit_byte (acfg, '\x1d');
1316 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1319 emit_bytes (acfg, call_start, call_len);
1321 /* The arg is stored at the offset+1 pointer, relative to beginning */
1322 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1323 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1325 /* We can't emit this data directly, hide in a "push imm32" */
1326 emit_byte (acfg, '\x68'); /* push */
1327 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1328 emit_alignment (acfg, kNaClAlignment);
1329 #endif /*__native_client_codegen__*/
1330 #elif defined(TARGET_ARM)
1334 /* This should be exactly 20 bytes long */
1337 ARM_PUSH (code, 0x5fff);
1338 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1339 /* Load the value from the GOT */
1340 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1342 ARM_BLX_REG (code, ARMREG_R1);
1344 g_assert (code - buf == 16);
1347 emit_bytes (acfg, buf, code - buf);
1349 * Only one offset is needed, since the second one would be equal to the
1352 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1353 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1354 #elif defined(TARGET_ARM64)
1355 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1356 #elif defined(TARGET_POWERPC)
1363 g_assert (!acfg->use_bin_writer);
1366 * PPC has no ip relative addressing, so we need to compute the address
1367 * of the mscorlib got. That is slow and complex, so instead, we store it
1368 * in the second got slot of every aot image. The caller already computed
1369 * the address of its got and placed it into r30.
1371 emit_unset_mode (acfg);
1372 /* Load mscorlib got address */
1373 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1374 /* Load generic trampoline address */
1375 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1376 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1377 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1378 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1379 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1381 fprintf (acfg->fp, "mtctr 11\n");
1382 /* Load trampoline argument */
1383 /* On ppc, we pass it normally to the generic trampoline */
1384 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1385 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1386 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1387 /* Branch to generic trampoline */
1388 fprintf (acfg->fp, "bctr\n");
1390 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1391 *tramp_size = 10 * 4;
1393 *tramp_size = 9 * 4;
1395 #elif defined(TARGET_X86)
1399 /* Similar to the PPC code above */
1401 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1403 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1404 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1405 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1409 /* Load mscorlib got address */
1410 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1411 /* Push trampoline argument */
1412 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1413 /* Load generic trampoline address */
1414 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1415 /* Branch to generic trampoline */
1416 x86_jump_reg (code, X86_ECX);
1418 #ifdef __native_client_codegen__
1420 /* emit nops to next 32 byte alignment */
1421 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1422 while (code < (buf + a)) x86_nop(code);
1425 emit_bytes (acfg, buf, code - buf);
1427 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1428 g_assert (code - buf == *tramp_size);
1430 g_assert_not_reached ();
1435 * arch_emit_unbox_trampoline:
1437 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1438 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1441 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1443 #if defined(TARGET_AMD64)
1448 this_reg = mono_arch_get_this_arg_reg (NULL);
1450 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1452 emit_bytes (acfg, buf, code - buf);
1454 emit_byte (acfg, '\xe9');
1455 emit_symbol_diff (acfg, call_target, ".", -4);
1456 #elif defined(TARGET_X86)
1463 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1465 emit_bytes (acfg, buf, code - buf);
1468 emit_byte (acfg, '\xe9');
1469 emit_symbol_diff (acfg, call_target, ".", -4);
1470 #elif defined(TARGET_ARM)
1474 if (acfg->thumb_mixed && cfg->compile_llvm) {
1475 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1476 fprintf (acfg->fp, "b %s\n", call_target);
1477 fprintf (acfg->fp, ".arm\n");
1478 fprintf (acfg->fp, ".align 2\n");
1484 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1486 emit_bytes (acfg, buf, code - buf);
1487 /* jump to method */
1488 if (acfg->use_bin_writer) {
1495 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1496 emit_bytes (acfg, buf, 4);
1498 if (acfg->thumb_mixed && cfg->compile_llvm)
1499 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1501 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1503 #elif defined(TARGET_ARM64)
1504 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1505 #elif defined(TARGET_POWERPC)
1508 g_assert (!acfg->use_bin_writer);
1510 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1511 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1513 g_assert_not_reached ();
1518 * arch_emit_static_rgctx_trampoline:
1520 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1521 * two GOT slots which contain the rgctx argument, and the method to jump to.
1522 * TRAMP_SIZE is set to the size of the emitted trampoline.
1523 * These kinds of trampolines cannot be enumerated statically, since there could
1524 * be one trampoline per method instantiation, so we emit the same code for all
1525 * trampolines, and parameterize them using two GOT slots.
1528 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1530 #if defined(TARGET_AMD64)
1531 #if defined(__default_codegen__)
1532 /* This should be exactly 13 bytes long */
1535 /* mov <OFFSET>(%rip), %r10 */
1536 emit_byte (acfg, '\x4d');
1537 emit_byte (acfg, '\x8b');
1538 emit_byte (acfg, '\x15');
1539 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1541 /* jmp *<offset>(%rip) */
1542 emit_byte (acfg, '\xff');
1543 emit_byte (acfg, '\x25');
1544 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1545 #elif defined(__native_client_codegen__)
1547 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1548 guint8 *code = buf_aligned;
1550 /* mov <OFFSET>(%rip), %r10d */
1551 emit_byte (acfg, '\x45');
1552 emit_byte (acfg, '\x8b');
1553 emit_byte (acfg, '\x15');
1554 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1556 /* mov <OFFSET>(%rip), %r11d */
1557 emit_byte (acfg, '\x45');
1558 emit_byte (acfg, '\x8b');
1559 emit_byte (acfg, '\x1d');
1560 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1563 amd64_jump_reg (code, AMD64_R11);
1564 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1566 emit_alignment (acfg, kNaClAlignment);
1567 *tramp_size = kNaClAlignment;
1568 #endif /*__native_client_codegen__*/
1570 #elif defined(TARGET_ARM)
1574 /* This should be exactly 24 bytes long */
1577 /* Load rgctx value */
1578 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1579 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1580 /* Load branch addr + branch */
1581 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1582 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1584 g_assert (code - buf == 16);
1587 emit_bytes (acfg, buf, code - buf);
1588 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1589 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1590 #elif defined(TARGET_ARM64)
1591 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1592 #elif defined(TARGET_POWERPC)
1599 g_assert (!acfg->use_bin_writer);
1602 * PPC has no ip relative addressing, so we need to compute the address
1603 * of the mscorlib got. That is slow and complex, so instead, we store it
1604 * in the second got slot of every aot image. The caller already computed
1605 * the address of its got and placed it into r30.
1607 emit_unset_mode (acfg);
1608 /* Load mscorlib got address */
1609 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1611 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1612 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1613 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1614 /* Load target address */
1615 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1616 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1617 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1618 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1619 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1620 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1622 fprintf (acfg->fp, "mtctr 11\n");
1623 /* Branch to the target address */
1624 fprintf (acfg->fp, "bctr\n");
1626 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1627 *tramp_size = 11 * 4;
1629 *tramp_size = 9 * 4;
1632 #elif defined(TARGET_X86)
1636 /* Similar to the PPC code above */
1638 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1641 /* Load mscorlib got address */
1642 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1644 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1645 /* Branch to the target address */
1646 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1648 #ifdef __native_client_codegen__
1650 /* emit nops to next 32 byte alignment */
1651 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1652 while (code < (buf + a)) x86_nop(code);
1656 emit_bytes (acfg, buf, code - buf);
1658 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1659 g_assert (code - buf == *tramp_size);
1661 g_assert_not_reached ();
1666 * arch_emit_imt_thunk:
1668 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1669 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1670 * key is the IMT key, and ptr holds the address of a memory location holding
1671 * the address to branch to if the IMT arg matches the key. The array is
1672 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1674 * TRAMP_SIZE is set to the size of the emitted trampoline.
1677 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1679 #if defined(TARGET_AMD64)
1681 #if defined(__native_client_codegen__)
1684 guint8 *labels [16];
1686 guint8 *mov_buf_ptr = mov_buf;
1688 const int kSizeOfMove = 7;
1689 #if defined(__default_codegen__)
1690 code = buf = g_malloc (256);
1691 #elif defined(__native_client_codegen__)
1692 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1693 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1694 /* The RIP relative move below is emitted first */
1699 /* FIXME: Optimize this, i.e. use binary search etc. */
1700 /* Maybe move the body into a separate function (slower, but much smaller) */
1702 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1705 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1707 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1710 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1712 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1715 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1716 amd64_jump_code (code, labels [0]);
1719 mono_amd64_patch (labels [2], code);
1720 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1721 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1724 mono_amd64_patch (labels [1], code);
1725 /* Load fail tramp */
1726 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1727 /* Check if there is a fail tramp */
1728 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1730 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1731 /* Jump to fail tramp */
1732 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1735 mono_amd64_patch (labels [3], code);
1736 x86_breakpoint (code);
1738 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1739 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1740 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1741 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1742 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1743 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1745 emit_bytes (acfg, buf, code - buf);
1747 *tramp_size = code - buf + kSizeOfMove;
1748 #if defined(__native_client_codegen__)
1749 /* The tramp will be padded to the next kNaClAlignment bundle. */
1750 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1753 #if defined(__default_codegen__)
1755 #elif defined(__native_client_codegen__)
1759 #elif defined(TARGET_X86)
1761 #ifdef __native_client_codegen__
1764 guint8 *labels [16];
1766 #if defined(__default_codegen__)
1767 code = buf = g_malloc (256);
1768 #elif defined(__native_client_codegen__)
1769 buf_alloc = g_malloc (256 + kNaClAlignment);
1770 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1773 /* Allocate a temporary stack slot */
1774 x86_push_reg (code, X86_EAX);
1776 x86_push_reg (code, X86_EAX);
1778 /* Load mscorlib got address */
1779 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1781 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1784 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1786 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1789 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1791 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1794 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1795 x86_jump_code (code, labels [0]);
1798 mono_x86_patch (labels [2], code);
1799 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1800 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1801 /* Save the target address to the temporary stack location */
1802 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1804 x86_pop_reg (code, X86_EAX);
1805 /* Jump to the target address */
1809 mono_x86_patch (labels [1], code);
1810 /* Load fail tramp */
1811 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1812 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1814 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1815 /* Jump to fail tramp */
1816 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1817 x86_pop_reg (code, X86_EAX);
1821 mono_x86_patch (labels [3], code);
1822 x86_breakpoint (code);
1824 #ifdef __native_client_codegen__
1826 /* emit nops to next 32 byte alignment */
1827 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1828 while (code < (buf + a)) x86_nop(code);
1831 emit_bytes (acfg, buf, code - buf);
1833 *tramp_size = code - buf;
1835 #if defined(__default_codegen__)
1837 #elif defined(__native_client_codegen__)
1841 #elif defined(TARGET_ARM)
1843 guint8 *code, *code2, *labels [16];
1847 /* The IMT method is in v5 */
1849 /* Need at least two free registers, plus a slot for storing the pc */
1850 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1852 /* Load the parameter from the GOT */
1853 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1854 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1857 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1858 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1860 ARM_B_COND (code, ARMCOND_EQ, 0);
1862 /* End-of-loop check */
1863 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1865 ARM_B_COND (code, ARMCOND_EQ, 0);
1868 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1871 arm_patch (labels [4], labels [1]);
1874 arm_patch (labels [2], code);
1875 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1876 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1877 /* Save it to the third stack slot */
1878 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1879 /* Restore the registers and branch */
1880 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1883 arm_patch (labels [3], code);
1884 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1885 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1886 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1890 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1892 emit_bytes (acfg, buf, code - buf);
1893 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1895 *tramp_size = code - buf + 4;
1896 #elif defined(TARGET_ARM64)
1897 arm64_emit_imt_thunk (acfg, offset, tramp_size);
1898 #elif defined(TARGET_POWERPC)
1900 guint8 *code, *labels [16];
1904 /* Load the mscorlib got address */
1905 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1906 /* Load the parameter from the GOT */
1907 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1908 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1910 /* Load and check key */
1912 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1913 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1915 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1917 /* End-of-loop check */
1918 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1920 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1923 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1926 mono_ppc_patch (labels [4], labels [1]);
1929 mono_ppc_patch (labels [2], code);
1930 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1931 /* r11 now contains the value of the vtable slot */
1932 /* this is not a function descriptor on ppc64 */
1933 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1934 ppc_mtctr (code, ppc_r11);
1935 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1938 mono_ppc_patch (labels [3], code);
1942 *tramp_size = code - buf;
1944 emit_bytes (acfg, buf, code - buf);
1946 g_assert_not_reached ();
1951 * arch_emit_gsharedvt_arg_trampoline:
1953 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1954 * two GOT slots which contain the argument, and the code to jump to.
1955 * TRAMP_SIZE is set to the size of the emitted trampoline.
1956 * These kinds of trampolines cannot be enumerated statically, since there could
1957 * be one trampoline per method instantiation, so we emit the same code for all
1958 * trampolines, and parameterize them using two GOT slots.
1961 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1963 #if defined(TARGET_X86)
1967 /* Similar to the PPC code above */
1969 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1972 /* Load mscorlib got address */
1973 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1975 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1976 /* Branch to the target address */
1977 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1979 #ifdef __native_client_codegen__
1981 /* emit nops to next 32 byte alignment */
1982 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1983 while (code < (buf + a)) x86_nop(code);
1987 emit_bytes (acfg, buf, code - buf);
1989 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1990 g_assert (code - buf == *tramp_size);
1991 #elif defined(TARGET_ARM)
1995 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1996 /* Similar to arch_emit_specific_trampoline () */
1999 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2000 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2001 /* Load the arg value from the GOT */
2002 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2003 /* Load the addr from the GOT */
2004 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2006 ARM_BX (code, ARMREG_R1);
2008 g_assert (code - buf == 20);
2011 emit_bytes (acfg, buf, code - buf);
2012 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2013 #elif defined(TARGET_ARM64)
2014 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2016 g_assert_not_reached ();
2021 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2023 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2024 /* Based on code generated by gcc */
2025 emit_unset_mode (acfg);
2028 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2029 ".section .ctors,\"aw\",@progbits\n"
2033 ".section .opd,\"aw\"\n"
2036 ".long .%s,.TOC.@tocbase32\n"
2039 ".type .%s,@function\n"
2041 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2043 ".section .ctors,\"aw\",@progbits\n"
2047 ".section .opd,\"aw\"\n"
2050 ".long .%1$s,.TOC.@tocbase32\n"
2051 ".size %1$s,.-%1$s\n"
2053 ".type .%1$s,@function\n"
2055 ".%1$s:\n", symbol);
2066 "lis 3, .Lglobals@h\n"
2067 "ori 3, 3, .Lglobals@l\n"
2068 "bl .mono_aot_register_module\n"
2076 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2078 ".size .%s,.-.%s\n", symbol, symbol);
2081 ".size .%1$s,.-.%1$s\n", symbol);
2087 /* END OF ARCH SPECIFIC CODE */
2090 mono_get_field_token (MonoClassField *field)
2092 MonoClass *klass = field->parent;
2095 for (i = 0; i < klass->field.count; ++i) {
2096 if (field == &klass->fields [i])
2097 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2100 g_assert_not_reached ();
2105 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2109 //printf ("ENCODE: %d 0x%x.\n", value, value);
2112 * Same encoding as the one used in the metadata, extended to handle values
2113 * greater than 0x1fffffff.
2115 if ((value >= 0) && (value <= 127))
2117 else if ((value >= 0) && (value <= 16383)) {
2118 p [0] = 0x80 | (value >> 8);
2119 p [1] = value & 0xff;
2121 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2122 p [0] = (value >> 24) | 0xc0;
2123 p [1] = (value >> 16) & 0xff;
2124 p [2] = (value >> 8) & 0xff;
2125 p [3] = value & 0xff;
2130 p [1] = (value >> 24) & 0xff;
2131 p [2] = (value >> 16) & 0xff;
2132 p [3] = (value >> 8) & 0xff;
2133 p [4] = value & 0xff;
2141 stream_init (MonoDynamicStream *sh)
2144 sh->alloc_size = 4096;
2145 sh->data = g_malloc (4096);
2147 /* So offsets are > 0 */
2153 make_room_in_stream (MonoDynamicStream *stream, int size)
2155 if (size <= stream->alloc_size)
2158 while (stream->alloc_size <= size) {
2159 if (stream->alloc_size < 4096)
2160 stream->alloc_size = 4096;
2162 stream->alloc_size *= 2;
2165 stream->data = g_realloc (stream->data, stream->alloc_size);
2169 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2173 make_room_in_stream (stream, stream->index + len);
2174 memcpy (stream->data + stream->index, data, len);
2175 idx = stream->index;
2176 stream->index += len;
2183 * Add data to the binary blob inside the aot image. Returns the offset inside the
2184 * blob where the data was stored.
2187 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2189 if (acfg->blob.alloc_size == 0)
2190 stream_init (&acfg->blob);
2192 return add_stream_data (&acfg->blob, (char*)data, data_len);
2196 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2201 if (acfg->blob.alloc_size == 0)
2202 stream_init (&acfg->blob);
2204 count = acfg->blob.index % align;
2206 /* we assume the stream data will be aligned */
2208 add_stream_data (&acfg->blob, buf, 4 - count);
2210 return add_stream_data (&acfg->blob, (char*)data, data_len);
2214 * emit_offset_table:
2216 * Emit a table of increasing offsets in a compact form using differential encoding.
2217 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2218 * group size, the more compact the table becomes, but the slower it becomes to compute
2219 * a given entry. Returns the size of the table.
2222 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2224 gint32 current_offset;
2225 int i, buf_size, ngroups, index_entry_size;
2227 guint32 *index_offsets;
2229 ngroups = (noffsets + (group_size - 1)) / group_size;
2231 index_offsets = g_new0 (guint32, ngroups);
2233 buf_size = noffsets * 4;
2234 p = buf = g_malloc0 (buf_size);
2237 for (i = 0; i < noffsets; ++i) {
2238 //printf ("D: %d -> %d\n", i, offsets [i]);
2239 if ((i % group_size) == 0) {
2240 index_offsets [i / group_size] = p - buf;
2241 /* Emit the full value for these entries */
2242 encode_value (offsets [i], p, &p);
2244 /* The offsets are allowed to be non-increasing */
2245 //g_assert (offsets [i] >= current_offset);
2246 encode_value (offsets [i] - current_offset, p, &p);
2248 current_offset = offsets [i];
2251 if (ngroups && index_offsets [ngroups - 1] < 65000)
2252 index_entry_size = 2;
2254 index_entry_size = 4;
2256 /* Emit the header */
2257 emit_int32 (acfg, noffsets);
2258 emit_int32 (acfg, group_size);
2259 emit_int32 (acfg, ngroups);
2260 emit_int32 (acfg, index_entry_size);
2262 /* Emit the index */
2263 for (i = 0; i < ngroups; ++i) {
2264 if (index_entry_size == 2)
2265 emit_int16 (acfg, index_offsets [i]);
2267 emit_int32 (acfg, index_offsets [i]);
2271 emit_bytes (acfg, buf, p - buf);
2273 return (int)(p - buf) + (ngroups * 4);
2277 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2281 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2285 index = g_hash_table_size (cfg->image_hash);
2286 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2287 g_ptr_array_add (cfg->image_table, image);
2293 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2296 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2298 /* FIXME: Search referenced images as well */
2299 if (!acfg->typespec_classes) {
2300 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2301 for (i = 0; i < len; ++i) {
2302 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2305 for (i = 0; i < len; ++i) {
2306 if (acfg->typespec_classes [i] == klass)
2311 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2317 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2320 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2323 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2326 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2329 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2334 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2338 if (klass->generic_class) {
2340 g_assert (klass->type_token);
2342 /* Find a typespec for a class if possible */
2343 token = find_typespec_for_class (acfg, klass);
2345 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2346 encode_value (token, p, &p);
2348 MonoClass *gclass = klass->generic_class->container_class;
2349 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2350 static int count = 0;
2353 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2354 encode_klass_ref (acfg, gclass, p, &p);
2355 encode_ginst (acfg, inst, p, &p);
2359 } else if (klass->type_token) {
2360 int iindex = get_image_index (acfg, klass->image);
2362 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2364 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2365 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2367 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2368 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2369 encode_value (get_image_index (acfg, klass->image), p, &p);
2371 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2372 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2373 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2375 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2376 encode_value (klass->byval_arg.type, p, &p);
2377 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2379 encode_value (container ? 1 : 0, p, &p);
2381 encode_value (container->is_method, p, &p);
2382 g_assert (par->serial == 0);
2383 if (container->is_method)
2384 encode_method_ref (acfg, container->owner.method, p, &p);
2386 encode_klass_ref (acfg, container->owner.klass, p, &p);
2388 encode_value (par->serial, p, &p);
2390 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2391 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2392 encode_type (acfg, &klass->byval_arg, p, &p);
2395 g_assert (klass->rank > 0);
2396 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2397 encode_value (klass->rank, p, &p);
2398 encode_klass_ref (acfg, klass->element_class, p, &p);
2406 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2407 * standard metadata encoding.
2410 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2412 gboolean shared = FALSE;
2415 * The encoding of generic instances is large so emit them only once.
2417 if (klass->generic_class) {
2419 g_assert (klass->type_token);
2421 /* Find a typespec for a class if possible */
2422 token = find_typespec_for_class (acfg, klass);
2425 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2430 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2434 buf2 = g_malloc (1024);
2437 encode_klass_ref_inner (acfg, klass, p, &p);
2438 g_assert (p - buf2 < 1024);
2440 offset = add_to_blob (acfg, buf2, p - buf2);
2443 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2449 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2450 encode_value (offset, p, &p);
2455 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2459 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2461 guint32 token = mono_get_field_token (field);
2464 encode_klass_ref (cfg, field->parent, p, &p);
2465 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2466 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2471 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2476 encode_value (inst->type_argc, p, &p);
2477 for (i = 0; i < inst->type_argc; ++i)
2478 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2483 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2486 MonoGenericInst *inst;
2488 inst = context->class_inst;
2490 g_assert (inst->type_argc);
2491 encode_ginst (acfg, inst, p, &p);
2493 encode_value (0, p, &p);
2495 inst = context->method_inst;
2497 g_assert (inst->type_argc);
2498 encode_ginst (acfg, inst, p, &p);
2500 encode_value (0, p, &p);
2506 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2510 g_assert (t->num_mods == 0);
2511 /* t->attrs can be ignored */
2512 //g_assert (t->attrs == 0);
2515 *p = MONO_TYPE_PINNED;
2519 *p = MONO_TYPE_BYREF;
2527 case MONO_TYPE_VOID:
2528 case MONO_TYPE_BOOLEAN:
2529 case MONO_TYPE_CHAR:
2542 case MONO_TYPE_STRING:
2543 case MONO_TYPE_OBJECT:
2544 case MONO_TYPE_TYPEDBYREF:
2546 case MONO_TYPE_VALUETYPE:
2547 case MONO_TYPE_CLASS:
2548 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2550 case MONO_TYPE_SZARRAY:
2551 encode_klass_ref (acfg, t->data.klass, p, &p);
2554 encode_type (acfg, t->data.type, p, &p);
2556 case MONO_TYPE_GENERICINST: {
2557 MonoClass *gclass = t->data.generic_class->container_class;
2558 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2560 encode_klass_ref (acfg, gclass, p, &p);
2561 encode_ginst (acfg, inst, p, &p);
2564 case MONO_TYPE_ARRAY: {
2565 MonoArrayType *array = t->data.array;
2568 encode_klass_ref (acfg, array->eklass, p, &p);
2569 encode_value (array->rank, p, &p);
2570 encode_value (array->numsizes, p, &p);
2571 for (i = 0; i < array->numsizes; ++i)
2572 encode_value (array->sizes [i], p, &p);
2573 encode_value (array->numlobounds, p, &p);
2574 for (i = 0; i < array->numlobounds; ++i)
2575 encode_value (array->lobounds [i], p, &p);
2579 case MONO_TYPE_MVAR:
2580 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2583 g_assert_not_reached ();
2590 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2596 /* Similar to the metadata encoding */
2597 if (sig->generic_param_count)
2601 if (sig->explicit_this)
2603 flags |= (sig->call_convention & 0x0F);
2607 if (sig->generic_param_count)
2608 encode_value (sig->generic_param_count, p, &p);
2609 encode_value (sig->param_count, p, &p);
2611 encode_type (acfg, sig->ret, p, &p);
2612 for (i = 0; i < sig->param_count; ++i) {
2613 if (sig->sentinelpos == i) {
2614 *p = MONO_TYPE_SENTINEL;
2617 encode_type (acfg, sig->params [i], p, &p);
2623 #define MAX_IMAGE_INDEX 250
2626 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2628 guint32 image_index = get_image_index (acfg, method->klass->image);
2629 guint32 token = method->token;
2630 MonoJumpInfoToken *ji;
2634 * The encoding for most methods is as follows:
2635 * - image index encoded as a leb128
2636 * - token index encoded as a leb128
2637 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2638 * types of method encodings.
2641 /* Mark methods which can't use aot trampolines because they need the further
2642 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2644 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2645 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2646 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2648 if (method->wrapper_type) {
2649 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2651 encode_value (method->wrapper_type, p, &p);
2653 switch (method->wrapper_type) {
2654 case MONO_WRAPPER_REMOTING_INVOKE:
2655 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2656 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2659 m = mono_marshal_method_from_wrapper (method);
2661 encode_method_ref (acfg, m, p, &p);
2664 case MONO_WRAPPER_PROXY_ISINST:
2665 case MONO_WRAPPER_LDFLD:
2666 case MONO_WRAPPER_LDFLDA:
2667 case MONO_WRAPPER_STFLD:
2668 case MONO_WRAPPER_ISINST: {
2669 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2670 encode_klass_ref (acfg, proxy_class, p, &p);
2673 case MONO_WRAPPER_LDFLD_REMOTE:
2674 case MONO_WRAPPER_STFLD_REMOTE:
2676 case MONO_WRAPPER_ALLOC: {
2677 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2679 /* The GC name is saved once in MonoAotFileInfo */
2680 g_assert (info->alloc_type != -1);
2681 encode_value (info->alloc_type, p, &p);
2684 case MONO_WRAPPER_WRITE_BARRIER:
2686 case MONO_WRAPPER_STELEMREF: {
2687 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2690 encode_value (info->subtype, p, &p);
2691 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2692 encode_value (info->d.virtual_stelemref.kind, p, &p);
2695 case MONO_WRAPPER_UNKNOWN: {
2696 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2699 encode_value (info->subtype, p, &p);
2700 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2701 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2702 encode_klass_ref (acfg, method->klass, p, &p);
2703 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2704 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2705 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2706 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2709 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2710 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2713 encode_value (info->subtype, p, &p);
2714 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2715 strcpy ((char*)p, method->name);
2716 p += strlen (method->name) + 1;
2717 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2718 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2720 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2721 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2725 case MONO_WRAPPER_SYNCHRONIZED: {
2728 m = mono_marshal_method_from_wrapper (method);
2730 g_assert (m != method);
2731 encode_method_ref (acfg, m, p, &p);
2734 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2735 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2738 encode_value (info->subtype, p, &p);
2740 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2741 encode_value (info->d.element_addr.rank, p, &p);
2742 encode_value (info->d.element_addr.elem_size, p, &p);
2743 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2744 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2746 g_assert_not_reached ();
2750 case MONO_WRAPPER_CASTCLASS: {
2751 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2754 encode_value (info->subtype, p, &p);
2757 case MONO_WRAPPER_RUNTIME_INVOKE: {
2758 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2761 encode_value (info->subtype, p, &p);
2762 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2763 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2764 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2765 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2768 case MONO_WRAPPER_DELEGATE_INVOKE:
2769 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2770 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2771 if (method->is_inflated) {
2772 /* These wrappers are identified by their class */
2773 encode_value (1, p, &p);
2774 encode_klass_ref (acfg, method->klass, p, &p);
2776 MonoMethodSignature *sig = mono_method_signature (method);
2777 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2779 encode_value (0, p, &p);
2780 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2781 encode_value (info ? info->subtype : 0, p, &p);
2782 encode_signature (acfg, sig, p, &p);
2786 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2787 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2790 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2791 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2795 g_assert_not_reached ();
2797 } else if (mono_method_signature (method)->is_inflated) {
2799 * This is a generic method, find the original token which referenced it and
2801 * Obtain the token from information recorded by the JIT.
2803 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2805 image_index = get_image_index (acfg, ji->image);
2806 g_assert (image_index < MAX_IMAGE_INDEX);
2809 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2810 encode_value (image_index, p, &p);
2811 encode_value (token, p, &p);
2813 MonoMethod *declaring;
2814 MonoGenericContext *context = mono_method_get_context (method);
2816 g_assert (method->is_inflated);
2817 declaring = ((MonoMethodInflated*)method)->declaring;
2820 * This might be a non-generic method of a generic instance, which
2821 * doesn't have a token since the reference is generated by the JIT
2822 * like Nullable:Box/Unbox, or by generic sharing.
2824 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2825 /* Encode the klass */
2826 encode_klass_ref (acfg, method->klass, p, &p);
2827 /* Encode the method */
2828 image_index = get_image_index (acfg, method->klass->image);
2829 g_assert (image_index < MAX_IMAGE_INDEX);
2830 g_assert (declaring->token);
2831 token = declaring->token;
2832 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2833 encode_value (image_index, p, &p);
2834 encode_value (token, p, &p);
2835 encode_generic_context (acfg, context, p, &p);
2837 } else if (token == 0) {
2838 /* This might be a method of a constructed type like int[,].Set */
2839 /* Obtain the token from information recorded by the JIT */
2840 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2842 image_index = get_image_index (acfg, ji->image);
2843 g_assert (image_index < MAX_IMAGE_INDEX);
2846 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2847 encode_value (image_index, p, &p);
2848 encode_value (token, p, &p);
2851 g_assert (method->klass->rank);
2853 /* Encode directly */
2854 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2855 encode_klass_ref (acfg, method->klass, p, &p);
2856 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2857 encode_value (0, p, &p);
2858 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2859 encode_value (1, p, &p);
2860 else if (!strcmp (method->name, "Get"))
2861 encode_value (2, p, &p);
2862 else if (!strcmp (method->name, "Address"))
2863 encode_value (3, p, &p);
2864 else if (!strcmp (method->name, "Set"))
2865 encode_value (4, p, &p);
2867 g_assert_not_reached ();
2870 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2872 if (image_index >= MONO_AOT_METHODREF_MIN) {
2873 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2874 encode_value (image_index, p, &p);
2875 encode_value (mono_metadata_token_index (token), p, &p);
2877 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2884 compare_patches (gconstpointer a, gconstpointer b)
2888 i = (*(MonoJumpInfo**)a)->ip.i;
2889 j = (*(MonoJumpInfo**)b)->ip.i;
2900 static G_GNUC_UNUSED char*
2901 patch_to_string (MonoJumpInfo *patch_info)
2905 str = g_string_new ("");
2907 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2909 switch (patch_info->type) {
2910 case MONO_PATCH_INFO_VTABLE:
2911 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2916 g_string_append_printf (str, ")");
2917 return g_string_free (str, FALSE);
2923 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2926 static inline gboolean
2927 is_plt_patch (MonoJumpInfo *patch_info)
2929 switch (patch_info->type) {
2930 case MONO_PATCH_INFO_METHOD:
2931 case MONO_PATCH_INFO_INTERNAL_METHOD:
2932 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2933 case MONO_PATCH_INFO_ICALL_ADDR:
2934 case MONO_PATCH_INFO_CLASS_INIT:
2935 case MONO_PATCH_INFO_RGCTX_FETCH:
2936 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2937 case MONO_PATCH_INFO_MONITOR_ENTER:
2938 case MONO_PATCH_INFO_MONITOR_EXIT:
2939 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2949 * Return the symbol identifying the plt entry PLT_OFFSET.
2952 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2956 * The Apple linker reorganizes object files, so it doesn't like branches to local
2957 * labels, since those have no relocations.
2959 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2961 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2968 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2970 static MonoPltEntry*
2971 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2975 if (!is_plt_patch (patch_info))
2978 if (!acfg->patch_to_plt_entry [patch_info->type])
2979 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2980 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2982 // FIXME: This breaks the calculation of final_got_size
2983 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2985 * Allocate a separate PLT slot for each such patch, since some plt
2986 * entries will refer to the method itself, and some will refer to the
2993 MonoJumpInfo *new_ji;
2995 g_assert (!acfg->final_got_size);
2997 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2999 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3000 res->plt_offset = acfg->plt_offset;
3002 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3003 if (acfg->aot_opts.write_symbols)
3004 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3006 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3008 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3010 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3012 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3014 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3015 //mono_print_ji (patch_info); printf ("\n");
3016 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3018 acfg->plt_offset ++;
3027 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3028 * JI could be found if it exists, otherwise allocates a new one.
3031 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
3035 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
3037 return got_offset - 1;
3039 got_offset = acfg->got_offset;
3040 acfg->got_offset ++;
3042 if (acfg->final_got_size)
3043 g_assert (got_offset < acfg->final_got_size);
3045 acfg->stats.got_slots ++;
3046 acfg->stats.got_slot_types [ji->type] ++;
3048 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3049 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3050 g_ptr_array_add (acfg->got_patches, ji);
3055 /* Add a method to the list of methods which need to be emitted */
3057 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3060 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3061 g_ptr_array_add (acfg->methods, method);
3062 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3063 acfg->nmethods = acfg->methods->len + 1;
3066 if (method->wrapper_type || extra)
3067 g_ptr_array_add (acfg->extra_methods, method);
3071 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3073 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3081 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3085 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3089 index = acfg->method_index;
3090 add_method_with_index (acfg, method, index, extra);
3092 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3094 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3096 acfg->method_index ++;
3102 add_method (MonoAotCompile *acfg, MonoMethod *method)
3104 return add_method_full (acfg, method, FALSE, 0);
3108 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3110 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3111 method = mini_get_shared_method (method);
3113 if (acfg->aot_opts.log_generics)
3114 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3116 add_method_full (acfg, method, TRUE, depth);
3120 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3122 add_extra_method_with_depth (acfg, method, 0);
3126 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3128 MonoAotCompile *acfg = user_data;
3129 MonoJitICallInfo *callinfo = value;
3130 MonoMethod *wrapper;
3136 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3137 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3140 add_method (acfg, wrapper);
3144 get_runtime_invoke_sig (MonoMethodSignature *sig)
3146 MonoMethodBuilder *mb;
3149 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3150 m = mono_mb_create_method (mb, sig, 16);
3151 return mono_marshal_get_runtime_invoke (m, FALSE);
3155 can_marshal_struct (MonoClass *klass)
3157 MonoClassField *field;
3158 gboolean can_marshal = TRUE;
3159 gpointer iter = NULL;
3160 MonoMarshalType *info;
3163 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3166 info = mono_marshal_load_type_info (klass);
3168 /* Only allow a few field types to avoid asserts in the marshalling code */
3169 while ((field = mono_class_get_fields (klass, &iter))) {
3170 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3173 switch (field->type->type) {
3178 case MONO_TYPE_BOOLEAN:
3181 case MONO_TYPE_CHAR:
3189 case MONO_TYPE_STRING:
3191 case MONO_TYPE_VALUETYPE:
3192 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3193 can_marshal = FALSE;
3195 case MONO_TYPE_SZARRAY: {
3196 gboolean has_mspec = FALSE;
3199 for (i = 0; i < info->num_fields; ++i) {
3200 if (info->fields [i].field == field && info->fields [i].mspec)
3205 can_marshal = FALSE;
3209 can_marshal = FALSE;
3215 /* Its hard to compute whenever these can be marshalled or not */
3216 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3223 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3225 /* Create a vtype instantiation */
3226 MonoGenericContext shared_context;
3228 MonoGenericInst *inst;
3229 MonoGenericContainer *container;
3230 MonoClass **constraints;
3233 memset (ctx, 0, sizeof (MonoGenericContext));
3235 if (method->klass->generic_container) {
3236 shared_context = method->klass->generic_container->context;
3237 inst = shared_context.class_inst;
3239 args = g_new0 (MonoType*, inst->type_argc);
3240 for (i = 0; i < inst->type_argc; ++i) {
3241 args [i] = &mono_defaults.int_class->byval_arg;
3243 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3245 if (method->is_generic) {
3246 container = mono_method_get_generic_container (method);
3247 shared_context = container->context;
3248 inst = shared_context.method_inst;
3250 args = g_new0 (MonoType*, inst->type_argc);
3251 for (i = 0; i < container->type_argc; ++i) {
3252 MonoGenericParamInfo *info = &container->type_params [i].info;
3253 gboolean ref_only = FALSE;
3255 if (info && info->constraints) {
3256 constraints = info->constraints;
3258 while (*constraints) {
3259 MonoClass *cklass = *constraints;
3260 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3261 /* Inflaring the method with our vtype would not be valid */
3268 args [i] = &mono_defaults.object_class->byval_arg;
3270 args [i] = &mono_defaults.int_class->byval_arg;
3272 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3277 add_wrappers (MonoAotCompile *acfg)
3279 MonoMethod *method, *m;
3281 MonoMethodSignature *sig, *csig;
3285 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3286 * so there is only one wrapper of a given type, or inlining their contents into their
3289 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3291 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3292 gboolean skip = FALSE;
3294 method = mono_get_method (acfg->image, token, NULL);
3296 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3297 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3298 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3301 /* Skip methods which can not be handled by get_runtime_invoke () */
3302 sig = mono_method_signature (method);
3305 if ((sig->ret->type == MONO_TYPE_PTR) ||
3306 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3308 if (mono_class_is_open_constructed_type (sig->ret))
3311 for (j = 0; j < sig->param_count; j++) {
3312 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3314 if (mono_class_is_open_constructed_type (sig->params [j]))
3318 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3319 if (!mono_class_is_contextbound (method->klass)) {
3320 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3321 gboolean has_nullable = FALSE;
3323 for (j = 0; j < sig->param_count; j++) {
3324 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3325 has_nullable = TRUE;
3328 if (info && !has_nullable) {
3329 /* Supported by the dynamic runtime-invoke wrapper */
3337 //printf ("%s\n", mono_method_full_name (method, TRUE));
3338 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3342 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3343 MonoMethodDesc *desc;
3344 MonoMethod *orig_method;
3347 /* Runtime invoke wrappers */
3349 /* void runtime-invoke () [.cctor] */
3350 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3351 csig->ret = &mono_defaults.void_class->byval_arg;
3352 add_method (acfg, get_runtime_invoke_sig (csig));
3354 /* void runtime-invoke () [Finalize] */
3355 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3357 csig->ret = &mono_defaults.void_class->byval_arg;
3358 add_method (acfg, get_runtime_invoke_sig (csig));
3360 /* void runtime-invoke (string) [exception ctor] */
3361 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3363 csig->ret = &mono_defaults.void_class->byval_arg;
3364 csig->params [0] = &mono_defaults.string_class->byval_arg;
3365 add_method (acfg, get_runtime_invoke_sig (csig));
3367 /* void runtime-invoke (string, string) [exception ctor] */
3368 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3370 csig->ret = &mono_defaults.void_class->byval_arg;
3371 csig->params [0] = &mono_defaults.string_class->byval_arg;
3372 csig->params [1] = &mono_defaults.string_class->byval_arg;
3373 add_method (acfg, get_runtime_invoke_sig (csig));
3375 /* string runtime-invoke () [Exception.ToString ()] */
3376 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3378 csig->ret = &mono_defaults.string_class->byval_arg;
3379 add_method (acfg, get_runtime_invoke_sig (csig));
3381 /* void runtime-invoke (string, Exception) [exception ctor] */
3382 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3384 csig->ret = &mono_defaults.void_class->byval_arg;
3385 csig->params [0] = &mono_defaults.string_class->byval_arg;
3386 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3387 add_method (acfg, get_runtime_invoke_sig (csig));
3389 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3390 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3392 csig->ret = &(mono_class_from_name (
3393 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3394 csig->params [0] = &mono_defaults.string_class->byval_arg;
3395 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3396 add_method (acfg, get_runtime_invoke_sig (csig));
3398 /* runtime-invoke used by finalizers */
3399 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3401 /* This is used by mono_runtime_capture_context () */
3402 method = mono_get_context_capture_method ();
3404 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3406 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3407 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3411 add_method (acfg, mono_marshal_get_stelemref ());
3413 if (MONO_ARCH_HAVE_TLS_GET) {
3414 /* Managed Allocators */
3415 nallocators = mono_gc_get_managed_allocator_types ();
3416 for (i = 0; i < nallocators; ++i) {
3417 m = mono_gc_get_managed_allocator_by_type (i);
3419 add_method (acfg, m);
3422 /* Monitor Enter/Exit */
3423 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3424 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3425 /* This is a v4 method */
3427 method = mono_monitor_get_fast_path (orig_method);
3429 add_method (acfg, method);
3431 mono_method_desc_free (desc);
3433 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3434 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3435 g_assert (orig_method);
3436 mono_method_desc_free (desc);
3437 method = mono_monitor_get_fast_path (orig_method);
3439 add_method (acfg, method);
3442 /* Stelemref wrappers */
3444 MonoMethod **wrappers;
3447 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3448 for (i = 0; i < nwrappers; ++i)
3449 add_method (acfg, wrappers [i]);
3453 /* castclass_with_check wrapper */
3454 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3455 /* isinst_with_check wrapper */
3456 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3458 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3460 MonoMethodDesc *desc;
3463 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3464 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3465 mono_method_desc_free (desc);
3467 m = mono_monitor_get_fast_path (m);
3469 add_method (acfg, m);
3474 /* JIT icall wrappers */
3475 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3476 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3480 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3481 * we use the original method instead at runtime.
3482 * Since full-aot doesn't support remoting, this is not a problem.
3485 /* remoting-invoke wrappers */
3486 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3487 MonoMethodSignature *sig;
3489 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3490 method = mono_get_method (acfg->image, token, NULL);
3492 sig = mono_method_signature (method);
3494 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3495 m = mono_marshal_get_remoting_invoke_with_check (method);
3497 add_method (acfg, m);
3502 /* delegate-invoke wrappers */
3503 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3505 MonoCustomAttrInfo *cattr;
3507 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3508 klass = mono_class_get (acfg->image, token);
3511 mono_loader_clear_error ();
3515 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3518 if (!klass->generic_container) {
3519 method = mono_get_delegate_invoke (klass);
3521 m = mono_marshal_get_delegate_invoke (method, NULL);
3523 add_method (acfg, m);
3525 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3527 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3529 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3531 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3533 cattr = mono_custom_attrs_from_class (klass);
3538 for (j = 0; j < cattr->num_attrs; ++j)
3539 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3541 if (j < cattr->num_attrs)
3542 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3544 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3545 MonoGenericContext ctx;
3546 MonoMethod *inst, *gshared;
3549 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3552 method = mono_get_delegate_invoke (klass);
3553 create_gsharedvt_inst (acfg, method, &ctx);
3555 inst = mono_class_inflate_generic_method (method, &ctx);
3557 m = mono_marshal_get_delegate_invoke (inst, NULL);
3558 g_assert (m->is_inflated);
3560 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3561 add_extra_method (acfg, gshared);
3564 method = mono_get_delegate_begin_invoke (klass);
3565 create_gsharedvt_inst (acfg, method, &ctx);
3567 inst = mono_class_inflate_generic_method (method, &ctx);
3569 m = mono_marshal_get_delegate_begin_invoke (inst);
3570 g_assert (m->is_inflated);
3572 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3573 add_extra_method (acfg, gshared);
3576 method = mono_get_delegate_end_invoke (klass);
3577 create_gsharedvt_inst (acfg, method, &ctx);
3579 inst = mono_class_inflate_generic_method (method, &ctx);
3581 m = mono_marshal_get_delegate_end_invoke (inst);
3582 g_assert (m->is_inflated);
3584 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3585 add_extra_method (acfg, gshared);
3590 /* array access wrappers */
3591 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3594 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3595 klass = mono_class_get (acfg->image, token);
3598 mono_loader_clear_error ();
3602 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3603 MonoMethod *m, *wrapper;
3605 /* Add runtime-invoke wrappers too */
3607 m = mono_class_get_method_from_name (klass, "Get", -1);
3609 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3610 add_extra_method (acfg, wrapper);
3611 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3613 m = mono_class_get_method_from_name (klass, "Set", -1);
3615 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3616 add_extra_method (acfg, wrapper);
3617 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3621 /* Synchronized wrappers */
3622 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3623 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3624 method = mono_get_method (acfg->image, token, NULL);
3626 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3627 if (method->is_generic) {
3629 } else if (method->klass->generic_container) {
3630 MonoGenericContext ctx;
3631 MonoMethod *inst, *gshared, *m;
3634 * Create a generic wrapper for a generic instance, and AOT that.
3636 create_gsharedvt_inst (acfg, method, &ctx);
3637 inst = mono_class_inflate_generic_method (method, &ctx);
3638 m = mono_marshal_get_synchronized_wrapper (inst);
3639 g_assert (m->is_inflated);
3640 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3641 add_method (acfg, gshared);
3643 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3648 /* pinvoke wrappers */
3649 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3651 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3653 method = mono_get_method (acfg->image, token, NULL);
3655 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3656 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3657 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3661 /* native-to-managed wrappers */
3662 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3664 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3665 MonoCustomAttrInfo *cattr;
3668 method = mono_get_method (acfg->image, token, NULL);
3671 * Only generate native-to-managed wrappers for methods which have an
3672 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3673 * name to avoid defining a new assembly to contain it.
3675 cattr = mono_custom_attrs_from_method (method);
3678 for (j = 0; j < cattr->num_attrs; ++j)
3679 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3681 if (j < cattr->num_attrs) {
3682 MonoCustomAttrEntry *e = &cattr->attrs [j];
3683 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3684 const char *p = (const char*)e->data;
3686 int slen, num_named, named_type, data_type;
3690 char *export_name = NULL;
3691 MonoMethod *wrapper;
3693 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3694 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3695 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3696 mono_method_full_name (method, TRUE));
3700 g_assert (sig->param_count == 1);
3701 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3704 * Decode the cattr manually since we can't create objects
3705 * during aot compilation.
3711 /* From load_cattr_value () in reflection.c */
3712 slen = mono_metadata_decode_value (p, &p);
3713 n = g_memdup (p, slen + 1);
3715 t = mono_reflection_type_from_name (n, acfg->image);
3719 klass = mono_class_from_mono_type (t);
3720 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3724 num_named = read16 (p);
3727 g_assert (num_named < 2);
3728 if (num_named == 1) {
3731 MonoType *prop_type;
3733 /* parse ExportSymbol attribute */
3735 named_type = *named;
3740 name_len = mono_metadata_decode_blob_size (named, &named);
3741 name = g_malloc (name_len + 1);
3742 memcpy (name, named, name_len);
3743 name [name_len] = 0;
3746 g_assert (named_type == 0x54);
3747 g_assert (!strcmp (name, "ExportSymbol"));
3749 prop_type = &mono_defaults.string_class->byval_arg;
3751 /* load_cattr_value (), string case */
3752 g_assert (*named != (char)0xff);
3753 slen = mono_metadata_decode_value (named, &named);
3754 export_name = g_malloc (slen + 1);
3755 memcpy (export_name, named, slen);
3756 export_name [slen] = 0;
3760 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3761 add_method (acfg, wrapper);
3763 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3767 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3768 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3769 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3773 /* StructureToPtr/PtrToStructure wrappers */
3774 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3777 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3778 klass = mono_class_get (acfg->image, token);
3781 mono_loader_clear_error ();
3785 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3786 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3787 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3788 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3794 has_type_vars (MonoClass *klass)
3796 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3799 return has_type_vars (klass->element_class);
3800 if (klass->generic_class) {
3801 MonoGenericContext *context = &klass->generic_class->context;
3802 if (context->class_inst) {
3805 for (i = 0; i < context->class_inst->type_argc; ++i)
3806 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3810 if (klass->generic_container)
3816 is_vt_inst (MonoGenericInst *inst)
3820 for (i = 0; i < inst->type_argc; ++i) {
3821 MonoType *t = inst->type_argv [i];
3822 if (t->type == MONO_TYPE_VALUETYPE)
3829 method_has_type_vars (MonoMethod *method)
3831 if (has_type_vars (method->klass))
3834 if (method->is_inflated) {
3835 MonoGenericContext *context = mono_method_get_context (method);
3836 if (context->method_inst) {
3839 for (i = 0; i < context->method_inst->type_argc; ++i)
3840 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3847 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3850 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3852 /* This might lead to a huge code blowup so only do it if neccesary */
3853 if (!acfg->aot_opts.full_aot && !force)
3856 add_generic_class_with_depth (acfg, klass, 0, ref);
3860 check_type_depth (MonoType *t, int depth)
3868 case MONO_TYPE_GENERICINST: {
3869 MonoGenericClass *gklass = t->data.generic_class;
3870 MonoGenericInst *ginst = gklass->context.class_inst;
3873 for (i = 0; i < ginst->type_argc; ++i) {
3874 if (check_type_depth (ginst->type_argv [i], depth + 1))
3888 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3891 * add_generic_class:
3893 * Add all methods of a generic class.
3896 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3899 MonoClassField *field;
3901 gboolean use_gsharedvt = FALSE;
3903 if (!acfg->ginst_hash)
3904 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3906 mono_class_init (klass);
3908 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3911 if (has_type_vars (klass))
3914 if (!klass->generic_class && !klass->rank)
3917 if (klass->exception_type)
3920 if (!acfg->ginst_hash)
3921 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3923 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3926 if (check_type_depth (&klass->byval_arg, 0))
3929 if (acfg->aot_opts.log_generics)
3930 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3932 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3935 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3936 * Enable this only for some classes since gsharedvt might not support all methods.
3938 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) &&
3939 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
3940 use_gsharedvt = TRUE;
3943 while ((method = mono_class_get_methods (klass, &iter))) {
3944 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3946 * This is partial sharing, and we can't handle it yet
3951 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3953 add_types_from_method_header (acfg, method);
3957 if (method->is_generic)
3962 * FIXME: Instances which are referenced by these methods are not added,
3963 * for example Array.Resize<int> for List<int>.Add ().
3965 add_extra_method_with_depth (acfg, method, depth + 1);
3969 while ((field = mono_class_get_fields (klass, &iter))) {
3970 if (field->type->type == MONO_TYPE_GENERICINST)
3971 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3974 if (klass->delegate) {
3975 method = mono_get_delegate_invoke (klass);
3977 method = mono_marshal_get_delegate_invoke (method, NULL);
3979 if (acfg->aot_opts.log_generics)
3980 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3982 add_method (acfg, method);
3985 /* Add superclasses */
3987 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3990 * For ICollection<T>, add instances of the helper methods
3991 * in Array, since a T[] could be cast to ICollection<T>.
3993 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3994 (!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"))) {
3995 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3996 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4000 if (!strcmp (klass->name, "IEnumerator`1"))
4001 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4003 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4005 /* Add the T[]/InternalEnumerator class */
4006 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4010 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4011 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4015 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4016 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4020 while ((method = mono_class_get_methods (array_class, &iter))) {
4021 if (strstr (method->name, name_prefix)) {
4022 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4024 add_extra_method_with_depth (acfg, m, depth);
4028 g_free (name_prefix);
4031 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4032 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4033 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4034 MonoClass *icomparable, *gcomparer;
4035 MonoGenericContext ctx;
4036 MonoType *args [16];
4038 memset (&ctx, 0, sizeof (ctx));
4040 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4041 g_assert (icomparable);
4042 args [0] = &tclass->byval_arg;
4043 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4045 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4046 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4047 g_assert (gcomparer);
4048 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4052 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4053 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4054 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4055 MonoClass *iface, *gcomparer;
4056 MonoGenericContext ctx;
4057 MonoType *args [16];
4059 memset (&ctx, 0, sizeof (ctx));
4061 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4063 args [0] = &tclass->byval_arg;
4064 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4066 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4067 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4068 g_assert (gcomparer);
4069 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4075 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4078 MonoGenericContext ctx;
4079 MonoType *args [16];
4081 if (acfg->aot_opts.no_instances)
4084 memset (&ctx, 0, sizeof (ctx));
4086 for (i = 0; i < ninsts; ++i) {
4087 args [0] = insts [i];
4088 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4089 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4094 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4096 MonoMethodHeader *header;
4097 MonoMethodSignature *sig;
4100 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4102 sig = mono_method_signature (method);
4105 for (j = 0; j < sig->param_count; ++j)
4106 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4107 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4110 header = mono_method_get_header (method);
4113 for (j = 0; j < header->num_locals; ++j)
4114 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4115 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4117 mono_loader_clear_error ();
4122 * add_generic_instances:
4124 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4127 add_generic_instances (MonoAotCompile *acfg)
4132 MonoGenericContext *context;
4134 if (acfg->aot_opts.no_instances)
4137 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4138 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4139 method = mono_get_method (acfg->image, token, NULL);
4144 if (method->klass->image != acfg->image)
4147 context = mono_method_get_context (method);
4149 if (context && ((context->class_inst && context->class_inst->is_open)))
4153 * For open methods, create an instantiation which can be passed to the JIT.
4154 * FIXME: Handle class_inst as well.
4156 if (context && context->method_inst && context->method_inst->is_open) {
4157 MonoGenericContext shared_context;
4158 MonoGenericInst *inst;
4159 MonoType **type_argv;
4161 MonoMethod *declaring_method;
4162 gboolean supported = TRUE;
4164 /* Check that the context doesn't contain open constructed types */
4165 if (context->class_inst) {
4166 inst = context->class_inst;
4167 for (i = 0; i < inst->type_argc; ++i) {
4168 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)
4170 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4174 if (context->method_inst) {
4175 inst = context->method_inst;
4176 for (i = 0; i < inst->type_argc; ++i) {
4177 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)
4179 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4187 memset (&shared_context, 0, sizeof (MonoGenericContext));
4189 inst = context->class_inst;
4191 type_argv = g_new0 (MonoType*, inst->type_argc);
4192 for (i = 0; i < inst->type_argc; ++i) {
4193 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)
4194 type_argv [i] = &mono_defaults.object_class->byval_arg;
4196 type_argv [i] = inst->type_argv [i];
4199 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4203 inst = context->method_inst;
4205 type_argv = g_new0 (MonoType*, inst->type_argc);
4206 for (i = 0; i < inst->type_argc; ++i) {
4207 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)
4208 type_argv [i] = &mono_defaults.object_class->byval_arg;
4210 type_argv [i] = inst->type_argv [i];
4213 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4217 if (method->is_generic || method->klass->generic_container)
4218 declaring_method = method;
4220 declaring_method = mono_method_get_declaring_generic_method (method);
4222 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4226 * If the method is fully sharable, it was already added in place of its
4227 * generic definition.
4229 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4233 * FIXME: Partially shared methods are not shared here, so we end up with
4234 * many identical methods.
4236 add_extra_method (acfg, method);
4239 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4242 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4244 klass = mono_class_get (acfg->image, token);
4245 if (!klass || klass->rank) {
4246 mono_loader_clear_error ();
4250 add_generic_class (acfg, klass, FALSE, "typespec");
4253 /* Add types of args/locals */
4254 for (i = 0; i < acfg->methods->len; ++i) {
4255 method = g_ptr_array_index (acfg->methods, i);
4256 add_types_from_method_header (acfg, method);
4259 if (acfg->image == mono_defaults.corlib) {
4261 MonoType *insts [256];
4264 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4265 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4266 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4267 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4268 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4269 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4270 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4271 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4272 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4273 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4274 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4275 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4277 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4278 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4280 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4281 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4283 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4285 /* Add instances of the array generic interfaces for primitive types */
4286 /* This will add instances of the InternalArray_ helper methods in Array too */
4287 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4289 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4290 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4292 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4293 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4295 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4298 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4299 * used for all instances of GetGenericValueImpl by the AOT runtime.
4302 MonoGenericContext ctx;
4303 MonoType *args [16];
4304 MonoMethod *get_method;
4305 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4307 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4310 memset (&ctx, 0, sizeof (ctx));
4311 args [0] = &mono_defaults.object_class->byval_arg;
4312 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4313 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4317 /* Same for CompareExchange<T>/Exchange<T> */
4319 MonoGenericContext ctx;
4320 MonoType *args [16];
4322 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4323 gpointer iter = NULL;
4325 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4326 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4327 memset (&ctx, 0, sizeof (ctx));
4328 args [0] = &mono_defaults.object_class->byval_arg;
4329 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4330 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4335 /* Same for Volatile.Read/Write<T> */
4337 MonoGenericContext ctx;
4338 MonoType *args [16];
4340 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4341 gpointer iter = NULL;
4343 if (volatile_klass) {
4344 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4345 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4346 memset (&ctx, 0, sizeof (ctx));
4347 args [0] = &mono_defaults.object_class->byval_arg;
4348 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4349 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4358 * is_direct_callable:
4360 * Return whenever the method identified by JI is directly callable without
4361 * going through the PLT.
4364 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4366 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4367 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4369 gboolean direct_callable = TRUE;
4371 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4372 direct_callable = FALSE;
4373 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4374 // FIXME: Maybe call the wrapper directly ?
4375 direct_callable = FALSE;
4377 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4378 /* Disable this so all calls go through load_method (), see the
4379 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4380 * mono_debugger_agent_init ().
4382 direct_callable = FALSE;
4385 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4386 /* sgen does some initialization when the allocator method is created */
4387 direct_callable = FALSE;
4389 if (direct_callable)
4392 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4393 if (acfg->aot_opts.direct_pinvoke)
4395 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4396 if (acfg->aot_opts.direct_icalls)
4404 #ifdef MONO_ARCH_AOT_SUPPORTED
4406 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4408 MonoImage *image = method->klass->image;
4409 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4410 MonoTableInfo *tables = image->tables;
4411 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4412 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4413 guint32 im_cols [MONO_IMPLMAP_SIZE];
4416 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4420 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4423 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4425 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4428 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4430 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4437 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4439 if (a->native_offset == b->native_offset)
4440 return a->il_offset - b->il_offset;
4442 return a->native_offset - b->native_offset;
4446 * compute_line_numbers:
4448 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4451 static MonoDebugSourceLocation**
4452 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4454 MonoDebugMethodInfo *minfo;
4455 MonoDebugLineNumberEntry *ln_array;
4456 MonoDebugSourceLocation *loc;
4457 int i, prev_line, prev_il_offset;
4458 int *native_to_il_offset = NULL;
4459 MonoDebugSourceLocation **res;
4462 minfo = mono_debug_lookup_method (method);
4465 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4466 if (debug_info->code_size != code_size)
4469 g_assert (code_size);
4471 /* Compute the native->IL offset mapping */
4473 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4474 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4476 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4478 native_to_il_offset = g_new0 (int, code_size + 1);
4480 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4482 MonoDebugLineNumberEntry *lne = &ln_array [i];
4485 for (j = 0; j < lne->native_offset; ++j)
4486 native_to_il_offset [j] = -1;
4489 if (i < debug_info->num_line_numbers - 1) {
4490 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4492 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4493 native_to_il_offset [j] = lne->il_offset;
4495 for (j = lne->native_offset; j < code_size; ++j)
4496 native_to_il_offset [j] = lne->il_offset;
4501 /* Compute the native->line number mapping */
4502 res = g_new0 (MonoDebugSourceLocation*, code_size);
4503 prev_il_offset = -1;
4506 for (i = 0; i < code_size; ++i) {
4507 int il_offset = native_to_il_offset [i];
4509 if (il_offset == -1 || il_offset == prev_il_offset)
4511 prev_il_offset = il_offset;
4512 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4513 if (!(loc && loc->source_file))
4515 if (loc->row == prev_line) {
4516 mono_debug_symfile_free_location (loc);
4519 prev_line = loc->row;
4520 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4522 /* This will cover the prolog too */
4532 get_file_index (MonoAotCompile *acfg, const char *source_file)
4536 // FIXME: Free these
4537 if (!acfg->dwarf_ln_filenames)
4538 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4539 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4541 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4542 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4543 emit_unset_mode (acfg);
4544 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4556 * emit_and_reloc_code:
4558 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4559 * is true, calls are made through the GOT too. This is used for emitting trampolines
4560 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4561 * since trampolines are needed to make PTL work.
4564 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4566 int i, pindex, start_index, method_index;
4568 MonoJumpInfo *patch_info;
4569 MonoMethodHeader *header;
4570 MonoDebugSourceLocation **locs = NULL;
4572 #ifdef MONO_ARCH_AOT_SUPPORTED
4573 gboolean direct_call, external_call;
4575 const char *direct_call_target = 0;
4576 const char *direct_pinvoke;
4580 header = mono_method_get_header (method);
4582 method_index = get_method_index (acfg, method);
4585 if (acfg->gas_line_numbers && method && debug_info) {
4586 locs = compute_line_numbers (method, code_len, debug_info);
4588 int findex = get_file_index (acfg, "<unknown>");
4589 emit_unset_mode (acfg);
4590 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4594 /* Collect and sort relocations */
4595 patches = g_ptr_array_new ();
4596 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4597 g_ptr_array_add (patches, patch_info);
4598 g_ptr_array_sort (patches, compare_patches);
4601 for (i = 0; i < code_len; i += INST_LEN) {
4603 for (pindex = start_index; pindex < patches->len; ++pindex) {
4604 patch_info = g_ptr_array_index (patches, pindex);
4605 if (patch_info->ip.i >= i)
4609 if (locs && locs [i]) {
4610 MonoDebugSourceLocation *loc = locs [i];
4613 findex = get_file_index (acfg, loc->source_file);
4614 emit_unset_mode (acfg);
4615 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4616 mono_debug_symfile_free_location (loc);
4620 #ifdef MONO_ARCH_AOT_SUPPORTED
4621 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4622 start_index = pindex;
4624 switch (patch_info->type) {
4625 case MONO_PATCH_INFO_NONE:
4627 case MONO_PATCH_INFO_GOT_OFFSET: {
4630 arch_emit_got_offset (acfg, code + i, &code_size);
4631 i += code_size - INST_LEN;
4633 patch_info->type = MONO_PATCH_INFO_NONE;
4636 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4637 int code_size, index;
4638 char *selector = (void*)patch_info->data.target;
4640 if (!acfg->objc_selector_to_index)
4641 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4642 if (!acfg->objc_selectors)
4643 acfg->objc_selectors = g_ptr_array_new ();
4644 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4648 index = acfg->objc_selector_index;
4649 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4650 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4651 acfg->objc_selector_index ++;
4654 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4655 i += code_size - INST_LEN;
4657 patch_info->type = MONO_PATCH_INFO_NONE;
4662 * If this patch is a call, try emitting a direct call instead of
4663 * through a PLT entry. This is possible if the called method is in
4664 * the same assembly and requires no initialization.
4666 direct_call = FALSE;
4667 external_call = FALSE;
4668 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4669 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4670 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4671 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4673 direct_call_target = callee_cfg->asm_symbol;
4674 patch_info->type = MONO_PATCH_INFO_NONE;
4675 acfg->stats.direct_calls ++;
4678 acfg->stats.all_calls ++;
4679 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4680 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4681 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4682 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4684 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4685 if (direct_pinvoke) {
4687 g_assert (strlen (direct_pinvoke) < 1000);
4688 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4691 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4692 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4693 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4694 /* Call to a C function implementing a jit icall */
4696 external_call = TRUE;
4697 g_assert (strlen (sym) < 1000);
4698 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4700 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4701 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4702 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4703 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4704 /* Call to a jit icall without a wrapper */
4706 external_call = TRUE;
4707 g_assert (strlen (sym) < 1000);
4708 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4713 patch_info->type = MONO_PATCH_INFO_NONE;
4714 acfg->stats.direct_calls ++;
4717 if (!got_only && !direct_call) {
4718 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4720 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4722 direct_call_target = plt_entry->symbol;
4724 /* Nullify the patch */
4725 patch_info->type = MONO_PATCH_INFO_NONE;
4726 plt_entry->jit_used = TRUE;
4733 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4734 i += call_size - INST_LEN;
4738 got_slot = get_got_offset (acfg, patch_info);
4740 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4741 i += code_size - INST_LEN;
4747 #endif /* MONO_ARCH_AOT_SUPPORTED */
4750 /* Find next patch */
4752 for (pindex = start_index; pindex < patches->len; ++pindex) {
4753 patch_info = g_ptr_array_index (patches, pindex);
4754 if (patch_info->ip.i >= i)
4758 /* Try to emit multiple bytes at once */
4759 if (pindex < patches->len && patch_info->ip.i > i) {
4762 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4763 if (locs && locs [limit])
4767 emit_code_bytes (acfg, code + i, limit - i);
4768 i = limit - INST_LEN;
4770 emit_code_bytes (acfg, code + i, INST_LEN);
4781 * Return a modified version of S which only includes characters permissible in symbols.
4784 sanitize_symbol (MonoAotCompile *acfg, char *s)
4786 gboolean process = FALSE;
4795 for (i = 0; i < len; ++i)
4796 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4801 gs = g_string_sized_new (len);
4802 for (i = 0; i < len; ++i) {
4804 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4805 g_string_append_c (gs, c);
4806 } else if (c > 0x7f) {
4807 /* multi-byte utf8 */
4808 g_string_append_printf (gs, "_0x%x", c);
4811 while (c >> 6 == 0x2) {
4812 g_string_append_printf (gs, "%x", c);
4816 g_string_append_printf (gs, "_");
4819 g_string_append_c (gs, '_');
4823 res = mono_mempool_strdup (acfg->mempool, gs->str);
4824 g_string_free (gs, TRUE);
4829 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4831 char *name1, *name2, *cached;
4832 int i, j, len, count;
4835 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4836 if (!prefix || !*prefix)
4840 name1 = mono_method_full_name (method, TRUE);
4841 len = strlen (name1);
4842 name2 = malloc (strlen (prefix) + len + 16);
4843 memcpy (name2, prefix, strlen (prefix));
4844 j = strlen (prefix);
4845 for (i = 0; i < len; ++i) {
4846 if (isalnum (name1 [i])) {
4847 name2 [j ++] = name1 [i];
4848 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4850 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4853 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4862 while (g_hash_table_lookup (cache, name2)) {
4863 sprintf (name2 + j, "_%d", count);
4867 cached = g_strdup (name2);
4868 g_hash_table_insert (cache, cached, cached);
4874 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4879 char *debug_sym = NULL;
4880 char *symbol = NULL;
4881 int func_alignment = AOT_FUNC_ALIGNMENT;
4882 MonoMethodHeader *header;
4885 method = cfg->orig_method;
4886 code = cfg->native_code;
4887 header = cfg->header;
4889 method_index = get_method_index (acfg, method);
4890 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4893 /* Make the labels local */
4894 emit_section_change (acfg, ".text", 0);
4895 emit_alignment (acfg, func_alignment);
4897 if (acfg->global_symbols && acfg->need_no_dead_strip)
4898 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4900 emit_label (acfg, cfg->asm_symbol);
4902 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4904 * Write a C style symbol for every method, this has two uses:
4905 * - it works on platforms where the dwarf debugging info is not
4907 * - it allows the setting of breakpoints of aot-ed methods.
4909 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4911 if (acfg->need_no_dead_strip)
4912 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4913 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4914 emit_label (acfg, debug_sym);
4917 export_name = g_hash_table_lookup (acfg->export_names, method);
4919 /* Emit a global symbol for the method */
4920 emit_global_inner (acfg, export_name, TRUE);
4921 emit_label (acfg, export_name);
4924 if (cfg->verbose_level > 0)
4925 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4927 acfg->stats.code_size += cfg->code_len;
4929 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4931 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE, mono_debug_find_method (cfg->jit_info->d.method, mono_domain_get ()));
4935 if (acfg->aot_opts.write_symbols) {
4936 emit_symbol_size (acfg, debug_sym, ".");
4940 emit_label (acfg, symbol);
4947 * Encode PATCH_INFO into its disk representation.
4950 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4954 switch (patch_info->type) {
4955 case MONO_PATCH_INFO_NONE:
4957 case MONO_PATCH_INFO_IMAGE:
4958 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4960 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4961 case MONO_PATCH_INFO_JIT_TLS_ID:
4962 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4963 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4965 case MONO_PATCH_INFO_METHOD_REL:
4966 encode_value ((gint)patch_info->data.offset, p, &p);
4968 case MONO_PATCH_INFO_SWITCH: {
4969 gpointer *table = (gpointer *)patch_info->data.table->table;
4972 encode_value (patch_info->data.table->table_size, p, &p);
4973 for (k = 0; k < patch_info->data.table->table_size; k++)
4974 encode_value ((int)(gssize)table [k], p, &p);
4977 case MONO_PATCH_INFO_METHODCONST:
4978 case MONO_PATCH_INFO_METHOD:
4979 case MONO_PATCH_INFO_METHOD_JUMP:
4980 case MONO_PATCH_INFO_ICALL_ADDR:
4981 case MONO_PATCH_INFO_METHOD_RGCTX:
4982 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4983 encode_method_ref (acfg, patch_info->data.method, p, &p);
4985 case MONO_PATCH_INFO_INTERNAL_METHOD:
4986 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4987 guint32 len = strlen (patch_info->data.name);
4989 encode_value (len, p, &p);
4991 memcpy (p, patch_info->data.name, len);
4996 case MONO_PATCH_INFO_LDSTR: {
4997 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4998 guint32 token = patch_info->data.token->token;
4999 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5000 encode_value (image_index, p, &p);
5001 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5004 case MONO_PATCH_INFO_RVA:
5005 case MONO_PATCH_INFO_DECLSEC:
5006 case MONO_PATCH_INFO_LDTOKEN:
5007 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5008 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5009 encode_value (patch_info->data.token->token, p, &p);
5010 encode_value (patch_info->data.token->has_context, p, &p);
5011 if (patch_info->data.token->has_context)
5012 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5014 case MONO_PATCH_INFO_EXC_NAME: {
5015 MonoClass *ex_class;
5018 mono_class_from_name (mono_defaults.exception_class->image,
5019 "System", patch_info->data.target);
5020 g_assert (ex_class);
5021 encode_klass_ref (acfg, ex_class, p, &p);
5024 case MONO_PATCH_INFO_R4:
5025 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5027 case MONO_PATCH_INFO_R8:
5028 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5029 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5031 case MONO_PATCH_INFO_VTABLE:
5032 case MONO_PATCH_INFO_CLASS:
5033 case MONO_PATCH_INFO_IID:
5034 case MONO_PATCH_INFO_ADJUSTED_IID:
5035 case MONO_PATCH_INFO_CLASS_INIT:
5036 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5038 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5039 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5040 if (patch_info->data.del_tramp->method) {
5041 encode_value (1, p, &p);
5042 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5044 encode_value (0, p, &p);
5047 case MONO_PATCH_INFO_FIELD:
5048 case MONO_PATCH_INFO_SFLDA:
5049 encode_field_info (acfg, patch_info->data.field, p, &p);
5051 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5053 case MONO_PATCH_INFO_RGCTX_FETCH: {
5054 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5059 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5060 * reference the same method, so encode the method only once.
5062 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5064 buf2 = g_malloc (1024);
5067 encode_method_ref (acfg, entry->method, p2, &p2);
5068 g_assert (p2 - buf2 < 1024);
5070 offset = add_to_blob (acfg, buf2, p2 - buf2);
5073 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5078 encode_value (offset, p, &p);
5079 g_assert ((int)entry->info_type < 256);
5080 g_assert (entry->data->type < 256);
5081 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5082 encode_patch (acfg, entry->data, p, &p);
5085 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5086 case MONO_PATCH_INFO_MONITOR_ENTER:
5087 case MONO_PATCH_INFO_MONITOR_EXIT:
5088 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5090 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5091 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5092 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5094 case MONO_PATCH_INFO_SIGNATURE:
5095 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5097 case MONO_PATCH_INFO_TLS_OFFSET:
5098 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5100 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5101 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5102 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5104 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5105 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5108 encode_method_ref (acfg, info->method, p, &p);
5109 encode_value (info->num_entries, p, &p);
5110 for (i = 0; i < info->num_entries; ++i) {
5111 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5113 encode_value (template->info_type, p, &p);
5114 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5115 case MONO_PATCH_INFO_CLASS:
5116 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5118 case MONO_PATCH_INFO_FIELD:
5119 encode_field_info (acfg, template->data, p, &p);
5122 g_assert_not_reached ();
5129 g_warning ("unable to handle jump info %d", patch_info->type);
5130 g_assert_not_reached ();
5137 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5140 guint32 pindex, offset;
5141 MonoJumpInfo *patch_info;
5143 encode_value (n_patches, p, &p);
5145 for (pindex = 0; pindex < patches->len; ++pindex) {
5146 patch_info = g_ptr_array_index (patches, pindex);
5148 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5152 offset = get_got_offset (acfg, patch_info);
5153 encode_value (offset, p, &p);
5160 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5164 int pindex, buf_size, n_patches;
5166 MonoJumpInfo *patch_info;
5167 MonoMethodHeader *header;
5168 guint32 method_index;
5170 guint32 first_got_offset;
5172 method = cfg->orig_method;
5173 header = mono_method_get_header (method);
5175 method_index = get_method_index (acfg, method);
5177 /* Sort relocations */
5178 patches = g_ptr_array_new ();
5179 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5180 g_ptr_array_add (patches, patch_info);
5181 g_ptr_array_sort (patches, compare_patches);
5183 first_got_offset = acfg->cfgs [method_index]->got_offset;
5185 /**********************/
5186 /* Encode method info */
5187 /**********************/
5189 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5190 p = buf = g_malloc (buf_size);
5192 if (mono_class_get_cctor (method->klass))
5193 encode_klass_ref (acfg, method->klass, p, &p);
5195 /* Not needed when loading the method */
5196 encode_value (0, p, &p);
5199 if (cfg->opt & MONO_OPT_SHARED) {
5200 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5201 for (l = cfg->ldstr_list; l; l = l->next) {
5202 encode_value ((long)l->data, p, &p);
5206 /* Used only in shared mode */
5207 g_assert (!cfg->ldstr_list);
5210 for (pindex = 0; pindex < patches->len; ++pindex) {
5211 patch_info = g_ptr_array_index (patches, pindex);
5213 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5214 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5215 patch_info->type = MONO_PATCH_INFO_NONE;
5220 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5221 /* Stored in a GOT slot initialized at module load time */
5222 patch_info->type = MONO_PATCH_INFO_NONE;
5226 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5227 /* Stored in a GOT slot initialized at module load time */
5228 patch_info->type = MONO_PATCH_INFO_NONE;
5232 if (is_plt_patch (patch_info)) {
5233 /* Calls are made through the PLT */
5234 patch_info->type = MONO_PATCH_INFO_NONE;
5242 g_assert (cfg->has_got_slots);
5244 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5246 acfg->stats.info_size += p - buf;
5248 g_assert (p - buf < buf_size);
5250 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5255 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5257 guint32 cache_index;
5260 /* Reuse the unwind module to canonize and store unwind info entries */
5261 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5263 /* Use +/- 1 to distinguish 0s from missing entries */
5264 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5272 * It would be easier to use assembler symbols, but the caller needs an
5275 offset = acfg->unwind_info_offset;
5276 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5277 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5280 encode_value (encoded_len, p, &p);
5282 acfg->unwind_info_offset += encoded_len + (p - buf);
5288 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5291 int i, k, buf_size, method_index;
5292 guint32 debug_info_size;
5294 MonoMethodHeader *header;
5295 guint8 *p, *buf, *debug_info;
5296 MonoJitInfo *jinfo = cfg->jit_info;
5298 gboolean use_unwind_ops = FALSE;
5299 MonoSeqPointInfo *seq_points;
5301 method = cfg->orig_method;
5302 code = cfg->native_code;
5303 header = cfg->header;
5305 method_index = get_method_index (acfg, method);
5307 if (!acfg->aot_opts.nodebug) {
5308 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5311 debug_info_size = 0;
5314 seq_points = cfg->seq_point_info;
5316 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5317 p = buf = g_malloc (buf_size);
5319 use_unwind_ops = cfg->unwind_ops != NULL;
5321 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);
5323 encode_value (flags, p, &p);
5325 if (use_unwind_ops) {
5326 guint32 encoded_len;
5328 guint32 unwind_desc;
5330 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5332 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5333 g_assert (unwind_desc < 0xffff);
5334 if (cfg->has_unwind_info_for_epilog) {
5336 * The lower 16 bits identify the unwind descriptor, the upper 16 bits contain the offset of
5337 * the start of the epilog from the end of the method.
5339 g_assert (cfg->code_size - cfg->epilog_begin < 0xffff);
5340 encode_value (((cfg->code_size - cfg->epilog_begin) << 16) | unwind_desc, p, &p);
5343 encode_value (unwind_desc, p, &p);
5346 encode_value (jinfo->unwind_info, p, &p);
5349 /*Encode the number of holes before the number of clauses to make decoding easier*/
5350 if (jinfo->has_try_block_holes) {
5351 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5352 encode_value (table->num_holes, p, &p);
5355 /* Exception table */
5356 if (cfg->compile_llvm) {
5358 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5359 * since the information is only available to llc. Instead, we let llc save the data
5360 * into the LSDA, and read it from there at runtime.
5362 /* The assembly might be CIL stripped so emit the data ourselves */
5363 if (header->num_clauses)
5364 encode_value (header->num_clauses, p, &p);
5366 for (k = 0; k < header->num_clauses; ++k) {
5367 MonoExceptionClause *clause;
5369 clause = &header->clauses [k];
5371 encode_value (clause->flags, p, &p);
5372 if (clause->data.catch_class) {
5373 encode_value (1, p, &p);
5374 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5376 encode_value (0, p, &p);
5379 /* Emit a list of nesting clauses */
5380 for (i = 0; i < header->num_clauses; ++i) {
5382 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5384 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5386 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5387 encode_value (i, p, &p);
5389 encode_value (-1, p, &p);
5392 if (jinfo->num_clauses)
5393 encode_value (jinfo->num_clauses, p, &p);
5395 for (k = 0; k < jinfo->num_clauses; ++k) {
5396 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5398 encode_value (ei->flags, p, &p);
5399 encode_value (ei->exvar_offset, p, &p);
5401 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5402 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5404 if (ei->data.catch_class) {
5408 buf2 = g_malloc (4096);
5410 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5412 g_assert (len < 4096);
5413 encode_value (len, p, &p);
5414 memcpy (p, buf2, len);
5418 encode_value (0, p, &p);
5422 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5423 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5424 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5428 if (jinfo->has_try_block_holes) {
5429 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5430 for (i = 0; i < table->num_holes; ++i) {
5431 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5432 encode_value (hole->clause, p, &p);
5433 encode_value (hole->length, p, &p);
5434 encode_value (hole->offset, p, &p);
5438 if (jinfo->has_arch_eh_info) {
5439 MonoArchEHJitInfo *eh_info;
5441 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5442 encode_value (eh_info->stack_size, p, &p);
5445 if (jinfo->has_generic_jit_info) {
5446 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5447 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5453 encode_value (gi->nlocs, p, &p);
5455 for (i = 0; i < gi->nlocs; ++i) {
5456 MonoDwarfLocListEntry *entry = &gi->locations [i];
5458 encode_value (entry->is_reg ? 1 : 0, p, &p);
5459 encode_value (entry->reg, p, &p);
5461 encode_value (entry->offset, p, &p);
5463 g_assert (entry->from == 0);
5465 encode_value (entry->from, p, &p);
5466 encode_value (entry->to, p, &p);
5469 if (!cfg->compile_llvm) {
5470 encode_value (gi->has_this ? 1 : 0, p, &p);
5471 encode_value (gi->this_reg, p, &p);
5472 encode_value (gi->this_offset, p, &p);
5477 * Need to encode jinfo->method too, since it is not equal to 'method'
5478 * when using generic sharing.
5480 buf2 = g_malloc (4096);
5482 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5484 g_assert (len < 4096);
5485 encode_value (len, p, &p);
5486 memcpy (p, buf2, len);
5490 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5491 MonoMethodInflated *inflated;
5492 MonoGenericContext *context;
5493 MonoGenericInst *inst;
5495 g_assert (jinfo->d.method->is_inflated);
5496 inflated = (MonoMethodInflated*)jinfo->d.method;
5497 context = &inflated->context;
5499 encode_value (1, p, &p);
5500 if (context->class_inst) {
5501 inst = context->class_inst;
5503 encode_value (inst->type_argc, p, &p);
5504 for (i = 0; i < inst->type_argc; ++i)
5505 encode_value (gsctx->var_is_vt [i], p, &p);
5507 encode_value (0, p, &p);
5509 if (context->method_inst) {
5510 inst = context->method_inst;
5512 encode_value (inst->type_argc, p, &p);
5513 for (i = 0; i < inst->type_argc; ++i)
5514 encode_value (gsctx->mvar_is_vt [i], p, &p);
5516 encode_value (0, p, &p);
5519 encode_value (0, p, &p);
5524 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5526 encode_value (seq_points->len, p, &p);
5527 last_il_offset = last_native_offset = 0;
5528 for (i = 0; i < seq_points->len; ++i) {
5529 SeqPoint *sp = &seq_points->seq_points [i];
5530 il_offset = sp->il_offset;
5531 native_offset = sp->native_offset;
5532 encode_value (il_offset - last_il_offset, p, &p);
5533 encode_value (native_offset - last_native_offset, p, &p);
5534 last_il_offset = il_offset;
5535 last_native_offset = native_offset;
5537 encode_value (sp->flags, p, &p);
5538 encode_value (sp->next_len, p, &p);
5539 for (j = 0; j < sp->next_len; ++j)
5540 encode_value (sp->next [j], p, &p);
5544 g_assert (debug_info_size < buf_size);
5546 encode_value (debug_info_size, p, &p);
5547 if (debug_info_size) {
5548 memcpy (p, debug_info, debug_info_size);
5549 p += debug_info_size;
5550 g_free (debug_info);
5555 encode_value (cfg->gc_map_size, p, &p);
5556 /* The GC map requires 4 bytes of alignment */
5557 while ((gsize)p % 4)
5559 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5560 p += cfg->gc_map_size;
5563 acfg->stats.ex_info_size += p - buf;
5565 g_assert (p - buf < buf_size);
5568 /* The GC Map requires 4 byte alignment */
5569 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5574 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5576 MonoClass *klass = mono_class_get (acfg->image, token);
5578 int i, buf_size, res;
5579 gboolean no_special_static, cant_encode;
5580 gpointer iter = NULL;
5583 mono_loader_clear_error ();
5587 p = buf = g_malloc (buf_size);
5589 /* Mark as unusable */
5590 encode_value (-1, p, &p);
5592 res = add_to_blob (acfg, buf, p - buf);
5598 buf_size = 10240 + (klass->vtable_size * 16);
5599 p = buf = g_malloc (buf_size);
5603 mono_class_init (klass);
5605 mono_class_get_nested_types (klass, &iter);
5606 g_assert (klass->nested_classes_inited);
5608 mono_class_setup_vtable (klass);
5611 * Emit all the information which is required for creating vtables so
5612 * the runtime does not need to create the MonoMethod structures which
5613 * take up a lot of space.
5616 no_special_static = !mono_class_has_special_static_fields (klass);
5618 /* Check whenever we have enough info to encode the vtable */
5619 cant_encode = FALSE;
5620 for (i = 0; i < klass->vtable_size; ++i) {
5621 MonoMethod *cm = klass->vtable [i];
5623 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5627 mono_class_has_finalizer (klass);
5629 if (klass->generic_container || cant_encode) {
5630 encode_value (-1, p, &p);
5632 encode_value (klass->vtable_size, p, &p);
5633 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);
5634 if (klass->has_cctor)
5635 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5636 if (klass->has_finalize)
5637 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5639 encode_value (klass->instance_size, p, &p);
5640 encode_value (mono_class_data_size (klass), p, &p);
5641 encode_value (klass->packing_size, p, &p);
5642 encode_value (klass->min_align, p, &p);
5644 for (i = 0; i < klass->vtable_size; ++i) {
5645 MonoMethod *cm = klass->vtable [i];
5648 encode_method_ref (acfg, cm, p, &p);
5650 encode_value (0, p, &p);
5654 acfg->stats.class_info_size += p - buf;
5656 g_assert (p - buf < buf_size);
5657 res = add_to_blob (acfg, buf, p - buf);
5664 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5666 char *debug_sym = NULL;
5670 case MONO_PATCH_INFO_METHOD:
5671 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5673 case MONO_PATCH_INFO_INTERNAL_METHOD:
5674 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5676 case MONO_PATCH_INFO_CLASS_INIT:
5677 s = mono_type_get_name (&ji->data.klass->byval_arg);
5678 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5681 case MONO_PATCH_INFO_RGCTX_FETCH:
5682 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5684 case MONO_PATCH_INFO_ICALL_ADDR: {
5685 char *s = get_debug_sym (ji->data.method, "", cache);
5687 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5691 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5692 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5694 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5695 debug_sym = g_strdup_printf ("plt__generic_class_init");
5701 return sanitize_symbol (acfg, debug_sym);
5705 * Calls made from AOTed code are routed through a table of jumps similar to the
5706 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5707 * control to the AOT runtime through a trampoline.
5710 emit_plt (MonoAotCompile *acfg)
5716 sprintf (symbol, "plt");
5718 emit_section_change (acfg, ".text", 0);
5719 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5720 emit_label (acfg, symbol);
5721 emit_label (acfg, acfg->plt_symbol);
5723 for (i = 0; i < acfg->plt_offset; ++i) {
5724 char *debug_sym = NULL;
5725 MonoPltEntry *plt_entry = NULL;
5730 * The first plt entry is unused.
5734 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5739 * If the target is directly callable, alias the plt symbol to point to
5741 * FIXME: Use this to simplify emit_and_reloc_code ().
5742 * FIXME: Avoid the got slot.
5743 * FIXME: Add support to the binary writer.
5745 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5746 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5749 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5750 /* LLVM calls the PLT entries using bl, so emit a stub */
5751 emit_set_thumb_mode (acfg);
5752 fprintf (acfg->fp, "\n.thumb_func\n");
5753 emit_label (acfg, plt_entry->llvm_symbol);
5754 fprintf (acfg->fp, "bx pc\n");
5755 fprintf (acfg->fp, "nop\n");
5756 emit_set_arm_mode (acfg);
5757 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5759 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5766 debug_sym = plt_entry->debug_sym;
5768 if (acfg->thumb_mixed && !plt_entry->jit_used)
5769 /* Emit only a thumb version */
5772 if (acfg->llvm && !acfg->thumb_mixed)
5773 emit_label (acfg, plt_entry->llvm_symbol);
5776 if (acfg->need_no_dead_strip) {
5777 emit_unset_mode (acfg);
5778 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5780 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5781 emit_label (acfg, debug_sym);
5784 emit_label (acfg, plt_entry->symbol);
5786 arch_emit_plt_entry (acfg, i);
5789 emit_symbol_size (acfg, debug_sym, ".");
5792 if (acfg->thumb_mixed) {
5793 /* Make sure the ARM symbols don't alias the thumb ones */
5794 emit_zero_bytes (acfg, 16);
5797 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5800 for (i = 0; i < acfg->plt_offset; ++i) {
5801 char *debug_sym = NULL;
5802 MonoPltEntry *plt_entry = NULL;
5808 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5811 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5814 /* Skip plt entries not actually called by LLVM code */
5815 if (!plt_entry->llvm_used)
5818 if (acfg->aot_opts.write_symbols) {
5819 if (plt_entry->debug_sym)
5820 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5824 #if defined(TARGET_MACH)
5825 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5826 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5828 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5829 emit_label (acfg, debug_sym);
5831 fprintf (acfg->fp, "\n.thumb_func\n");
5833 emit_label (acfg, plt_entry->llvm_symbol);
5835 arch_emit_llvm_plt_entry (acfg, i);
5838 emit_symbol_size (acfg, debug_sym, ".");
5844 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5846 sprintf (symbol, "plt_end");
5847 emit_label (acfg, symbol);
5851 * emit_trampoline_full:
5853 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5854 * create_jit_info_for_trampoline ().
5856 static G_GNUC_UNUSED void
5857 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5859 char start_symbol [256];
5860 char end_symbol [256];
5862 guint32 buf_size, info_offset;
5863 MonoJumpInfo *patch_info;
5876 code_size = info->code_size;
5878 unwind_ops = info->unwind_ops;
5880 #ifdef __native_client_codegen__
5881 mono_nacl_fix_patches (code, ji);
5886 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5888 emit_section_change (acfg, ".text", 0);
5889 emit_global (acfg, start_symbol, TRUE);
5890 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5891 emit_label (acfg, start_symbol);
5893 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5894 emit_label (acfg, symbol);
5897 * The code should access everything through the GOT, so we pass
5900 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5902 emit_symbol_size (acfg, start_symbol, ".");
5905 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5906 emit_label (acfg, end_symbol);
5911 /* Sort relocations */
5912 patches = g_ptr_array_new ();
5913 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5914 if (patch_info->type != MONO_PATCH_INFO_NONE)
5915 g_ptr_array_add (patches, patch_info);
5916 g_ptr_array_sort (patches, compare_patches);
5918 buf_size = patches->len * 128 + 128;
5919 buf = g_malloc (buf_size);
5922 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5923 g_assert (p - buf < buf_size);
5925 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5927 info_offset = add_to_blob (acfg, buf, p - buf);
5929 emit_section_change (acfg, RODATA_SECT, 0);
5930 emit_global (acfg, symbol, FALSE);
5931 emit_label (acfg, symbol);
5933 emit_int32 (acfg, info_offset);
5937 guint32 encoded_len;
5941 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5943 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5944 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5947 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5948 emit_int32 (acfg, uw_offset);
5951 /* Emit debug info */
5955 sprintf (symbol, "%s", name);
5956 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5959 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5963 static G_GNUC_UNUSED void
5964 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5966 emit_trampoline_full (acfg, got_offset, info, FALSE);
5970 emit_trampolines (MonoAotCompile *acfg)
5973 char end_symbol [256];
5974 int i, tramp_got_offset;
5975 MonoAotTrampoline ntype;
5976 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5980 if (!acfg->aot_opts.full_aot)
5983 g_assert (acfg->image->assembly);
5985 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5986 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5987 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5988 MonoTrampInfo *info;
5991 * Emit the generic trampolines.
5993 * We could save some code by treating the generic trampolines as a wrapper
5994 * method, but that approach has its own complexities, so we choose the simpler
5997 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5998 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5999 #ifdef DISABLE_REMOTING
6000 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6003 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6004 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6007 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6008 emit_trampoline (acfg, acfg->got_offset, info);
6011 mono_arch_get_nullified_class_init_trampoline (&info);
6012 emit_trampoline (acfg, acfg->got_offset, info);
6013 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6014 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
6015 emit_trampoline (acfg, acfg->got_offset, info);
6016 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6017 emit_trampoline (acfg, acfg->got_offset, info);
6020 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6021 emit_trampoline (acfg, acfg->got_offset, info);
6023 /* Emit the exception related code pieces */
6024 mono_arch_get_restore_context (&info, TRUE);
6025 emit_trampoline (acfg, acfg->got_offset, info);
6026 mono_arch_get_call_filter (&info, TRUE);
6027 emit_trampoline (acfg, acfg->got_offset, info);
6028 mono_arch_get_throw_exception (&info, TRUE);
6029 emit_trampoline (acfg, acfg->got_offset, info);
6030 mono_arch_get_rethrow_exception (&info, TRUE);
6031 emit_trampoline (acfg, acfg->got_offset, info);
6032 mono_arch_get_throw_corlib_exception (&info, TRUE);
6033 emit_trampoline (acfg, acfg->got_offset, info);
6035 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6036 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6038 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6040 /* Create a separate out trampoline for more information in stack traces */
6041 info->name = g_strdup ("gsharedvt_out_trampoline");
6042 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6046 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6048 GSList *l = mono_arch_get_trampolines (TRUE);
6051 MonoTrampInfo *info = l->data;
6053 emit_trampoline (acfg, acfg->got_offset, info);
6059 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6062 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6063 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6064 emit_trampoline (acfg, acfg->got_offset, info);
6066 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6067 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6068 emit_trampoline (acfg, acfg->got_offset, info);
6071 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6072 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6073 emit_trampoline (acfg, acfg->got_offset, info);
6079 /* delegate_invoke_impl trampolines */
6080 l = mono_arch_get_delegate_invoke_impls ();
6082 MonoTrampInfo *info = l->data;
6084 emit_trampoline (acfg, acfg->got_offset, info);
6089 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6091 /* Emit trampolines which are numerous */
6094 * These include the following:
6095 * - specific trampolines
6096 * - static rgctx invoke trampolines
6098 * These trampolines have the same code, they are parameterized by GOT
6100 * They are defined in this file, in the arch_... routines instead of
6101 * in tramp-<ARCH>.c, since it is easier to do it this way.
6105 * When running in aot-only mode, we can't create specific trampolines at
6106 * runtime, so we create a few, and save them in the AOT file.
6107 * Normal trampolines embed their argument as a literal inside the
6108 * trampoline code, we can't do that here, so instead we embed an offset
6109 * which needs to be added to the trampoline address to get the address of
6110 * the GOT slot which contains the argument value.
6111 * The generated trampolines jump to the generic trampolines using another
6112 * GOT slot, which will be setup by the AOT loader to point to the
6113 * generic trampoline code of the given type.
6117 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6121 emit_section_change (acfg, ".text", 0);
6123 tramp_got_offset = acfg->got_offset;
6125 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6127 case MONO_AOT_TRAMP_SPECIFIC:
6128 sprintf (symbol, "specific_trampolines");
6130 case MONO_AOT_TRAMP_STATIC_RGCTX:
6131 sprintf (symbol, "static_rgctx_trampolines");
6133 case MONO_AOT_TRAMP_IMT_THUNK:
6134 sprintf (symbol, "imt_thunks");
6136 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6137 sprintf (symbol, "gsharedvt_arg_trampolines");
6140 g_assert_not_reached ();
6143 sprintf (end_symbol, "%s_e", symbol);
6145 if (acfg->aot_opts.write_symbols)
6146 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6148 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6149 emit_label (acfg, symbol);
6151 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6153 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6157 case MONO_AOT_TRAMP_SPECIFIC:
6158 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6159 tramp_got_offset += 2;
6161 case MONO_AOT_TRAMP_STATIC_RGCTX:
6162 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6163 tramp_got_offset += 2;
6165 case MONO_AOT_TRAMP_IMT_THUNK:
6166 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6167 tramp_got_offset += 1;
6169 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6170 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6171 tramp_got_offset += 2;
6174 g_assert_not_reached ();
6176 #ifdef __native_client_codegen__
6177 /* align to avoid 32-byte boundary crossings */
6178 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6181 if (!acfg->trampoline_size [ntype]) {
6182 g_assert (tramp_size);
6183 acfg->trampoline_size [ntype] = tramp_size;
6187 emit_label (acfg, end_symbol);
6188 emit_int32 (acfg, 0);
6191 arch_emit_specific_trampoline_pages (acfg);
6193 /* Reserve some entries at the end of the GOT for our use */
6194 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6197 acfg->got_offset += acfg->num_trampoline_got_entries;
6201 str_begins_with (const char *str1, const char *str2)
6203 int len = strlen (str2);
6204 return strncmp (str1, str2, len) == 0;
6208 mono_aot_readonly_field_override (MonoClassField *field)
6211 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6212 char *p = rdv->name;
6214 len = strlen (field->parent->name_space);
6215 if (strncmp (p, field->parent->name_space, len))
6220 len = strlen (field->parent->name);
6221 if (strncmp (p, field->parent->name, len))
6226 if (strcmp (p, field->name))
6228 switch (rdv->type) {
6230 return &rdv->value.i1;
6232 return &rdv->value.i2;
6234 return &rdv->value.i4;
6243 add_readonly_value (MonoAotOptions *opts, const char *val)
6248 /* the format of val is:
6249 * namespace.typename.fieldname=type/value
6250 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6252 fval = strrchr (val, '/');
6254 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6257 tval = strrchr (val, '=');
6259 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6262 rdv = g_new0 (ReadOnlyValue, 1);
6263 rdv->name = g_malloc0 (tval - val + 1);
6264 memcpy (rdv->name, val, tval - val);
6267 if (strncmp (tval, "i1", 2) == 0) {
6268 rdv->value.i1 = atoi (fval);
6269 rdv->type = MONO_TYPE_I1;
6270 } else if (strncmp (tval, "i2", 2) == 0) {
6271 rdv->value.i2 = atoi (fval);
6272 rdv->type = MONO_TYPE_I2;
6273 } else if (strncmp (tval, "i4", 2) == 0) {
6274 rdv->value.i4 = atoi (fval);
6275 rdv->type = MONO_TYPE_I4;
6277 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6280 rdv->next = readonly_values;
6281 readonly_values = rdv;
6285 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6287 gchar **args, **ptr;
6289 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6290 for (ptr = args; ptr && *ptr; ptr ++) {
6291 const char *arg = *ptr;
6293 if (str_begins_with (arg, "outfile=")) {
6294 opts->outfile = g_strdup (arg + strlen ("outfile="));
6295 } else if (str_begins_with (arg, "save-temps")) {
6296 opts->save_temps = TRUE;
6297 } else if (str_begins_with (arg, "keep-temps")) {
6298 opts->save_temps = TRUE;
6299 } else if (str_begins_with (arg, "write-symbols")) {
6300 opts->write_symbols = TRUE;
6301 } else if (str_begins_with (arg, "no-write-symbols")) {
6302 opts->write_symbols = FALSE;
6303 } else if (str_begins_with (arg, "metadata-only")) {
6304 opts->metadata_only = TRUE;
6305 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6306 opts->bind_to_runtime_version = TRUE;
6307 } else if (str_begins_with (arg, "full")) {
6308 opts->full_aot = TRUE;
6309 } else if (str_begins_with (arg, "threads=")) {
6310 opts->nthreads = atoi (arg + strlen ("threads="));
6311 } else if (str_begins_with (arg, "static")) {
6312 opts->static_link = TRUE;
6313 opts->no_dlsym = TRUE;
6314 } else if (str_begins_with (arg, "asmonly")) {
6315 opts->asm_only = TRUE;
6316 } else if (str_begins_with (arg, "asmwriter")) {
6317 opts->asm_writer = TRUE;
6318 } else if (str_begins_with (arg, "nodebug")) {
6319 opts->nodebug = TRUE;
6320 } else if (str_begins_with (arg, "dwarfdebug")) {
6321 opts->dwarf_debug = TRUE;
6322 } else if (str_begins_with (arg, "nopagetrampolines")) {
6323 opts->use_trampolines_page = FALSE;
6324 } else if (str_begins_with (arg, "ntrampolines=")) {
6325 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6326 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6327 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6328 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6329 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6330 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6331 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6332 } else if (str_begins_with (arg, "autoreg")) {
6333 opts->autoreg = TRUE;
6334 } else if (str_begins_with (arg, "tool-prefix=")) {
6335 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6336 } else if (str_begins_with (arg, "soft-debug")) {
6337 opts->soft_debug = TRUE;
6338 } else if (str_begins_with (arg, "direct-pinvoke")) {
6339 opts->direct_pinvoke = TRUE;
6340 } else if (str_begins_with (arg, "direct-icalls")) {
6341 opts->direct_icalls = TRUE;
6342 #if defined(TARGET_ARM) || defined(TARGET_ARM64)
6343 } else if (str_begins_with (arg, "iphone-abi")) {
6344 // older full-aot users did depend on this.
6346 } else if (str_begins_with (arg, "no-direct-calls")) {
6347 opts->no_direct_calls = TRUE;
6348 } else if (str_begins_with (arg, "print-skipped")) {
6349 opts->print_skipped_methods = TRUE;
6350 } else if (str_begins_with (arg, "stats")) {
6352 } else if (str_begins_with (arg, "no-instances")) {
6353 opts->no_instances = TRUE;
6354 } else if (str_begins_with (arg, "log-generics")) {
6355 opts->log_generics = TRUE;
6356 } else if (str_begins_with (arg, "log-instances=")) {
6357 opts->log_instances = TRUE;
6358 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6359 } else if (str_begins_with (arg, "log-instances")) {
6360 opts->log_instances = TRUE;
6361 } else if (str_begins_with (arg, "mtriple=")) {
6362 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6363 } else if (str_begins_with (arg, "llvm-path=")) {
6364 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6365 } else if (str_begins_with (arg, "readonly-value=")) {
6366 add_readonly_value (opts, arg + strlen ("readonly-value="));
6367 } else if (str_begins_with (arg, "info")) {
6368 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6370 } else if (str_begins_with (arg, "gc-maps")) {
6371 mini_gc_enable_gc_maps_for_aot ();
6372 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6373 printf ("Supported options for --aot:\n");
6374 printf (" outfile=\n");
6375 printf (" save-temps\n");
6376 printf (" keep-temps\n");
6377 printf (" write-symbols\n");
6378 printf (" metadata-only\n");
6379 printf (" bind-to-runtime-version\n");
6381 printf (" threads=\n");
6382 printf (" static\n");
6383 printf (" asmonly\n");
6384 printf (" asmwriter\n");
6385 printf (" nodebug\n");
6386 printf (" dwarfdebug\n");
6387 printf (" ntrampolines=\n");
6388 printf (" nrgctx-trampolines=\n");
6389 printf (" nimt-trampolines=\n");
6390 printf (" ngsharedvt-trampolines=\n");
6391 printf (" autoreg\n");
6392 printf (" tool-prefix=\n");
6393 printf (" readonly-value=\n");
6394 printf (" soft-debug\n");
6395 printf (" gc-maps\n");
6396 printf (" print-skipped\n");
6397 printf (" no-instances\n");
6398 printf (" stats\n");
6400 printf (" help/?\n");
6403 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6408 if (opts->use_trampolines_page) {
6409 opts->ntrampolines = 0;
6410 opts->nrgctx_trampolines = 0;
6411 opts->nimt_trampolines = 0;
6412 opts->ngsharedvt_arg_trampolines = 0;
6418 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6420 MonoMethod *method = (MonoMethod*)key;
6421 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6422 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6423 MonoAotCompile *acfg = user_data;
6425 new_ji->image = ji->image;
6426 new_ji->token = ji->token;
6427 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6431 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6433 if (klass->type_token)
6435 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6438 return can_encode_class (acfg, klass->element_class);
6443 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6445 if (method->wrapper_type) {
6446 switch (method->wrapper_type) {
6447 case MONO_WRAPPER_NONE:
6448 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6449 case MONO_WRAPPER_XDOMAIN_INVOKE:
6450 case MONO_WRAPPER_STFLD:
6451 case MONO_WRAPPER_LDFLD:
6452 case MONO_WRAPPER_LDFLDA:
6453 case MONO_WRAPPER_LDFLD_REMOTE:
6454 case MONO_WRAPPER_STFLD_REMOTE:
6455 case MONO_WRAPPER_STELEMREF:
6456 case MONO_WRAPPER_ISINST:
6457 case MONO_WRAPPER_PROXY_ISINST:
6458 case MONO_WRAPPER_ALLOC:
6459 case MONO_WRAPPER_REMOTING_INVOKE:
6460 case MONO_WRAPPER_UNKNOWN:
6461 case MONO_WRAPPER_WRITE_BARRIER:
6462 case MONO_WRAPPER_DELEGATE_INVOKE:
6463 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6464 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6465 case MONO_WRAPPER_SYNCHRONIZED:
6467 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6468 case MONO_WRAPPER_CASTCLASS: {
6469 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6478 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6482 if (!method->token) {
6483 /* The method is part of a constructed type like Int[,].Set (). */
6484 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6485 if (method->klass->rank)
6495 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6497 switch (patch_info->type) {
6498 case MONO_PATCH_INFO_METHOD:
6499 case MONO_PATCH_INFO_METHODCONST:
6500 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6501 MonoMethod *method = patch_info->data.method;
6503 return can_encode_method (acfg, method);
6505 case MONO_PATCH_INFO_VTABLE:
6506 case MONO_PATCH_INFO_CLASS_INIT:
6507 case MONO_PATCH_INFO_CLASS:
6508 case MONO_PATCH_INFO_IID:
6509 case MONO_PATCH_INFO_ADJUSTED_IID:
6510 if (!can_encode_class (acfg, patch_info->data.klass)) {
6511 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6515 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6516 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6517 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6522 case MONO_PATCH_INFO_RGCTX_FETCH: {
6523 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6525 if (!can_encode_method (acfg, entry->method))
6527 if (!can_encode_patch (acfg, entry->data))
6541 * AOT compile a given method.
6542 * This function might be called by multiple threads, so it must be thread-safe.
6545 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6548 MonoJumpInfo *patch_info;
6551 MonoMethod *wrapped;
6553 if (acfg->aot_opts.metadata_only)
6556 mono_acfg_lock (acfg);
6557 index = get_method_index (acfg, method);
6558 mono_acfg_unlock (acfg);
6560 /* fixme: maybe we can also precompile wrapper methods */
6561 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6562 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6563 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6564 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6568 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6571 wrapped = mono_marshal_method_from_wrapper (method);
6572 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6573 // FIXME: The wrapper should be generic too, but it is not
6576 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6579 InterlockedIncrement (&acfg->stats.mcount);
6582 if (method->is_generic || method->klass->generic_container) {
6583 InterlockedIncrement (&acfg->stats.genericcount);
6588 //acfg->aot_opts.print_skipped_methods = TRUE;
6591 * Since these methods are the only ones which are compiled with
6592 * AOT support, and they are not used by runtime startup/shutdown code,
6593 * the runtime will not see AOT methods during AOT compilation,so it
6594 * does not need to support them by creating a fake GOT etc.
6596 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
6597 mono_loader_clear_error ();
6599 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6600 if (acfg->aot_opts.print_skipped_methods)
6601 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6602 InterlockedIncrement (&acfg->stats.genericcount);
6605 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6606 if (acfg->aot_opts.print_skipped_methods)
6607 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6608 /* Let the exception happen at runtime */
6612 if (cfg->disable_aot) {
6613 if (acfg->aot_opts.print_skipped_methods)
6614 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6615 InterlockedIncrement (&acfg->stats.ocount);
6616 mono_destroy_compile (cfg);
6619 cfg->method_index = index;
6621 /* Nullify patches which need no aot processing */
6622 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6623 switch (patch_info->type) {
6624 case MONO_PATCH_INFO_LABEL:
6625 case MONO_PATCH_INFO_BB:
6626 patch_info->type = MONO_PATCH_INFO_NONE;
6633 /* Collect method->token associations from the cfg */
6634 mono_acfg_lock (acfg);
6635 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6636 mono_acfg_unlock (acfg);
6639 * Check for absolute addresses.
6642 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6643 switch (patch_info->type) {
6644 case MONO_PATCH_INFO_ABS:
6645 /* unable to handle this */
6654 if (acfg->aot_opts.print_skipped_methods)
6655 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6656 InterlockedIncrement (&acfg->stats.abscount);
6657 mono_destroy_compile (cfg);
6661 /* Lock for the rest of the code */
6662 mono_acfg_lock (acfg);
6665 * Check for methods/klasses we can't encode.
6668 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6669 if (!can_encode_patch (acfg, patch_info))
6674 if (acfg->aot_opts.print_skipped_methods)
6675 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6676 acfg->stats.ocount++;
6677 mono_destroy_compile (cfg);
6678 mono_acfg_unlock (acfg);
6682 if (method->is_inflated && acfg->aot_opts.log_instances) {
6683 if (acfg->instances_logfile)
6684 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6686 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6689 /* Adds generic instances referenced by this method */
6691 * The depth is used to avoid infinite loops when generic virtual recursion is
6694 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6695 if (!acfg->aot_opts.no_instances && depth < 32) {
6696 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6697 switch (patch_info->type) {
6698 case MONO_PATCH_INFO_METHOD: {
6699 MonoMethod *m = patch_info->data.method;
6700 if (m->is_inflated) {
6701 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6702 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6703 !method_has_type_vars (m)) {
6704 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6705 if (acfg->aot_opts.full_aot)
6706 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6708 add_extra_method_with_depth (acfg, m, depth + 1);
6709 add_types_from_method_header (acfg, m);
6712 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6714 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6715 add_extra_method_with_depth (acfg, m, depth + 1);
6718 case MONO_PATCH_INFO_VTABLE: {
6719 MonoClass *klass = patch_info->data.klass;
6721 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6722 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6725 case MONO_PATCH_INFO_SFLDA: {
6726 MonoClass *klass = patch_info->data.field->parent;
6728 /* The .cctor needs to run at runtime. */
6729 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6730 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6739 /* Determine whenever the method has GOT slots */
6740 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6741 switch (patch_info->type) {
6742 case MONO_PATCH_INFO_GOT_OFFSET:
6743 case MONO_PATCH_INFO_NONE:
6744 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6746 case MONO_PATCH_INFO_IMAGE:
6747 /* The assembly is stored in GOT slot 0 */
6748 if (patch_info->data.image != acfg->image)
6749 cfg->has_got_slots = TRUE;
6752 if (!is_plt_patch (patch_info))
6753 cfg->has_got_slots = TRUE;
6758 if (!cfg->has_got_slots)
6759 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6762 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6764 /* Make a copy of the patch info which is in the mempool */
6766 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6768 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6769 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6772 patches = new_patch_info;
6774 patches_end->next = new_patch_info;
6775 patches_end = new_patch_info;
6777 cfg->patch_info = patches;
6779 /* Make a copy of the unwind info */
6781 GSList *l, *unwind_ops;
6785 for (l = cfg->unwind_ops; l; l = l->next) {
6786 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6787 memcpy (op, l->data, sizeof (MonoUnwindOp));
6788 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6790 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6792 /* Make a copy of the argument/local info */
6794 MonoInst **args, **locals;
6795 MonoMethodSignature *sig;
6796 MonoMethodHeader *header;
6799 sig = mono_method_signature (method);
6800 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6801 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6802 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6803 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6807 header = mono_method_get_header (method);
6808 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6809 for (i = 0; i < header->num_locals; ++i) {
6810 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6811 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6813 cfg->locals = locals;
6816 /* Free some fields used by cfg to conserve memory */
6817 mono_mempool_destroy (cfg->mempool);
6818 cfg->mempool = NULL;
6819 g_free (cfg->varinfo);
6820 cfg->varinfo = NULL;
6824 mono_regstate_free (cfg->rs);
6828 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6830 while (index >= acfg->cfgs_size) {
6831 MonoCompile **new_cfgs;
6834 new_size = acfg->cfgs_size * 2;
6835 new_cfgs = g_new0 (MonoCompile*, new_size);
6836 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6837 g_free (acfg->cfgs);
6838 acfg->cfgs = new_cfgs;
6839 acfg->cfgs_size = new_size;
6841 acfg->cfgs [index] = cfg;
6843 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6846 if (cfg->orig_method->wrapper_type)
6847 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6850 mono_acfg_unlock (acfg);
6852 InterlockedIncrement (&acfg->stats.ccount);
6856 compile_thread_main (gpointer *user_data)
6858 MonoDomain *domain = user_data [0];
6859 MonoAotCompile *acfg = user_data [1];
6860 GPtrArray *methods = user_data [2];
6863 mono_thread_attach (domain);
6865 for (i = 0; i < methods->len; ++i)
6866 compile_method (acfg, g_ptr_array_index (methods, i));
6870 load_profile_files (MonoAotCompile *acfg)
6874 int file_index, res, method_index, i;
6877 GList *unordered, *l;
6882 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6884 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6889 infile = fopen (tmp, "r");
6892 printf ("Using profile data file '%s'\n", tmp);
6897 res = fscanf (infile, "%32s\n", ver);
6898 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6899 printf ("Profile file has wrong version or invalid.\n");
6906 MonoMethodDesc *desc;
6909 if (fgets (name, 1023, infile) == NULL)
6912 /* Kill the newline */
6913 if (strlen (name) > 0)
6914 name [strlen (name) - 1] = '\0';
6916 desc = mono_method_desc_new (name, TRUE);
6918 method = mono_method_desc_search_in_image (desc, acfg->image);
6920 if (method && mono_method_get_token (method)) {
6921 token = mono_method_get_token (method);
6922 method_index = mono_metadata_token_index (token) - 1;
6925 for (i = 0; i < acfg->method_order->len; ++i) {
6926 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6932 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6934 //printf ("No method found matching '%s'.\n", name);
6940 /* Add missing methods */
6942 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6944 for (i = 0; i < acfg->method_order->len; ++i) {
6945 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6951 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6953 unordered = g_list_reverse (unordered);
6954 for (l = unordered; l; l = l->next)
6955 g_ptr_array_add (acfg->method_order, l->data);
6958 /* Used by the LLVM backend */
6960 mono_aot_get_got_offset (MonoJumpInfo *ji)
6962 return get_got_offset (llvm_acfg, ji);
6966 mono_aot_get_method_name (MonoCompile *cfg)
6968 if (llvm_acfg->aot_opts.static_link)
6969 /* Include the assembly name too to avoid duplicate symbol errors */
6970 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6972 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6976 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6978 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6979 MonoPltEntry *plt_entry;
6982 ji->data.target = data;
6984 if (!can_encode_patch (llvm_acfg, ji))
6987 plt_entry = get_plt_entry (llvm_acfg, ji);
6988 plt_entry->llvm_used = TRUE;
6990 #if defined(TARGET_MACH)
6991 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6993 return g_strdup_printf (plt_entry->llvm_symbol);
6998 mono_aot_get_method_index (MonoMethod *method)
7000 g_assert (llvm_acfg);
7001 return get_method_index (llvm_acfg, method);
7005 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7009 mono_acfg_lock (llvm_acfg);
7010 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7011 mono_acfg_unlock (llvm_acfg);
7021 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7025 emit_llvm_file (MonoAotCompile *acfg)
7027 char *command, *opts, *tempbc;
7029 MonoJumpInfo *patch_info;
7032 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
7036 /* Compute the final size of the got */
7037 for (i = 0; i < acfg->nmethods; ++i) {
7038 if (acfg->cfgs [i]) {
7039 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
7040 if (patch_info->type != MONO_PATCH_INFO_NONE) {
7041 if (!is_plt_patch (patch_info))
7042 get_got_offset (acfg, patch_info);
7044 get_plt_entry (acfg, patch_info);
7050 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
7052 if (acfg->aot_opts.full_aot) {
7056 * Need to add the got entries used by the trampolines.
7057 * This is only a conservative approximation.
7059 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
7060 /* For the generic + rgctx trampolines */
7061 acfg->final_got_size += 400;
7062 /* For the specific trampolines */
7063 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
7064 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
7069 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7070 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
7074 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7075 * a lot of time, and doesn't seem to save much space.
7076 * The following optimizations cannot be enabled:
7078 * - 'jump-threading' changes our blockaddress references to int constants.
7079 * - 'basiccg' fails because it contains:
7080 * if (CS && !isa<IntrinsicInst>(II)) {
7081 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7082 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7083 * The opt list below was produced by taking the output of:
7084 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7085 * then removing tailcallelim + the global opts.
7086 * strip-dead-prototypes deletes unused intrinsics definitions.
7088 opts = g_strdup ("-instcombine -simplifycfg");
7089 //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 -domtree -verify");
7090 /* The dse pass is disabled because of #13734 and #17616 */
7092 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7093 * // If we have no DataLayout information around, then the size of the store
7094 * // is inferrable from the pointee type. If they are the same type, then
7095 * // we know that the store is safe.
7096 * if (AA.getDataLayout() == 0 &&
7097 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7098 * return OverwriteComplete;
7099 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7101 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7103 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7104 printf ("Executing opt: %s\n", command);
7105 if (system (command) != 0) {
7111 if (!acfg->llc_args)
7112 acfg->llc_args = g_string_new ("");
7114 /* Verbose asm slows down llc greatly */
7115 g_string_append (acfg->llc_args, " -asm-verbose=false");
7117 if (acfg->aot_opts.mtriple)
7118 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7120 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7121 /* ios requires PIC code now */
7122 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7124 if (llvm_acfg->aot_opts.static_link)
7125 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7127 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7129 unlink (acfg->tmpfname);
7131 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->tmpbasename);
7133 printf ("Executing llc: %s\n", command);
7135 if (system (command) != 0) {
7142 emit_code (MonoAotCompile *acfg)
7144 int oindex, i, prev_index;
7147 #if defined(TARGET_POWERPC64)
7148 sprintf (symbol, ".Lgot_addr");
7149 emit_section_change (acfg, ".text", 0);
7150 emit_alignment (acfg, 8);
7151 emit_label (acfg, symbol);
7152 emit_pointer (acfg, acfg->got_symbol);
7156 * This global symbol is used to compute the address of each method using the
7157 * code_offsets array. It is also used to compute the memory ranges occupied by
7158 * AOT code, so it must be equal to the address of the first emitted method.
7160 emit_section_change (acfg, ".text", 0);
7161 emit_alignment (acfg, 8);
7163 for (i = 0; i < acfg->nmethods; ++i) {
7164 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7165 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7170 if (!acfg->methods_symbol) {
7171 sprintf (symbol, "methods");
7172 emit_label (acfg, symbol);
7173 acfg->methods_symbol = g_strdup (symbol);
7177 * Emit some padding so the local symbol for the first method doesn't have the
7178 * same address as 'methods'.
7180 #if defined(__default_codegen__)
7181 emit_zero_bytes (acfg, 16);
7182 #elif defined(__native_client_codegen__)
7184 const int kPaddingSize = 16;
7185 guint8 pad_buffer[kPaddingSize];
7186 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7187 emit_bytes (acfg, pad_buffer, kPaddingSize);
7191 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7195 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7197 cfg = acfg->cfgs [i];
7202 method = cfg->orig_method;
7204 /* Emit unbox trampoline */
7205 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7206 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7208 emit_section_change (acfg, ".text", 0);
7209 #ifdef __native_client_codegen__
7210 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7213 if (acfg->thumb_mixed && cfg->compile_llvm) {
7214 emit_set_thumb_mode (acfg);
7215 fprintf (acfg->fp, "\n.thumb_func\n");
7218 emit_label (acfg, symbol);
7220 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7222 if (acfg->thumb_mixed && cfg->compile_llvm) {
7223 emit_set_arm_mode (acfg);
7227 if (cfg->compile_llvm)
7228 acfg->stats.llvm_count ++;
7230 emit_method_code (acfg, cfg);
7233 sprintf (symbol, "methods_end");
7234 emit_section_change (acfg, ".text", 0);
7235 emit_alignment (acfg, 8);
7236 emit_label (acfg, symbol);
7237 /* To distinguish it from the next symbol */
7238 emit_int32 (acfg, 0);
7241 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7242 * from optimizing them away, since it doesn't see that code_offsets references them.
7243 * JITted methods don't need this since they are referenced using assembler local
7245 * FIXME: This is why write-symbols doesn't work on OSX ?
7247 if (acfg->llvm && acfg->need_no_dead_strip) {
7248 fprintf (acfg->fp, "\n");
7249 for (i = 0; i < acfg->nmethods; ++i) {
7250 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7251 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7255 if (acfg->direct_method_addresses) {
7256 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7259 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7260 * This is PIE code, and the linker can update it if needed.
7262 sprintf (symbol, "method_addresses");
7263 emit_section_change (acfg, ".text", 1);
7264 emit_alignment (acfg, 8);
7265 emit_label (acfg, symbol);
7266 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7267 emit_unset_mode (acfg);
7268 if (acfg->need_no_dead_strip)
7269 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7271 for (i = 0; i < acfg->nmethods; ++i) {
7272 #ifdef MONO_ARCH_AOT_SUPPORTED
7276 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7278 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7282 sprintf (symbol, "method_addresses_end");
7283 emit_label (acfg, symbol);
7286 sprintf (symbol, "code_offsets");
7287 emit_section_change (acfg, RODATA_SECT, 1);
7288 emit_alignment (acfg, 8);
7289 emit_label (acfg, symbol);
7290 emit_int32 (acfg, 0);
7292 sprintf (symbol, "code_offsets");
7293 emit_section_change (acfg, RODATA_SECT, 1);
7294 emit_alignment (acfg, 8);
7295 emit_label (acfg, symbol);
7297 acfg->stats.offsets_size += acfg->nmethods * 4;
7299 for (i = 0; i < acfg->nmethods; ++i) {
7300 if (acfg->cfgs [i]) {
7301 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7303 emit_int32 (acfg, 0xffffffff);
7309 /* Emit a sorted table mapping methods to their unbox trampolines */
7310 sprintf (symbol, "unbox_trampolines");
7311 if (acfg->direct_method_addresses)
7312 emit_section_change (acfg, ".text", 0);
7314 emit_section_change (acfg, RODATA_SECT, 0);
7315 emit_alignment (acfg, 8);
7316 emit_label (acfg, symbol);
7319 for (i = 0; i < acfg->nmethods; ++i) {
7324 cfg = acfg->cfgs [i];
7328 method = cfg->orig_method;
7330 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7331 #ifdef MONO_ARCH_AOT_SUPPORTED
7335 index = get_method_index (acfg, method);
7336 sprintf (symbol, "ut_%d", index);
7338 emit_int32 (acfg, index);
7339 if (acfg->direct_method_addresses) {
7340 #ifdef MONO_ARCH_AOT_SUPPORTED
7341 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7344 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7346 /* Make sure the table is sorted by index */
7347 g_assert (index > prev_index);
7351 sprintf (symbol, "unbox_trampolines_end");
7352 emit_label (acfg, symbol);
7353 emit_int32 (acfg, 0);
7357 emit_info (MonoAotCompile *acfg)
7363 offsets = g_new0 (gint32, acfg->nmethods);
7365 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7366 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7368 if (acfg->cfgs [i]) {
7369 emit_method_info (acfg, acfg->cfgs [i]);
7370 offsets [i] = acfg->cfgs [i]->method_info_offset;
7376 sprintf (symbol, "method_info_offsets");
7377 emit_section_change (acfg, RODATA_SECT, 1);
7378 emit_alignment (acfg, 8);
7379 emit_label (acfg, symbol);
7381 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7386 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7388 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7389 #define mix(a,b,c) { \
7390 a -= c; a ^= rot(c, 4); c += b; \
7391 b -= a; b ^= rot(a, 6); a += c; \
7392 c -= b; c ^= rot(b, 8); b += a; \
7393 a -= c; a ^= rot(c,16); c += b; \
7394 b -= a; b ^= rot(a,19); a += c; \
7395 c -= b; c ^= rot(b, 4); b += a; \
7397 #define final(a,b,c) { \
7398 c ^= b; c -= rot(b,14); \
7399 a ^= c; a -= rot(c,11); \
7400 b ^= a; b -= rot(a,25); \
7401 c ^= b; c -= rot(b,16); \
7402 a ^= c; a -= rot(c,4); \
7403 b ^= a; b -= rot(a,14); \
7404 c ^= b; c -= rot(b,24); \
7408 mono_aot_type_hash (MonoType *t1)
7410 guint hash = t1->type;
7412 hash |= t1->byref << 6; /* do not collide with t1->type values */
7414 case MONO_TYPE_VALUETYPE:
7415 case MONO_TYPE_CLASS:
7416 case MONO_TYPE_SZARRAY:
7417 /* check if the distribution is good enough */
7418 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7420 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7421 case MONO_TYPE_ARRAY:
7422 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7423 case MONO_TYPE_GENERICINST:
7424 return ((hash << 5) - hash) ^ 0;
7431 * mono_aot_method_hash:
7433 * Return a hash code for methods which only depends on metadata.
7436 mono_aot_method_hash (MonoMethod *method)
7438 MonoMethodSignature *sig;
7442 guint32 *hashes_start, *hashes;
7444 MonoGenericInst *ginst = NULL;
7446 /* Similar to the hash in mono_method_get_imt_slot () */
7448 sig = mono_method_signature (method);
7450 if (method->is_inflated)
7451 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7453 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7454 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7455 hashes = hashes_start;
7457 /* Some wrappers are assigned to random classes */
7458 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7459 klass = method->klass;
7461 klass = mono_defaults.object_class;
7463 if (!method->wrapper_type) {
7464 char *full_name = mono_type_full_name (&klass->byval_arg);
7466 hashes [0] = mono_metadata_str_hash (full_name);
7470 hashes [0] = mono_metadata_str_hash (klass->name);
7471 hashes [1] = mono_metadata_str_hash (klass->name_space);
7473 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7474 /* The method name includes a stringified pointer */
7477 hashes [2] = mono_metadata_str_hash (method->name);
7478 hashes [3] = method->wrapper_type;
7479 hashes [4] = mono_aot_type_hash (sig->ret);
7481 for (i = 0; i < sig->param_count; i++) {
7482 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7485 for (i = 0; i < ginst->type_argc; ++i)
7486 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7488 g_assert (hindex == hashes_count);
7490 /* Setup internal state */
7491 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7493 /* Handle most of the hashes */
7494 while (hashes_count > 3) {
7503 /* Handle the last 3 hashes (all the case statements fall through) */
7504 switch (hashes_count) {
7505 case 3 : c += hashes [2];
7506 case 2 : b += hashes [1];
7507 case 1 : a += hashes [0];
7509 case 0: /* nothing left to add */
7513 free (hashes_start);
7522 * mono_aot_get_array_helper_from_wrapper;
7524 * Get the helper method in Array called by an array wrapper method.
7527 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7531 MonoGenericContext ctx;
7532 MonoType *args [16];
7533 char *mname, *iname, *s, *s2, *helper_name = NULL;
7535 prefix = "System.Collections.Generic";
7536 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7537 s2 = strstr (s, "`1.");
7543 //printf ("X: %s %s\n", iname, mname);
7545 if (!strcmp (iname, "IList"))
7546 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7548 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7549 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7551 g_free (helper_name);
7554 if (m->is_generic) {
7555 memset (&ctx, 0, sizeof (ctx));
7556 args [0] = &method->klass->element_class->byval_arg;
7557 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7558 m = mono_class_inflate_generic_method (m, &ctx);
7564 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7566 typedef struct HashEntry {
7567 guint32 key, value, index;
7568 struct HashEntry *next;
7572 * emit_extra_methods:
7574 * Emit methods which are not in the METHOD table, like wrappers.
7577 emit_extra_methods (MonoAotCompile *acfg)
7579 int i, table_size, buf_size;
7582 guint32 *info_offsets;
7585 HashEntry *entry, *new_entry;
7586 int nmethods, max_chain_length;
7589 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7591 /* Emit method info */
7593 for (i = 0; i < acfg->extra_methods->len; ++i) {
7594 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7595 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7601 p = buf = g_malloc (buf_size);
7605 method = cfg->method_to_register;
7607 encode_method_ref (acfg, method, p, &p);
7609 g_assert ((p - buf) < buf_size);
7611 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7616 * Construct a chained hash table for mapping indexes in extra_method_info to
7619 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7620 table = g_ptr_array_sized_new (table_size);
7621 for (i = 0; i < table_size; ++i)
7622 g_ptr_array_add (table, NULL);
7623 chain_lengths = g_new0 (int, table_size);
7624 max_chain_length = 0;
7625 for (i = 0; i < acfg->extra_methods->len; ++i) {
7626 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7627 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7633 key = info_offsets [i];
7634 value = get_method_index (acfg, method);
7636 hash = mono_aot_method_hash (method) % table_size;
7637 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7639 chain_lengths [hash] ++;
7640 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7642 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7643 new_entry->key = key;
7644 new_entry->value = value;
7646 entry = g_ptr_array_index (table, hash);
7647 if (entry == NULL) {
7648 new_entry->index = hash;
7649 g_ptr_array_index (table, hash) = new_entry;
7652 entry = entry->next;
7654 entry->next = new_entry;
7655 new_entry->index = table->len;
7656 g_ptr_array_add (table, new_entry);
7660 //printf ("MAX: %d\n", max_chain_length);
7662 /* Emit the table */
7663 sprintf (symbol, "extra_method_table");
7664 emit_section_change (acfg, RODATA_SECT, 0);
7665 emit_alignment (acfg, 8);
7666 emit_label (acfg, symbol);
7668 emit_int32 (acfg, table_size);
7669 for (i = 0; i < table->len; ++i) {
7670 HashEntry *entry = g_ptr_array_index (table, i);
7672 if (entry == NULL) {
7673 emit_int32 (acfg, 0);
7674 emit_int32 (acfg, 0);
7675 emit_int32 (acfg, 0);
7677 //g_assert (entry->key > 0);
7678 emit_int32 (acfg, entry->key);
7679 emit_int32 (acfg, entry->value);
7681 emit_int32 (acfg, entry->next->index);
7683 emit_int32 (acfg, 0);
7688 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7689 * This is used by mono_aot_find_jit_info ().
7691 sprintf (symbol, "extra_method_info_offsets");
7692 emit_section_change (acfg, RODATA_SECT, 0);
7693 emit_alignment (acfg, 8);
7694 emit_label (acfg, symbol);
7696 emit_int32 (acfg, acfg->extra_methods->len);
7697 for (i = 0; i < acfg->extra_methods->len; ++i) {
7698 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7700 emit_int32 (acfg, get_method_index (acfg, method));
7701 emit_int32 (acfg, info_offsets [i]);
7706 emit_exception_info (MonoAotCompile *acfg)
7712 offsets = g_new0 (gint32, acfg->nmethods);
7713 for (i = 0; i < acfg->nmethods; ++i) {
7714 if (acfg->cfgs [i]) {
7715 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7716 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7722 sprintf (symbol, "ex_info_offsets");
7723 emit_section_change (acfg, RODATA_SECT, 1);
7724 emit_alignment (acfg, 8);
7725 emit_label (acfg, symbol);
7727 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7732 emit_unwind_info (MonoAotCompile *acfg)
7738 * The unwind info contains a lot of duplicates so we emit each unique
7739 * entry once, and only store the offset from the start of the table in the
7743 sprintf (symbol, "unwind_info");
7744 emit_section_change (acfg, RODATA_SECT, 1);
7745 emit_alignment (acfg, 8);
7746 emit_label (acfg, symbol);
7748 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7749 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7750 guint8 *unwind_info;
7751 guint32 unwind_info_len;
7755 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7758 encode_value (unwind_info_len, p, &p);
7759 emit_bytes (acfg, buf, p - buf);
7760 emit_bytes (acfg, unwind_info, unwind_info_len);
7762 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7767 emit_class_info (MonoAotCompile *acfg)
7773 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7774 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7775 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7777 sprintf (symbol, "class_info_offsets");
7778 emit_section_change (acfg, RODATA_SECT, 1);
7779 emit_alignment (acfg, 8);
7780 emit_label (acfg, symbol);
7782 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7786 typedef struct ClassNameTableEntry {
7787 guint32 token, index;
7788 struct ClassNameTableEntry *next;
7789 } ClassNameTableEntry;
7792 emit_class_name_table (MonoAotCompile *acfg)
7795 guint32 token, hash;
7800 ClassNameTableEntry *entry, *new_entry;
7803 * Construct a chained hash table for mapping class names to typedef tokens.
7805 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7806 table = g_ptr_array_sized_new (table_size);
7807 for (i = 0; i < table_size; ++i)
7808 g_ptr_array_add (table, NULL);
7809 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7810 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7811 klass = mono_class_get (acfg->image, token);
7813 mono_loader_clear_error ();
7816 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7817 hash = mono_metadata_str_hash (full_name) % table_size;
7820 /* FIXME: Allocate from the mempool */
7821 new_entry = g_new0 (ClassNameTableEntry, 1);
7822 new_entry->token = token;
7824 entry = g_ptr_array_index (table, hash);
7825 if (entry == NULL) {
7826 new_entry->index = hash;
7827 g_ptr_array_index (table, hash) = new_entry;
7830 entry = entry->next;
7832 entry->next = new_entry;
7833 new_entry->index = table->len;
7834 g_ptr_array_add (table, new_entry);
7838 /* Emit the table */
7839 sprintf (symbol, "class_name_table");
7840 emit_section_change (acfg, RODATA_SECT, 0);
7841 emit_alignment (acfg, 8);
7842 emit_label (acfg, symbol);
7844 /* FIXME: Optimize memory usage */
7845 g_assert (table_size < 65000);
7846 emit_int16 (acfg, table_size);
7847 g_assert (table->len < 65000);
7848 for (i = 0; i < table->len; ++i) {
7849 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7851 if (entry == NULL) {
7852 emit_int16 (acfg, 0);
7853 emit_int16 (acfg, 0);
7855 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7857 emit_int16 (acfg, entry->next->index);
7859 emit_int16 (acfg, 0);
7865 emit_image_table (MonoAotCompile *acfg)
7871 * The image table is small but referenced in a lot of places.
7872 * So we emit it at once, and reference its elements by an index.
7875 sprintf (symbol, "image_table");
7876 emit_section_change (acfg, RODATA_SECT, 1);
7877 emit_alignment (acfg, 8);
7878 emit_label (acfg, symbol);
7880 emit_int32 (acfg, acfg->image_table->len);
7881 for (i = 0; i < acfg->image_table->len; i++) {
7882 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7883 MonoAssemblyName *aname = &image->assembly->aname;
7885 /* FIXME: Support multi-module assemblies */
7886 g_assert (image->assembly->image == image);
7888 emit_string (acfg, image->assembly_name);
7889 emit_string (acfg, image->guid);
7890 emit_string (acfg, aname->culture ? aname->culture : "");
7891 emit_string (acfg, (const char*)aname->public_key_token);
7893 emit_alignment (acfg, 8);
7894 emit_int32 (acfg, aname->flags);
7895 emit_int32 (acfg, aname->major);
7896 emit_int32 (acfg, aname->minor);
7897 emit_int32 (acfg, aname->build);
7898 emit_int32 (acfg, aname->revision);
7903 emit_got_info (MonoAotCompile *acfg)
7906 int i, first_plt_got_patch, buf_size;
7908 guint32 *got_info_offsets;
7910 /* Add the patches needed by the PLT to the GOT */
7911 acfg->plt_got_offset_base = acfg->got_offset;
7912 first_plt_got_patch = acfg->got_patches->len;
7913 for (i = 1; i < acfg->plt_offset; ++i) {
7914 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7916 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7918 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7921 acfg->got_offset += acfg->plt_offset;
7925 * - optimize offsets table.
7926 * - reduce number of exported symbols.
7927 * - emit info for a klass only once.
7928 * - determine when a method uses a GOT slot which is guaranteed to be already
7930 * - clean up and document the code.
7931 * - use String.Empty in class libs.
7934 /* Encode info required to decode shared GOT entries */
7935 buf_size = acfg->got_patches->len * 128;
7936 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7937 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7938 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7940 if (acfg->plt_offset)
7941 acfg->plt_got_info_offsets [0] = 0;
7942 for (i = 0; i < acfg->got_patches->len; ++i) {
7943 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7948 encode_value (ji->type, p, &p);
7950 encode_patch (acfg, ji, p, &p);
7951 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7952 g_assert (p - buf <= buf_size);
7953 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7955 if (i >= first_plt_got_patch)
7956 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7957 acfg->stats.got_info_size += p - buf;
7960 /* Emit got_info_offsets table */
7961 sprintf (symbol, "got_info_offsets");
7962 emit_section_change (acfg, RODATA_SECT, 1);
7963 emit_alignment (acfg, 8);
7964 emit_label (acfg, symbol);
7966 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7967 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7971 emit_got (MonoAotCompile *acfg)
7976 /* Don't make GOT global so accesses to it don't need relocations */
7977 sprintf (symbol, "%s", acfg->got_symbol);
7978 emit_section_change (acfg, ".bss", 0);
7979 emit_alignment (acfg, 8);
7980 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7981 emit_label (acfg, symbol);
7982 if (acfg->got_offset > 0)
7983 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7985 sprintf (symbol, "got_end");
7986 emit_label (acfg, symbol);
7990 typedef struct GlobalsTableEntry {
7991 guint32 value, index;
7992 struct GlobalsTableEntry *next;
7993 } GlobalsTableEntry;
7996 emit_globals (MonoAotCompile *acfg)
8002 GlobalsTableEntry *entry, *new_entry;
8004 if (!acfg->aot_opts.static_link)
8008 * When static linking, we emit a table containing our globals.
8012 * Construct a chained hash table for mapping global names to their index in
8013 * the globals table.
8015 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8016 table = g_ptr_array_sized_new (table_size);
8017 for (i = 0; i < table_size; ++i)
8018 g_ptr_array_add (table, NULL);
8019 for (i = 0; i < acfg->globals->len; ++i) {
8020 char *name = g_ptr_array_index (acfg->globals, i);
8022 hash = mono_metadata_str_hash (name) % table_size;
8024 /* FIXME: Allocate from the mempool */
8025 new_entry = g_new0 (GlobalsTableEntry, 1);
8026 new_entry->value = i;
8028 entry = g_ptr_array_index (table, hash);
8029 if (entry == NULL) {
8030 new_entry->index = hash;
8031 g_ptr_array_index (table, hash) = new_entry;
8034 entry = entry->next;
8036 entry->next = new_entry;
8037 new_entry->index = table->len;
8038 g_ptr_array_add (table, new_entry);
8042 /* Emit the table */
8043 sprintf (symbol, ".Lglobals_hash");
8044 emit_section_change (acfg, RODATA_SECT, 0);
8045 emit_alignment (acfg, 8);
8046 emit_label (acfg, symbol);
8048 /* FIXME: Optimize memory usage */
8049 g_assert (table_size < 65000);
8050 emit_int16 (acfg, table_size);
8051 for (i = 0; i < table->len; ++i) {
8052 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8054 if (entry == NULL) {
8055 emit_int16 (acfg, 0);
8056 emit_int16 (acfg, 0);
8058 emit_int16 (acfg, entry->value + 1);
8060 emit_int16 (acfg, entry->next->index);
8062 emit_int16 (acfg, 0);
8066 /* Emit the names */
8067 for (i = 0; i < acfg->globals->len; ++i) {
8068 char *name = g_ptr_array_index (acfg->globals, i);
8070 sprintf (symbol, "name_%d", i);
8071 emit_section_change (acfg, RODATA_SECT, 1);
8073 emit_alignment (acfg, 4);
8075 emit_label (acfg, symbol);
8076 emit_string (acfg, name);
8079 /* Emit the globals table */
8080 sprintf (symbol, "globals");
8081 emit_section_change (acfg, ".data", 0);
8082 /* This is not a global, since it is accessed by the init function */
8083 emit_alignment (acfg, 8);
8084 emit_label (acfg, symbol);
8086 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8087 emit_pointer (acfg, symbol);
8089 for (i = 0; i < acfg->globals->len; ++i) {
8090 char *name = g_ptr_array_index (acfg->globals, i);
8092 sprintf (symbol, "name_%d", i);
8093 emit_pointer (acfg, symbol);
8095 sprintf (symbol, "%s", name);
8096 emit_pointer (acfg, symbol);
8098 /* Null terminate the table */
8099 emit_int32 (acfg, 0);
8100 emit_int32 (acfg, 0);
8104 emit_autoreg (MonoAotCompile *acfg)
8109 * Emit a function into the .ctor section which will be called by the ELF
8110 * loader to register this module with the runtime.
8112 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8115 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8117 arch_emit_autoreg (acfg, symbol);
8123 emit_mem_end (MonoAotCompile *acfg)
8127 sprintf (symbol, "mem_end");
8128 emit_section_change (acfg, ".text", 1);
8129 emit_alignment (acfg, 8);
8130 emit_label (acfg, symbol);
8134 * Emit a structure containing all the information not stored elsewhere.
8137 emit_file_info (MonoAotCompile *acfg)
8142 const char *gc_name;
8145 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8147 if (acfg->aot_opts.bind_to_runtime_version) {
8148 build_info = mono_get_runtime_build_info ();
8149 emit_string_symbol (acfg, "runtime_version", build_info);
8150 g_free (build_info);
8152 emit_string_symbol (acfg, "runtime_version", "");
8155 /* Emit a string holding the assembly name */
8156 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8159 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8162 gc_name = mono_gc_get_gc_name ();
8163 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8165 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8166 emit_section_change (acfg, ".data", 0);
8167 emit_alignment (acfg, 8);
8168 emit_label (acfg, symbol);
8169 if (!acfg->aot_opts.static_link)
8170 emit_global (acfg, symbol, FALSE);
8172 /* The data emitted here must match MonoAotFileInfo. */
8174 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8175 emit_int32 (acfg, 0);
8178 * We emit pointers to our data structures instead of emitting global symbols which
8179 * point to them, to reduce the number of globals, and because using globals leads to
8180 * various problems (i.e. arm/thumb).
8182 emit_pointer (acfg, acfg->got_symbol);
8183 emit_pointer (acfg, acfg->methods_symbol);
8186 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8188 emit_pointer (acfg, "mono_eh_frame");
8190 emit_pointer (acfg, NULL);
8192 emit_pointer (acfg, "blob");
8193 emit_pointer (acfg, "class_name_table");
8194 emit_pointer (acfg, "class_info_offsets");
8195 emit_pointer (acfg, "method_info_offsets");
8196 emit_pointer (acfg, "ex_info_offsets");
8197 emit_pointer (acfg, "code_offsets");
8198 if (acfg->direct_method_addresses)
8199 emit_pointer (acfg, "method_addresses");
8201 emit_pointer (acfg, NULL);
8202 emit_pointer (acfg, "extra_method_info_offsets");
8203 emit_pointer (acfg, "extra_method_table");
8204 emit_pointer (acfg, "got_info_offsets");
8205 emit_pointer (acfg, "methods_end");
8206 emit_pointer (acfg, "unwind_info");
8207 emit_pointer (acfg, "mem_end");
8208 emit_pointer (acfg, "image_table");
8209 emit_pointer (acfg, "plt");
8210 emit_pointer (acfg, "plt_end");
8211 emit_pointer (acfg, "assembly_guid");
8212 emit_pointer (acfg, "runtime_version");
8213 if (acfg->num_trampoline_got_entries) {
8214 emit_pointer (acfg, "specific_trampolines");
8215 emit_pointer (acfg, "static_rgctx_trampolines");
8216 emit_pointer (acfg, "imt_thunks");
8217 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8219 emit_pointer (acfg, NULL);
8220 emit_pointer (acfg, NULL);
8221 emit_pointer (acfg, NULL);
8222 emit_pointer (acfg, NULL);
8224 if (acfg->thumb_mixed) {
8225 emit_pointer (acfg, "thumb_end");
8227 emit_pointer (acfg, NULL);
8229 if (acfg->aot_opts.static_link) {
8230 emit_pointer (acfg, "globals");
8232 emit_pointer (acfg, NULL);
8234 emit_pointer (acfg, "assembly_name");
8235 emit_pointer (acfg, "unbox_trampolines");
8236 emit_pointer (acfg, "unbox_trampolines_end");
8238 emit_int32 (acfg, acfg->plt_got_offset_base);
8239 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8240 emit_int32 (acfg, acfg->plt_offset);
8241 emit_int32 (acfg, acfg->nmethods);
8242 emit_int32 (acfg, acfg->flags);
8243 emit_int32 (acfg, acfg->opts);
8244 emit_int32 (acfg, acfg->simd_opts);
8245 emit_int32 (acfg, gc_name_offset);
8247 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8248 emit_int32 (acfg, acfg->num_trampolines [i]);
8249 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8250 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8251 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8252 emit_int32 (acfg, acfg->trampoline_size [i]);
8253 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8255 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8260 memset (&t, 0, sizeof (MonoType));
8261 t.type = MONO_TYPE_R8;
8262 mono_type_size (&t, &align);
8263 emit_int32 (acfg, align);
8265 memset (&t, 0, sizeof (MonoType));
8266 t.type = MONO_TYPE_I8;
8267 mono_type_size (&t, &align);
8269 emit_int32 (acfg, align);
8272 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8273 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8275 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8276 emit_int32 (acfg, acfg->tramp_page_size);
8277 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8278 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8280 if (acfg->aot_opts.static_link) {
8284 * Emit a global symbol which can be passed by an embedding app to
8285 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8288 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8290 /* Get rid of characters which cannot occur in symbols */
8292 for (p = symbol; *p; ++p) {
8293 if (!(isalnum (*p) || *p == '_'))
8296 acfg->static_linking_symbol = g_strdup (symbol);
8297 emit_global_inner (acfg, symbol, FALSE);
8298 emit_alignment (acfg, sizeof (gpointer));
8299 emit_label (acfg, symbol);
8300 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8305 emit_blob (MonoAotCompile *acfg)
8309 sprintf (symbol, "blob");
8310 emit_section_change (acfg, RODATA_SECT, 1);
8311 emit_alignment (acfg, 8);
8312 emit_label (acfg, symbol);
8314 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8318 emit_objc_selectors (MonoAotCompile *acfg)
8322 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8327 * cat > foo.m << EOF
8330 * return @selector(print:);
8335 img_writer_emit_unset_mode (acfg->w);
8336 g_assert (acfg->fp);
8337 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8338 fprintf (acfg->fp, ".align 3\n");
8339 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8340 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8341 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8343 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8344 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8345 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8346 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8349 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8350 fprintf (acfg->fp, ".align 3\n");
8351 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8352 fprintf (acfg->fp, ".long 0\n");
8353 fprintf (acfg->fp, ".long 16\n");
8357 emit_dwarf_info (MonoAotCompile *acfg)
8359 #ifdef EMIT_DWARF_INFO
8363 /* DIEs for methods */
8364 for (i = 0; i < acfg->nmethods; ++i) {
8365 MonoCompile *cfg = acfg->cfgs [i];
8370 // FIXME: LLVM doesn't define .Lme_...
8371 if (cfg->compile_llvm)
8374 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8376 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->d.method, mono_domain_get ()));
8382 collect_methods (MonoAotCompile *acfg)
8385 MonoImage *image = acfg->image;
8387 /* Collect methods */
8388 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8390 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8392 method = mono_get_method (acfg->image, token, NULL);
8395 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8396 printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8400 /* Load all methods eagerly to skip the slower lazy loading code */
8401 mono_class_setup_methods (method->klass);
8403 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8404 /* Compile the wrapper instead */
8405 /* We do this here instead of add_wrappers () because it is easy to do it here */
8406 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8410 /* FIXME: Some mscorlib methods don't have debug info */
8412 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8413 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8414 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8415 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8416 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8417 if (!mono_debug_lookup_method (method)) {
8418 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8425 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8426 add_method_with_index (acfg, method, i, FALSE);
8427 acfg->method_index ++;
8430 /* gsharedvt methods */
8431 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8433 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8435 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8438 method = mono_get_method (acfg->image, token, NULL);
8442 if (strcmp (method->name, "gshared2"))
8446 if (!strstr (method->klass->image->name, "mini"))
8449 if (method->is_generic || method->klass->generic_container) {
8450 MonoMethod *gshared;
8452 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8453 add_extra_method (acfg, gshared);
8457 add_generic_instances (acfg);
8459 if (acfg->aot_opts.full_aot)
8460 add_wrappers (acfg);
8464 compile_methods (MonoAotCompile *acfg)
8468 if (acfg->aot_opts.nthreads > 0) {
8473 gpointer *user_data;
8474 MonoMethod **methods;
8476 methods_len = acfg->methods->len;
8478 len = acfg->methods->len / acfg->aot_opts.nthreads;
8481 * Partition the list of methods into fragments, and hand it to threads to
8484 threads = g_ptr_array_new ();
8485 /* Make a copy since acfg->methods is modified by compile_method () */
8486 methods = g_new0 (MonoMethod*, methods_len);
8487 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8488 for (i = 0; i < methods_len; ++i)
8489 methods [i] = g_ptr_array_index (acfg->methods, i);
8491 while (i < methods_len) {
8492 frag = g_ptr_array_new ();
8493 for (j = 0; j < len; ++j) {
8494 if (i < methods_len) {
8495 g_ptr_array_add (frag, methods [i]);
8500 user_data = g_new0 (gpointer, 3);
8501 user_data [0] = mono_domain_get ();
8502 user_data [1] = acfg;
8503 user_data [2] = frag;
8505 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8506 g_ptr_array_add (threads, handle);
8510 for (i = 0; i < threads->len; ++i) {
8511 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8517 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8518 for (i = methods_len; i < acfg->methods->len; ++i) {
8519 /* This can new methods to acfg->methods */
8520 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8525 compile_asm (MonoAotCompile *acfg)
8527 char *command, *objfile;
8528 char *outfile_name, *tmp_outfile_name;
8529 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8531 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8532 #define AS_OPTIONS "--64"
8533 #elif defined(TARGET_POWERPC64)
8534 #define AS_OPTIONS "-a64 -mppc64"
8535 #define LD_OPTIONS "-m elf64ppc"
8536 #elif defined(sparc) && SIZEOF_VOID_P == 8
8537 #define AS_OPTIONS "-xarch=v9"
8538 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8539 #define AS_OPTIONS "-arch i386"
8541 #define AS_OPTIONS ""
8544 #ifdef __native_client_codegen__
8545 #if defined(TARGET_AMD64)
8546 #define AS_NAME "nacl64-as"
8548 #define AS_NAME "nacl-as"
8550 #elif defined(TARGET_OSX)
8551 #define AS_NAME "clang -c -x assembler"
8553 #define AS_NAME "as"
8557 #define LD_OPTIONS ""
8561 #define LD_NAME "ld -shared -G"
8562 #elif defined(__ppc__) && defined(TARGET_MACH)
8563 #define LD_NAME "gcc -dynamiclib"
8564 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8565 #define LD_NAME "clang --shared"
8566 #elif defined(HOST_WIN32)
8567 #define LD_NAME "gcc -shared --dll"
8568 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8569 #define LD_NAME "clang -m32 -dynamiclib"
8572 if (acfg->aot_opts.asm_only) {
8573 printf ("Output file: '%s'.\n", acfg->tmpfname);
8574 if (acfg->aot_opts.static_link)
8575 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8579 if (acfg->aot_opts.static_link) {
8580 if (acfg->aot_opts.outfile)
8581 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8583 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8585 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8587 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);
8588 printf ("Executing the native assembler: %s\n", command);
8589 if (system (command) != 0) {
8597 if (acfg->aot_opts.static_link) {
8598 printf ("Output file: '%s'.\n", objfile);
8599 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8604 if (acfg->aot_opts.outfile)
8605 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8607 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8609 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8612 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8614 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8616 printf ("Executing the native linker: %s\n", command);
8617 if (system (command) != 0) {
8618 g_free (tmp_outfile_name);
8619 g_free (outfile_name);
8627 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8628 printf ("Stripping the binary: %s\n", com);
8632 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8634 * gas generates 'mapping symbols' each time code and data is mixed, which
8635 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8637 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8638 printf ("Stripping the binary: %s\n", command);
8639 if (system (command) != 0) {
8640 g_free (tmp_outfile_name);
8641 g_free (outfile_name);
8648 rename (tmp_outfile_name, outfile_name);
8650 #if defined(TARGET_MACH)
8651 command = g_strdup_printf ("dsymutil %s", outfile_name);
8652 printf ("Executing dsymutil: %s\n", command);
8653 if (system (command) != 0) {
8658 if (!acfg->aot_opts.save_temps)
8661 g_free (tmp_outfile_name);
8662 g_free (outfile_name);
8665 if (acfg->aot_opts.save_temps)
8666 printf ("Retained input file.\n");
8668 unlink (acfg->tmpfname);
8673 static MonoAotCompile*
8674 acfg_create (MonoAssembly *ass, guint32 opts)
8676 MonoImage *image = ass->image;
8677 MonoAotCompile *acfg;
8680 acfg = g_new0 (MonoAotCompile, 1);
8681 acfg->methods = g_ptr_array_new ();
8682 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8683 acfg->method_depth = g_hash_table_new (NULL, NULL);
8684 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8685 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8686 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8687 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8688 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8689 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8690 acfg->got_patches = g_ptr_array_new ();
8691 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8692 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8693 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8694 acfg->image_hash = g_hash_table_new (NULL, NULL);
8695 acfg->image_table = g_ptr_array_new ();
8696 acfg->globals = g_ptr_array_new ();
8697 acfg->image = image;
8699 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8700 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8701 acfg->mempool = mono_mempool_new ();
8702 acfg->extra_methods = g_ptr_array_new ();
8703 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8704 acfg->unwind_ops = g_ptr_array_new ();
8705 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8706 acfg->method_order = g_ptr_array_new ();
8707 acfg->export_names = g_hash_table_new (NULL, NULL);
8708 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8709 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8710 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8711 mono_mutex_init_recursive (&acfg->mutex);
8717 acfg_free (MonoAotCompile *acfg)
8721 img_writer_destroy (acfg->w);
8722 for (i = 0; i < acfg->nmethods; ++i)
8724 g_free (acfg->cfgs [i]);
8725 g_free (acfg->cfgs);
8726 g_free (acfg->static_linking_symbol);
8727 g_free (acfg->got_symbol);
8728 g_free (acfg->plt_symbol);
8729 g_ptr_array_free (acfg->methods, TRUE);
8730 g_ptr_array_free (acfg->got_patches, TRUE);
8731 g_ptr_array_free (acfg->image_table, TRUE);
8732 g_ptr_array_free (acfg->globals, TRUE);
8733 g_ptr_array_free (acfg->unwind_ops, TRUE);
8734 g_hash_table_destroy (acfg->method_indexes);
8735 g_hash_table_destroy (acfg->method_depth);
8736 g_hash_table_destroy (acfg->plt_offset_to_entry);
8737 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8738 if (acfg->patch_to_plt_entry [i])
8739 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8741 g_free (acfg->patch_to_plt_entry);
8742 g_hash_table_destroy (acfg->patch_to_got_offset);
8743 g_hash_table_destroy (acfg->method_to_cfg);
8744 g_hash_table_destroy (acfg->token_info_hash);
8745 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8746 g_hash_table_destroy (acfg->image_hash);
8747 g_hash_table_destroy (acfg->unwind_info_offsets);
8748 g_hash_table_destroy (acfg->method_label_hash);
8749 g_hash_table_destroy (acfg->export_names);
8750 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8751 g_hash_table_destroy (acfg->klass_blob_hash);
8752 g_hash_table_destroy (acfg->method_blob_hash);
8753 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8754 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8755 g_free (acfg->patch_to_got_offset_by_type);
8756 mono_mempool_destroy (acfg->mempool);
8761 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8763 MonoImage *image = ass->image;
8764 int i, res, all_sizes;
8765 MonoAotCompile *acfg;
8766 char *outfile_name, *tmp_outfile_name, *p;
8767 char llvm_stats_msg [256];
8771 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8772 if (opts & MONO_OPT_GSHAREDVT) {
8773 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8778 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8780 acfg = acfg_create (ass, opts);
8782 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8783 acfg->aot_opts.write_symbols = TRUE;
8784 acfg->aot_opts.ntrampolines = 1024;
8785 acfg->aot_opts.nrgctx_trampolines = 1024;
8786 acfg->aot_opts.nimt_trampolines = 128;
8787 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8788 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8789 acfg->aot_opts.llvm_path = g_strdup ("");
8791 acfg->aot_opts.use_trampolines_page = TRUE;
8794 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8796 if (acfg->aot_opts.static_link)
8797 acfg->aot_opts.autoreg = TRUE;
8799 //acfg->aot_opts.print_skipped_methods = TRUE;
8801 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8802 if (acfg->aot_opts.full_aot) {
8803 printf ("--aot=full is not supported on this platform.\n");
8808 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8809 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8813 if (acfg->aot_opts.static_link)
8814 acfg->aot_opts.asm_writer = TRUE;
8816 if (acfg->aot_opts.soft_debug) {
8817 MonoDebugOptions *opt = mini_get_debug_options ();
8819 opt->mdb_optimizations = TRUE;
8820 opt->gen_seq_points = TRUE;
8822 if (!mono_debug_enabled ()) {
8823 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8826 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8829 if (mono_use_llvm) {
8831 acfg->aot_opts.asm_writer = TRUE;
8832 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8834 if (acfg->aot_opts.soft_debug) {
8835 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8840 if (acfg->aot_opts.full_aot)
8841 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8843 if (acfg->aot_opts.instances_logfile_path) {
8844 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
8845 if (!acfg->instances_logfile) {
8846 fprintf (stderr, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
8851 load_profile_files (acfg);
8853 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8854 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8855 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8857 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8858 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8859 if (acfg->opts & MONO_OPT_GSHAREDVT)
8860 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8863 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8867 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8868 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8869 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8871 /* Get rid of characters which cannot occur in symbols */
8872 for (p = acfg->got_symbol_base; *p; ++p) {
8873 if (!(isalnum (*p) || *p == '_'))
8876 for (p = acfg->plt_symbol; *p; ++p) {
8877 if (!(isalnum (*p) || *p == '_'))
8880 for (p = acfg->assembly_name_sym; *p; ++p) {
8881 if (!(isalnum (*p) || *p == '_'))
8885 acfg->method_index = 1;
8889 if (acfg->aot_opts.full_aot)
8890 mono_set_partial_sharing_supported (TRUE);
8893 collect_methods (acfg);
8895 acfg->cfgs_size = acfg->methods->len + 32;
8896 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8898 /* PLT offset 0 is reserved for the PLT trampoline */
8899 acfg->plt_offset = 1;
8904 mono_llvm_create_aot_module (acfg->got_symbol_base);
8908 /* GOT offset 0 is reserved for the address of the current assembly */
8912 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8913 ji->type = MONO_PATCH_INFO_IMAGE;
8914 ji->data.image = acfg->image;
8916 get_got_offset (acfg, ji);
8918 /* Slot 1 is reserved for the mscorlib got addr */
8919 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8920 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8921 get_got_offset (acfg, ji);
8923 /* This is very common */
8924 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8925 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8926 get_got_offset (acfg, ji);
8928 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8929 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8930 get_got_offset (acfg, ji);
8935 compile_methods (acfg);
8939 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8945 if (acfg->aot_opts.asm_only) {
8946 if (acfg->aot_opts.outfile) {
8947 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8948 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8950 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8951 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8954 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8955 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8958 emit_llvm_file (acfg);
8962 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8963 if (acfg->aot_opts.outfile)
8964 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8966 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8969 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8970 * it might be in another file system so the rename () won't work.
8972 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8974 acfg->fp = fopen (tmp_outfile_name, "w");
8976 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8980 acfg->w = img_writer_create (acfg->fp, TRUE);
8981 acfg->use_bin_writer = TRUE;
8984 /* Append to the .s file created by llvm */
8985 /* FIXME: Use multiple files instead */
8986 acfg->fp = fopen (acfg->tmpfname, "a+");
8988 if (acfg->aot_opts.asm_only) {
8989 if (acfg->aot_opts.outfile)
8990 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8992 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8993 acfg->fp = fopen (acfg->tmpfname, "w+");
8995 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8996 acfg->fp = fdopen (i, "w+");
8999 if (acfg->fp == 0) {
9000 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9003 acfg->w = img_writer_create (acfg->fp, FALSE);
9005 tmp_outfile_name = NULL;
9006 outfile_name = NULL;
9009 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9011 /* Compute symbols for methods */
9012 for (i = 0; i < acfg->nmethods; ++i) {
9013 if (acfg->cfgs [i]) {
9014 MonoCompile *cfg = acfg->cfgs [i];
9015 int method_index = get_method_index (acfg, cfg->orig_method);
9017 if (COMPILE_LLVM (cfg))
9018 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9019 else if (acfg->global_symbols)
9020 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
9022 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9026 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9028 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9029 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9032 //acfg->gas_line_numbers = TRUE;
9035 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9036 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9037 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
9040 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9043 img_writer_emit_start (acfg->w);
9046 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9048 if (acfg->thumb_mixed) {
9051 * This global symbol marks the end of THUMB code, and the beginning of ARM
9052 * code generated by our JIT.
9054 sprintf (symbol, "thumb_end");
9055 emit_section_change (acfg, ".text", 0);
9056 emit_alignment (acfg, 8);
9057 emit_label (acfg, symbol);
9058 emit_zero_bytes (acfg, 16);
9060 fprintf (acfg->fp, ".arm\n");
9067 emit_extra_methods (acfg);
9069 emit_trampolines (acfg);
9071 emit_class_name_table (acfg);
9073 emit_got_info (acfg);
9075 emit_exception_info (acfg);
9077 emit_unwind_info (acfg);
9079 emit_class_info (acfg);
9083 emit_image_table (acfg);
9087 emit_file_info (acfg);
9091 emit_objc_selectors (acfg);
9093 emit_globals (acfg);
9095 emit_autoreg (acfg);
9098 emit_dwarf_info (acfg);
9099 mono_dwarf_writer_close (acfg->dwarf);
9102 emit_mem_end (acfg);
9104 if (acfg->need_pt_gnu_stack) {
9105 /* This is required so the .so doesn't have an executable stack */
9106 /* The bin writer already emits this */
9107 if (!acfg->use_bin_writer)
9108 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9113 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9116 g_assert (acfg->got_offset <= acfg->final_got_size);
9119 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9121 strcpy (llvm_stats_msg, "");
9123 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
9125 printf ("Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
9126 acfg->stats.code_size, acfg->stats.code_size * 100 / all_sizes,
9127 acfg->stats.info_size, acfg->stats.info_size * 100 / all_sizes,
9128 acfg->stats.ex_info_size, acfg->stats.ex_info_size * 100 / all_sizes,
9129 acfg->stats.unwind_info_size, acfg->stats.unwind_info_size * 100 / all_sizes,
9130 acfg->stats.class_info_size, acfg->stats.class_info_size * 100 / all_sizes,
9131 acfg->stats.plt_size ? acfg->stats.plt_size : acfg->plt_offset, acfg->stats.plt_size ? acfg->stats.plt_size * 100 / all_sizes : 0,
9132 acfg->stats.got_info_size, acfg->stats.got_info_size * 100 / all_sizes,
9133 acfg->stats.offsets_size, acfg->stats.offsets_size * 100 / all_sizes,
9134 (int)(acfg->got_offset * sizeof (gpointer)));
9135 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9136 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9138 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9139 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9140 if (acfg->stats.genericcount)
9141 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9142 if (acfg->stats.abscount)
9143 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9144 if (acfg->stats.lmfcount)
9145 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9146 if (acfg->stats.ocount)
9147 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9150 res = img_writer_emit_writeout (acfg->w);
9155 if (acfg->use_bin_writer) {
9156 int err = rename (tmp_outfile_name, outfile_name);
9159 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9163 res = compile_asm (acfg);
9170 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9172 if (acfg->aot_opts.stats) {
9175 printf ("GOT slot distribution:\n");
9176 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9177 if (acfg->stats.got_slot_types [i])
9178 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9181 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);
9193 mono_aot_readonly_field_override (MonoClassField *field)
9199 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)