2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72 #if defined(__linux__) || defined(__native_client_codegen__)
73 #define RODATA_SECT ".rodata"
74 #elif defined(TARGET_MACH)
75 #define RODATA_SECT ".section __TEXT, __const"
77 #define RODATA_SECT ".text"
80 #define TV_DECLARE(name) gint64 name
81 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
82 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
85 #define SHARED_EXT ".dll"
86 #elif defined(__ppc__) && defined(TARGET_MACH)
87 #define SHARED_EXT ".dylib"
88 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
89 #define SHARED_EXT ".dylib"
90 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
91 #define SHARED_EXT ".dylib"
93 #define SHARED_EXT ".so"
96 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
97 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
98 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
100 /* predefined values for static readonly fields without needed to run the .cctor */
101 typedef struct _ReadOnlyValue ReadOnlyValue;
102 struct _ReadOnlyValue {
105 int type; /* to be used later for typechecking to prevent user errors */
114 static ReadOnlyValue *readonly_values = NULL;
116 typedef struct MonoAotOptions {
119 gboolean write_symbols;
120 gboolean metadata_only;
121 gboolean bind_to_runtime_version;
124 gboolean static_link;
128 gboolean dwarf_debug;
130 gboolean log_generics;
131 gboolean direct_pinvoke;
132 gboolean direct_icalls;
133 gboolean no_direct_calls;
134 gboolean use_trampolines_page;
135 gboolean no_instances;
139 int nrgctx_trampolines;
140 int nimt_trampolines;
141 int ngsharedvt_arg_trampolines;
142 int nrgctx_fetch_trampolines;
143 gboolean print_skipped_methods;
151 typedef struct MonoAotStats {
152 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
153 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
154 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
155 int got_slots, offsets_size;
156 int got_slot_types [MONO_PATCH_INFO_NONE];
157 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
158 int jit_time, gen_time, link_time;
161 typedef struct MonoAotCompile {
164 GHashTable *method_indexes;
165 GHashTable *method_depth;
168 GHashTable *patch_to_plt_entry;
169 GHashTable *plt_offset_to_entry;
170 GHashTable *patch_to_got_offset;
171 GHashTable **patch_to_got_offset_by_type;
172 GPtrArray *got_patches;
173 GHashTable *image_hash;
174 GHashTable *method_to_cfg;
175 GHashTable *token_info_hash;
176 GHashTable *method_to_pinvoke_import;
177 GPtrArray *extra_methods;
178 GPtrArray *image_table;
180 GPtrArray *method_order;
181 GHashTable *export_names;
182 /* Maps MonoClass* -> blob offset */
183 GHashTable *klass_blob_hash;
184 /* Maps MonoMethod* -> blob offset */
185 GHashTable *method_blob_hash;
186 guint32 *plt_got_info_offsets;
187 guint32 got_offset, plt_offset, plt_got_offset_base;
188 guint32 final_got_size;
189 /* Number of GOT entries reserved for trampolines */
190 guint32 num_trampoline_got_entries;
192 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
193 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
194 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
196 MonoAotOptions aot_opts;
200 MonoMemPool *mempool;
203 char *static_linking_symbol;
204 CRITICAL_SECTION mutex;
205 gboolean use_bin_writer;
206 gboolean gas_line_numbers;
208 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
215 char *got_symbol_base;
218 GHashTable *method_label_hash;
219 const char *temp_prefix;
220 const char *user_symbol_prefix;
221 const char *llvm_label_prefix;
222 guint32 label_generator;
224 MonoAotFileFlags flags;
225 MonoDynamicStream blob;
226 MonoClass **typespec_classes;
229 char *assembly_name_sym;
230 GHashTable *plt_entry_debug_sym_cache;
231 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
232 GHashTable *ginst_hash;
233 GHashTable *dwarf_ln_filenames;
234 gboolean global_symbols;
235 gboolean direct_method_addresses;
236 int objc_selector_index, objc_selector_index_2;
237 GPtrArray *objc_selectors;
238 GHashTable *objc_selector_to_index;
243 char *symbol, *llvm_symbol, *debug_sym;
245 gboolean jit_used, llvm_used;
248 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
249 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
251 /* This points to the current acfg in LLVM mode */
252 static MonoAotCompile *llvm_acfg;
254 #ifdef HAVE_ARRAY_ELEM_INIT
255 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
256 #define MSGSTRFIELD1(line) str##line
257 static const struct msgstr_t {
258 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
259 #include "patch-info.h"
262 #define PATCH_INFO(a,b) b,
263 #include "patch-info.h"
266 static const gint16 opidx [] = {
267 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
268 #include "patch-info.h"
272 static G_GNUC_UNUSED const char*
273 get_patch_name (int info)
275 return (const char*)&opstr + opidx [info];
279 #define PATCH_INFO(a,b) b,
280 static const char* const
281 patch_types [MONO_PATCH_INFO_NUM + 1] = {
282 #include "patch-info.h"
286 static G_GNUC_UNUSED const char*
287 get_patch_name (int info)
289 return patch_types [info];
295 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
297 /* Wrappers around the image writer functions */
300 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
302 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
306 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
308 img_writer_emit_push_section (acfg->w, section_name, subsection);
312 emit_pop_section (MonoAotCompile *acfg)
314 img_writer_emit_pop_section (acfg->w);
318 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
320 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
324 emit_label (MonoAotCompile *acfg, const char *name)
326 img_writer_emit_label (acfg->w, name);
330 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
332 img_writer_emit_bytes (acfg->w, buf, size);
336 emit_string (MonoAotCompile *acfg, const char *value)
338 img_writer_emit_string (acfg->w, value);
342 emit_line (MonoAotCompile *acfg)
344 img_writer_emit_line (acfg->w);
348 emit_alignment (MonoAotCompile *acfg, int size)
350 img_writer_emit_alignment (acfg->w, size);
354 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
356 img_writer_emit_pointer_unaligned (acfg->w, target);
360 emit_pointer (MonoAotCompile *acfg, const char *target)
362 img_writer_emit_pointer (acfg->w, target);
366 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
368 if (prefix [0] != '\0') {
369 char *s = g_strdup_printf ("%s%s", prefix, target);
370 img_writer_emit_pointer (acfg->w, s);
373 img_writer_emit_pointer (acfg->w, target);
378 emit_int16 (MonoAotCompile *acfg, int value)
380 img_writer_emit_int16 (acfg->w, value);
384 emit_int32 (MonoAotCompile *acfg, int value)
386 img_writer_emit_int32 (acfg->w, value);
390 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
392 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
396 emit_zero_bytes (MonoAotCompile *acfg, int num)
398 img_writer_emit_zero_bytes (acfg->w, num);
402 emit_byte (MonoAotCompile *acfg, guint8 val)
404 img_writer_emit_byte (acfg->w, val);
407 #ifdef __native_client_codegen__
409 emit_nacl_call_alignment (MonoAotCompile *acfg)
411 img_writer_emit_nacl_call_alignment (acfg->w);
415 static G_GNUC_UNUSED void
416 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
418 img_writer_emit_global (acfg->w, name, func);
422 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
424 if (acfg->aot_opts.no_dlsym) {
425 g_ptr_array_add (acfg->globals, g_strdup (name));
426 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
428 img_writer_emit_global (acfg->w, name, func);
433 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
435 img_writer_emit_symbol_size (acfg->w, name, end_label);
439 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
441 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
443 /* On apple, all symbols need to be aligned to avoid warnings from ld */
444 emit_alignment (acfg, 4);
446 img_writer_emit_label (acfg->w, name);
447 img_writer_emit_string (acfg->w, value);
450 static G_GNUC_UNUSED void
451 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
454 guint8 b = value & 0x7f;
456 if (value != 0) /* more bytes to come */
462 static G_GNUC_UNUSED void
463 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
466 gboolean negative = (value < 0);
473 /* the following is unnecessary if the
474 * implementation of >>= uses an arithmetic rather
475 * than logical shift for a signed left operand
479 value |= - ((gint64)1 <<(size - 7));
480 /* sign bit of byte is second high order bit (0x40) */
481 if ((value == 0 && !(byte & 0x40)) ||
482 (value == -1 && (byte & 0x40)))
486 emit_byte (acfg, byte);
490 static G_GNUC_UNUSED void
491 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
496 guint8 b = value & 0x7f;
498 if (value != 0) /* more bytes to come */
506 static G_GNUC_UNUSED void
507 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
510 gboolean negative = (value < 0);
518 /* the following is unnecessary if the
519 * implementation of >>= uses an arithmetic rather
520 * than logical shift for a signed left operand
524 value |= - (1 <<(size - 7));
525 /* sign bit of byte is second high order bit (0x40) */
526 if ((value == 0 && !(byte & 0x40)) ||
527 (value == -1 && (byte & 0x40)))
538 emit_unset_mode (MonoAotCompile *acfg)
540 img_writer_emit_unset_mode (acfg->w);
543 static G_GNUC_UNUSED void
544 emit_set_thumb_mode (MonoAotCompile *acfg)
546 emit_unset_mode (acfg);
547 fprintf (acfg->fp, ".code 16\n");
550 static G_GNUC_UNUSED void
551 emit_set_arm_mode (MonoAotCompile *acfg)
553 emit_unset_mode (acfg);
554 fprintf (acfg->fp, ".code 32\n");
557 /* ARCHITECTURE SPECIFIC CODE */
559 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
560 #define EMIT_DWARF_INFO 1
563 #if defined(TARGET_ARM)
564 #define AOT_FUNC_ALIGNMENT 4
566 #define AOT_FUNC_ALIGNMENT 16
568 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
569 #undef AOT_FUNC_ALIGNMENT
570 #define AOT_FUNC_ALIGNMENT 32
573 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
574 #define PPC_LD_OP "ld"
575 #define PPC_LDX_OP "ldx"
577 #define PPC_LD_OP "lwz"
578 #define PPC_LDX_OP "lwzx"
582 #define AOT_TARGET_STR "AMD64"
587 #define AOT_TARGET_STR "ARM (MACH)"
589 #define AOT_TARGET_STR "ARM (!MACH)"
593 #ifdef TARGET_POWERPC64
594 #ifdef __mono_ilp32__
595 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
597 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
600 #ifdef TARGET_POWERPC
601 #ifdef __mono_ilp32__
602 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
604 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
611 #define AOT_TARGET_STR "X86 (WIN32)"
612 #elif defined(__native_client_codegen__)
613 #define AOT_TARGET_STR "X86 (native client codegen)"
615 #define AOT_TARGET_STR "X86 (!native client codegen)"
619 #ifndef AOT_TARGET_STR
620 #define AOT_TARGET_STR ""
624 arch_init (MonoAotCompile *acfg)
626 acfg->llc_args = g_string_new ("");
627 acfg->as_args = g_string_new ("");
630 * The prefix LLVM likes to put in front of symbol names on darwin.
631 * The mach-os specs require this for globals, but LLVM puts them in front of all
632 * symbols. We need to handle this, since we need to refer to LLVM generated
635 acfg->llvm_label_prefix = "";
636 acfg->user_symbol_prefix = "";
638 #if defined(TARGET_AMD64) && defined(TARGET_MACH)
639 /* osx contains an old as which doesn't support avx opcodes */
640 g_string_append (acfg->llc_args, "-mattr=-avx");
644 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
645 g_string_append (acfg->llc_args, "-mattr=+v6");
648 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
649 g_string_append (acfg->as_args, " -mfpu=vfp3");
651 g_string_append (acfg->llc_args, " -soft-float");
654 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
655 acfg->thumb_mixed = TRUE;
657 if (acfg->aot_opts.mtriple)
658 mono_arch_set_target (acfg->aot_opts.mtriple);
662 acfg->user_symbol_prefix = "_";
663 acfg->llvm_label_prefix = "_";
664 acfg->need_no_dead_strip = TRUE;
665 acfg->aot_opts.gnu_asm = TRUE;
668 #if defined(__linux__) && !defined(TARGET_ARM)
669 acfg->need_pt_gnu_stack = TRUE;
673 acfg->direct_method_addresses = TRUE;
674 acfg->global_symbols = TRUE;
679 * arch_emit_direct_call:
681 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
685 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, int *call_size)
687 #if defined(TARGET_X86) || defined(TARGET_AMD64)
688 /* Need to make sure this is exactly 5 bytes long */
689 if (external && !acfg->use_bin_writer) {
690 emit_unset_mode (acfg);
691 fprintf (acfg->fp, "call %s\n", target);
693 emit_byte (acfg, '\xe8');
694 emit_symbol_diff (acfg, target, ".", -4);
697 #elif defined(TARGET_ARM)
698 if (acfg->use_bin_writer) {
705 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
706 emit_bytes (acfg, buf, 4);
708 emit_unset_mode (acfg);
709 fprintf (acfg->fp, "bl %s\n", target);
712 #elif defined(TARGET_POWERPC)
713 if (acfg->use_bin_writer) {
714 g_assert_not_reached ();
716 emit_unset_mode (acfg);
717 fprintf (acfg->fp, "bl %s\n", target);
721 g_assert_not_reached ();
727 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
729 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
730 * in in the 2. slot of every GOT, and require every method to place the GOT
731 * address in r30, even when it doesn't access the GOT otherwise. This way,
732 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
737 * PPC64 uses function descriptors which greatly complicate all code, since
738 * these are used very inconsistently in the runtime. Some functions like
739 * mono_compile_method () return ftn descriptors, while others like the
740 * trampoline creation functions do not.
741 * We assume that all GOT slots contain function descriptors, and create
742 * descriptors in aot-runtime.c when needed.
743 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
744 * from function descriptors, we could do the same, but it would require
745 * rewriting all the ppc/aot code to handle function descriptors properly.
746 * So instead, we use the same approach as on PPC32.
747 * This is a horrible mess, but fixing it would probably lead to an even bigger
753 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
756 #ifdef MONO_ARCH_AOT_SUPPORTED
758 * arch_emit_got_offset:
760 * The memory pointed to by CODE should hold native code for computing the GOT
761 * address. Emit this code while patching it with the offset between code and
762 * the GOT. CODE_SIZE is set to the number of bytes emitted.
765 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
767 #if defined(TARGET_POWERPC64)
768 g_assert (!acfg->use_bin_writer);
769 emit_unset_mode (acfg);
771 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
772 * unsupported relocations. So we store the got address into the .Lgot_addr
773 * symbol which is in the text segment, compute its address, and load it.
775 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
776 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
777 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
778 fprintf (acfg->fp, "add 30, 30, 0\n");
779 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
780 acfg->label_generator ++;
782 #elif defined(TARGET_POWERPC)
783 g_assert (!acfg->use_bin_writer);
784 emit_unset_mode (acfg);
785 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
786 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
787 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
788 acfg->label_generator ++;
791 guint32 offset = mono_arch_get_patch_offset (code);
792 emit_bytes (acfg, code, offset);
793 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
795 *code_size = offset + 4;
800 * arch_emit_got_access:
802 * The memory pointed to by CODE should hold native code for loading a GOT
803 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
804 * CODE_SIZE is set to the number of bytes emitted.
807 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
809 /* Emit beginning of instruction */
810 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
812 /* Emit the offset */
814 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
815 *code_size = mono_arch_get_patch_offset (code) + 4;
816 #elif defined(TARGET_X86)
817 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
818 *code_size = mono_arch_get_patch_offset (code) + 4;
819 #elif defined(TARGET_ARM)
820 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
821 *code_size = mono_arch_get_patch_offset (code) + 4;
822 #elif defined(TARGET_POWERPC)
828 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
829 g_assert (code - buf == 8);
830 emit_bytes (acfg, buf, code - buf);
831 *code_size = code - buf;
834 g_assert_not_reached ();
841 * arch_emit_objc_selector_ref:
843 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
846 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
848 #if defined(TARGET_ARM)
851 int lindex = acfg->objc_selector_index_2 ++;
854 emit_bytes (acfg, code, 8);
856 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
857 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
859 emit_label (acfg, symbol1);
860 img_writer_emit_unset_mode (acfg->w);
861 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
865 g_assert_not_reached ();
870 * arch_emit_plt_entry:
872 * Emit code for the PLT entry with index INDEX.
875 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
877 #if defined(TARGET_X86)
878 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
879 #if defined(__default_codegen__)
880 /* jmp *<offset>(%ebx) */
881 emit_byte (acfg, 0xff);
882 emit_byte (acfg, 0xa3);
883 emit_int32 (acfg, offset);
884 /* Used by mono_aot_get_plt_info_offset */
885 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
886 #elif defined(__native_client_codegen__)
887 const guint8 kSizeOfNaClJmp = 11;
888 guint8 bytes[kSizeOfNaClJmp];
889 guint8 *pbytes = &bytes[0];
891 x86_jump_membase32 (pbytes, X86_EBX, offset);
892 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
893 /* four bytes of data, used by mono_arch_patch_plt_entry */
894 /* For Native Client, make this work with data embedded in push. */
895 emit_byte (acfg, 0x68); /* hide data in a push */
896 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
897 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
898 #endif /*__native_client_codegen__*/
899 #elif defined(TARGET_AMD64)
900 #if defined(__default_codegen__)
902 * We can't emit jumps because they are 32 bits only so they can't be patched.
903 * So we make indirect calls through GOT entries which are patched by the AOT
904 * loader to point to .Lpd entries.
906 /* jmpq *<offset>(%rip) */
907 emit_byte (acfg, '\xff');
908 emit_byte (acfg, '\x25');
909 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
910 /* Used by mono_aot_get_plt_info_offset */
911 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
912 #elif defined(__native_client_codegen__)
914 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
915 guint8 *code = buf_aligned;
917 /* mov <OFFSET>(%rip), %r11d */
918 emit_byte (acfg, '\x45');
919 emit_byte (acfg, '\x8b');
920 emit_byte (acfg, '\x1d');
921 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
923 amd64_jump_reg (code, AMD64_R11);
924 /* This should be constant for the plt patch */
925 g_assert ((size_t)(code-buf_aligned) == 10);
926 emit_bytes (acfg, buf_aligned, code - buf_aligned);
928 /* Hide data in a push imm32 so it passes validation */
929 emit_byte (acfg, 0x68); /* push */
930 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
931 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
932 #endif /*__native_client_codegen__*/
933 #elif defined(TARGET_ARM)
938 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
939 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
940 emit_bytes (acfg, buf, code - buf);
941 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
942 /* Used by mono_aot_get_plt_info_offset */
943 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
944 #elif defined(TARGET_POWERPC)
945 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
947 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
948 g_assert (!acfg->use_bin_writer);
949 emit_unset_mode (acfg);
950 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
951 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
952 fprintf (acfg->fp, "add 11, 11, 30\n");
953 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
954 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
955 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
956 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
958 fprintf (acfg->fp, "mtctr 11\n");
959 fprintf (acfg->fp, "bctr\n");
960 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
962 g_assert_not_reached ();
967 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
969 #if defined(TARGET_ARM)
971 /* LLVM calls the PLT entries using bl, so emit a stub */
972 /* FIXME: Too much overhead on every call */
973 fprintf (acfg->fp, ".thumb_func\n");
974 fprintf (acfg->fp, "bx pc\n");
975 fprintf (acfg->fp, "nop\n");
976 fprintf (acfg->fp, ".arm\n");
978 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
979 /* The caller already transitioned to thumb */
980 /* The code below should be 12 bytes long */
981 /* clang has trouble encoding these instructions, so emit the binary */
983 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
984 /* thumb can't encode ld pc, [pc, ip] */
985 fprintf (acfg->fp, "add ip, pc, ip\n");
986 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
987 fprintf (acfg->fp, "bx ip\n");
989 emit_set_thumb_mode (acfg);
990 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
991 fprintf (acfg->fp, ".2byte 0x44fc\n");
992 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
993 fprintf (acfg->fp, ".2byte 0x4760\n");
994 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
995 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
996 emit_unset_mode (acfg);
997 emit_set_arm_mode (acfg);
999 g_assert_not_reached ();
1004 * arch_emit_specific_trampoline_pages:
1006 * Emits a page full of trampolines: each trampoline uses its own address to
1007 * lookup both the generic trampoline code and the data argument.
1008 * This page can be remapped in process multiple times so we can get an
1009 * unlimited number of trampolines.
1010 * Specifically this implementation uses the following trick: two memory pages
1011 * are allocated, with the first containing the data and the second containing the trampolines.
1012 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1013 * implementation does all the lifting.
1014 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1015 * on the arm 32 bit system.
1018 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1020 #if defined(TARGET_ARM)
1023 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1025 #define COMMON_TRAMP_SIZE 16
1026 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1027 int imm8, rot_amount;
1030 if (!acfg->aot_opts.use_trampolines_page)
1033 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1034 emit_alignment (acfg, mono_pagesize ());
1035 emit_global (acfg, symbol, TRUE);
1036 emit_label (acfg, symbol);
1038 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1040 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1041 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1042 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1043 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1045 g_assert (code - buf == COMMON_TRAMP_SIZE);
1048 emit_bytes (acfg, buf, code - buf);
1050 for (i = 0; i < count; ++i) {
1052 ARM_PUSH (code, 0x5fff);
1054 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1055 g_assert (code - buf == 8);
1056 emit_bytes (acfg, buf, code - buf);
1059 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1060 * the instruction pointer address, so the generic trampoline at the start of the page
1061 * subtracts 4096 to get to the data page and loads the values
1062 * We again fit the generic trampiline in 16 bytes.
1064 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1065 emit_global (acfg, symbol, TRUE);
1066 emit_label (acfg, symbol);
1068 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1069 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1070 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1071 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1073 g_assert (code - buf == COMMON_TRAMP_SIZE);
1076 emit_bytes (acfg, buf, code - buf);
1078 for (i = 0; i < count; ++i) {
1080 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1082 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1083 g_assert (code - buf == 8);
1084 emit_bytes (acfg, buf, code - buf);
1088 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1090 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1091 emit_global (acfg, symbol, TRUE);
1092 emit_label (acfg, symbol);
1094 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1095 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1096 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1097 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1098 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1099 g_assert (code - buf == COMMON_TRAMP_SIZE);
1101 emit_bytes (acfg, buf, code - buf);
1103 for (i = 0; i < count; ++i) {
1105 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1107 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1108 g_assert (code - buf == 8);
1109 emit_bytes (acfg, buf, code - buf);
1112 /* now the imt trampolines: each specific trampolines puts in the ip register
1113 * the instruction pointer address, so the generic trampoline at the start of the page
1114 * subtracts 4096 to get to the data page and loads the values
1115 * We again fit the generic trampiline in 16 bytes.
1117 #define IMT_TRAMP_SIZE 72
1118 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1119 emit_global (acfg, symbol, TRUE);
1120 emit_label (acfg, symbol);
1122 /* Need at least two free registers, plus a slot for storing the pc */
1123 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1125 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1126 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1127 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1129 /* The IMT method is in v5, r0 has the imt array address */
1132 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1133 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1134 imt_found_check = code;
1135 ARM_B_COND (code, ARMCOND_EQ, 0);
1137 /* End-of-loop check */
1138 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1139 loop_end_check = code;
1140 ARM_B_COND (code, ARMCOND_EQ, 0);
1143 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1144 loop_branch_back = code;
1146 arm_patch (loop_branch_back, loop_start);
1149 arm_patch (imt_found_check, code);
1150 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1151 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1152 /* Save it to the third stack slot */
1153 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1154 /* Restore the registers and branch */
1155 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1158 arm_patch (loop_end_check, code);
1159 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1160 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1161 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1165 g_assert (code - buf == IMT_TRAMP_SIZE);
1166 emit_bytes (acfg, buf, code - buf);
1168 for (i = 0; i < count; ++i) {
1170 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1172 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1173 g_assert (code - buf == 8);
1174 emit_bytes (acfg, buf, code - buf);
1180 * arch_emit_specific_trampoline:
1182 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1183 * two GOT slots which contain the generic trampoline address and the trampoline
1184 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1187 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1190 * The trampolines created here are variations of the specific
1191 * trampolines created in mono_arch_create_specific_trampoline (). The
1193 * - the generic trampoline address is taken from a got slot.
1194 * - the offset of the got slot where the trampoline argument is stored
1195 * is embedded in the instruction stream, and the generic trampoline
1196 * can load the argument by loading the offset, adding it to the
1197 * address of the trampoline to get the address of the got slot, and
1198 * loading the argument from there.
1199 * - all the trampolines should be of the same length.
1201 #if defined(TARGET_AMD64)
1202 #if defined(__default_codegen__)
1203 /* This should be exactly 16 bytes long */
1205 /* call *<offset>(%rip) */
1206 emit_byte (acfg, '\x41');
1207 emit_byte (acfg, '\xff');
1208 emit_byte (acfg, '\x15');
1209 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1210 /* This should be relative to the start of the trampoline */
1211 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1212 emit_zero_bytes (acfg, 5);
1213 #elif defined(__native_client_codegen__)
1215 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1216 guint8 *code = buf_aligned;
1221 /* Emit this call in 'code' so we can find out how long it is. */
1222 amd64_call_reg (code, AMD64_R11);
1223 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1224 call_len = code - call_start;
1226 /* The tramp_size is twice the NaCl alignment because it starts with */
1227 /* a call which needs to be aligned to the end of the boundary. */
1228 *tramp_size = kNaClAlignment*2;
1230 /* Emit nops to align call site below which is 7 bytes plus */
1231 /* the length of the call sequence emitted above. */
1232 /* Note: this requires the specific trampoline starts on a */
1233 /* kNaclAlignedment aligned address, which it does because */
1234 /* it's its own function that is aligned. */
1235 guint8 nop_buf[256];
1236 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1237 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1238 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1240 /* The trampoline is stored at the offset'th pointer, the -4 is */
1241 /* present because RIP relative addressing starts at the end of */
1242 /* the current instruction, while the label "." is relative to */
1243 /* the beginning of the current asm location, which in this case */
1244 /* is not the mov instruction, but the offset itself, due to the */
1245 /* way the bytes and ints are emitted here. */
1246 got_offset = (offset * sizeof(gpointer)) - 4;
1248 /* mov <OFFSET>(%rip), %r11d */
1249 emit_byte (acfg, '\x45');
1250 emit_byte (acfg, '\x8b');
1251 emit_byte (acfg, '\x1d');
1252 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1255 emit_bytes (acfg, call_start, call_len);
1257 /* The arg is stored at the offset+1 pointer, relative to beginning */
1258 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1259 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1261 /* We can't emit this data directly, hide in a "push imm32" */
1262 emit_byte (acfg, '\x68'); /* push */
1263 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1264 emit_alignment (acfg, kNaClAlignment);
1265 #endif /*__native_client_codegen__*/
1266 #elif defined(TARGET_ARM)
1270 /* This should be exactly 20 bytes long */
1273 ARM_PUSH (code, 0x5fff);
1274 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1275 /* Load the value from the GOT */
1276 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1278 ARM_BLX_REG (code, ARMREG_R1);
1280 g_assert (code - buf == 16);
1283 emit_bytes (acfg, buf, code - buf);
1285 * Only one offset is needed, since the second one would be equal to the
1288 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1289 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1290 #elif defined(TARGET_POWERPC)
1297 g_assert (!acfg->use_bin_writer);
1300 * PPC has no ip relative addressing, so we need to compute the address
1301 * of the mscorlib got. That is slow and complex, so instead, we store it
1302 * in the second got slot of every aot image. The caller already computed
1303 * the address of its got and placed it into r30.
1305 emit_unset_mode (acfg);
1306 /* Load mscorlib got address */
1307 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1308 /* Load generic trampoline address */
1309 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1310 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1311 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1312 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1313 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1315 fprintf (acfg->fp, "mtctr 11\n");
1316 /* Load trampoline argument */
1317 /* On ppc, we pass it normally to the generic trampoline */
1318 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1319 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1320 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1321 /* Branch to generic trampoline */
1322 fprintf (acfg->fp, "bctr\n");
1324 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1325 *tramp_size = 10 * 4;
1327 *tramp_size = 9 * 4;
1329 #elif defined(TARGET_X86)
1333 /* Similar to the PPC code above */
1335 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1337 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1338 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1339 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1343 /* Load mscorlib got address */
1344 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1345 /* Push trampoline argument */
1346 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1347 /* Load generic trampoline address */
1348 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1349 /* Branch to generic trampoline */
1350 x86_jump_reg (code, X86_ECX);
1352 #ifdef __native_client_codegen__
1354 /* emit nops to next 32 byte alignment */
1355 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1356 while (code < (buf + a)) x86_nop(code);
1359 emit_bytes (acfg, buf, code - buf);
1361 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1362 g_assert (code - buf == *tramp_size);
1364 g_assert_not_reached ();
1369 * arch_emit_unbox_trampoline:
1371 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1372 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1375 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1377 #if defined(TARGET_AMD64)
1382 this_reg = mono_arch_get_this_arg_reg (NULL);
1384 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1386 emit_bytes (acfg, buf, code - buf);
1388 emit_byte (acfg, '\xe9');
1389 emit_symbol_diff (acfg, call_target, ".", -4);
1390 #elif defined(TARGET_X86)
1397 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1399 emit_bytes (acfg, buf, code - buf);
1402 emit_byte (acfg, '\xe9');
1403 emit_symbol_diff (acfg, call_target, ".", -4);
1404 #elif defined(TARGET_ARM)
1408 if (acfg->thumb_mixed && cfg->compile_llvm) {
1409 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1410 fprintf (acfg->fp, "b %s\n", call_target);
1411 fprintf (acfg->fp, ".arm\n");
1412 fprintf (acfg->fp, ".align 2\n");
1418 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1420 emit_bytes (acfg, buf, code - buf);
1421 /* jump to method */
1422 if (acfg->use_bin_writer) {
1429 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1430 emit_bytes (acfg, buf, 4);
1432 if (acfg->thumb_mixed && cfg->compile_llvm)
1433 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1435 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1437 #elif defined(TARGET_POWERPC)
1440 g_assert (!acfg->use_bin_writer);
1442 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1443 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1445 g_assert_not_reached ();
1450 * arch_emit_static_rgctx_trampoline:
1452 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1453 * two GOT slots which contain the rgctx argument, and the method to jump to.
1454 * TRAMP_SIZE is set to the size of the emitted trampoline.
1455 * These kinds of trampolines cannot be enumerated statically, since there could
1456 * be one trampoline per method instantiation, so we emit the same code for all
1457 * trampolines, and parameterize them using two GOT slots.
1460 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1462 #if defined(TARGET_AMD64)
1463 #if defined(__default_codegen__)
1464 /* This should be exactly 13 bytes long */
1467 /* mov <OFFSET>(%rip), %r10 */
1468 emit_byte (acfg, '\x4d');
1469 emit_byte (acfg, '\x8b');
1470 emit_byte (acfg, '\x15');
1471 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1473 /* jmp *<offset>(%rip) */
1474 emit_byte (acfg, '\xff');
1475 emit_byte (acfg, '\x25');
1476 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1477 #elif defined(__native_client_codegen__)
1479 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1480 guint8 *code = buf_aligned;
1482 /* mov <OFFSET>(%rip), %r10d */
1483 emit_byte (acfg, '\x45');
1484 emit_byte (acfg, '\x8b');
1485 emit_byte (acfg, '\x15');
1486 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1488 /* mov <OFFSET>(%rip), %r11d */
1489 emit_byte (acfg, '\x45');
1490 emit_byte (acfg, '\x8b');
1491 emit_byte (acfg, '\x1d');
1492 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1495 amd64_jump_reg (code, AMD64_R11);
1496 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1498 emit_alignment (acfg, kNaClAlignment);
1499 *tramp_size = kNaClAlignment;
1500 #endif /*__native_client_codegen__*/
1502 #elif defined(TARGET_ARM)
1506 /* This should be exactly 24 bytes long */
1509 /* Load rgctx value */
1510 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1511 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1512 /* Load branch addr + branch */
1513 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1514 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1516 g_assert (code - buf == 16);
1519 emit_bytes (acfg, buf, code - buf);
1520 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1521 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1522 #elif defined(TARGET_POWERPC)
1529 g_assert (!acfg->use_bin_writer);
1532 * PPC has no ip relative addressing, so we need to compute the address
1533 * of the mscorlib got. That is slow and complex, so instead, we store it
1534 * in the second got slot of every aot image. The caller already computed
1535 * the address of its got and placed it into r30.
1537 emit_unset_mode (acfg);
1538 /* Load mscorlib got address */
1539 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1541 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1542 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1543 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1544 /* Load target address */
1545 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1546 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1547 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1548 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1549 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1550 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1552 fprintf (acfg->fp, "mtctr 11\n");
1553 /* Branch to the target address */
1554 fprintf (acfg->fp, "bctr\n");
1556 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1557 *tramp_size = 11 * 4;
1559 *tramp_size = 9 * 4;
1562 #elif defined(TARGET_X86)
1566 /* Similar to the PPC code above */
1568 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1571 /* Load mscorlib got address */
1572 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1574 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1575 /* Branch to the target address */
1576 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1578 #ifdef __native_client_codegen__
1580 /* emit nops to next 32 byte alignment */
1581 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1582 while (code < (buf + a)) x86_nop(code);
1586 emit_bytes (acfg, buf, code - buf);
1588 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1589 g_assert (code - buf == *tramp_size);
1591 g_assert_not_reached ();
1596 * arch_emit_imt_thunk:
1598 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1599 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1600 * key is the IMT key, and ptr holds the address of a memory location holding
1601 * the address to branch to if the IMT arg matches the key. The array is
1602 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1604 * TRAMP_SIZE is set to the size of the emitted trampoline.
1607 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1609 #if defined(TARGET_AMD64)
1611 #if defined(__native_client_codegen__)
1614 guint8 *labels [16];
1616 guint8 *mov_buf_ptr = mov_buf;
1618 const int kSizeOfMove = 7;
1619 #if defined(__default_codegen__)
1620 code = buf = g_malloc (256);
1621 #elif defined(__native_client_codegen__)
1622 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1623 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1624 /* The RIP relative move below is emitted first */
1629 /* FIXME: Optimize this, i.e. use binary search etc. */
1630 /* Maybe move the body into a separate function (slower, but much smaller) */
1632 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1635 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1637 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1640 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1642 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1645 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1646 amd64_jump_code (code, labels [0]);
1649 mono_amd64_patch (labels [2], code);
1650 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1651 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1654 mono_amd64_patch (labels [1], code);
1655 /* Load fail tramp */
1656 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1657 /* Check if there is a fail tramp */
1658 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1660 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1661 /* Jump to fail tramp */
1662 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1665 mono_amd64_patch (labels [3], code);
1666 x86_breakpoint (code);
1668 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1669 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1670 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1671 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1672 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1673 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1675 emit_bytes (acfg, buf, code - buf);
1677 *tramp_size = code - buf + kSizeOfMove;
1678 #if defined(__native_client_codegen__)
1679 /* The tramp will be padded to the next kNaClAlignment bundle. */
1680 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1683 #if defined(__default_codegen__)
1685 #elif defined(__native_client_codegen__)
1689 #elif defined(TARGET_X86)
1691 #ifdef __native_client_codegen__
1694 guint8 *labels [16];
1696 #if defined(__default_codegen__)
1697 code = buf = g_malloc (256);
1698 #elif defined(__native_client_codegen__)
1699 buf_alloc = g_malloc (256 + kNaClAlignment);
1700 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1703 /* Allocate a temporary stack slot */
1704 x86_push_reg (code, X86_EAX);
1706 x86_push_reg (code, X86_EAX);
1708 /* Load mscorlib got address */
1709 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1711 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1714 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1716 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1719 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1721 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1724 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1725 x86_jump_code (code, labels [0]);
1728 mono_x86_patch (labels [2], code);
1729 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1730 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1731 /* Save the target address to the temporary stack location */
1732 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1734 x86_pop_reg (code, X86_EAX);
1735 /* Jump to the target address */
1739 mono_x86_patch (labels [1], code);
1740 /* Load fail tramp */
1741 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1742 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1744 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1745 /* Jump to fail tramp */
1746 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1747 x86_pop_reg (code, X86_EAX);
1751 mono_x86_patch (labels [3], code);
1752 x86_breakpoint (code);
1754 #ifdef __native_client_codegen__
1756 /* emit nops to next 32 byte alignment */
1757 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1758 while (code < (buf + a)) x86_nop(code);
1761 emit_bytes (acfg, buf, code - buf);
1763 *tramp_size = code - buf;
1765 #if defined(__default_codegen__)
1767 #elif defined(__native_client_codegen__)
1771 #elif defined(TARGET_ARM)
1773 guint8 *code, *code2, *labels [16];
1777 /* The IMT method is in v5 */
1779 /* Need at least two free registers, plus a slot for storing the pc */
1780 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1782 /* Load the parameter from the GOT */
1783 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1784 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1787 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1788 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1790 ARM_B_COND (code, ARMCOND_EQ, 0);
1792 /* End-of-loop check */
1793 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1795 ARM_B_COND (code, ARMCOND_EQ, 0);
1798 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1801 arm_patch (labels [4], labels [1]);
1804 arm_patch (labels [2], code);
1805 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1806 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1807 /* Save it to the third stack slot */
1808 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1809 /* Restore the registers and branch */
1810 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1813 arm_patch (labels [3], code);
1814 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1815 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1816 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1820 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1822 emit_bytes (acfg, buf, code - buf);
1823 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1825 *tramp_size = code - buf + 4;
1826 #elif defined(TARGET_POWERPC)
1828 guint8 *code, *labels [16];
1832 /* Load the mscorlib got address */
1833 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1834 /* Load the parameter from the GOT */
1835 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1836 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1838 /* Load and check key */
1840 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1841 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1843 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1845 /* End-of-loop check */
1846 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1848 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1851 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1854 mono_ppc_patch (labels [4], labels [1]);
1857 mono_ppc_patch (labels [2], code);
1858 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1859 /* r11 now contains the value of the vtable slot */
1860 /* this is not a function descriptor on ppc64 */
1861 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1862 ppc_mtctr (code, ppc_r11);
1863 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1866 mono_ppc_patch (labels [3], code);
1870 *tramp_size = code - buf;
1872 emit_bytes (acfg, buf, code - buf);
1874 g_assert_not_reached ();
1879 * arch_emit_gsharedvt_arg_trampoline:
1881 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1882 * two GOT slots which contain the argument, and the code to jump to.
1883 * TRAMP_SIZE is set to the size of the emitted trampoline.
1884 * These kinds of trampolines cannot be enumerated statically, since there could
1885 * be one trampoline per method instantiation, so we emit the same code for all
1886 * trampolines, and parameterize them using two GOT slots.
1889 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1891 #if defined(TARGET_X86)
1895 /* Similar to the PPC code above */
1897 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1900 /* Load mscorlib got address */
1901 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1903 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1904 /* Branch to the target address */
1905 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1907 #ifdef __native_client_codegen__
1909 /* emit nops to next 32 byte alignment */
1910 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1911 while (code < (buf + a)) x86_nop(code);
1915 emit_bytes (acfg, buf, code - buf);
1917 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1918 g_assert (code - buf == *tramp_size);
1919 #elif defined(TARGET_ARM)
1923 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1924 /* Similar to arch_emit_specific_trampoline () */
1927 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1928 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1929 /* Load the arg value from the GOT */
1930 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1931 /* Load the addr from the GOT */
1932 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1934 ARM_BX (code, ARMREG_R1);
1936 g_assert (code - buf == 20);
1939 emit_bytes (acfg, buf, code - buf);
1940 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1942 g_assert_not_reached ();
1947 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1949 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1950 /* Based on code generated by gcc */
1951 emit_unset_mode (acfg);
1954 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1955 ".section .ctors,\"aw\",@progbits\n"
1959 ".section .opd,\"aw\"\n"
1962 ".long .%s,.TOC.@tocbase32\n"
1965 ".type .%s,@function\n"
1967 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1969 ".section .ctors,\"aw\",@progbits\n"
1973 ".section .opd,\"aw\"\n"
1976 ".long .%1$s,.TOC.@tocbase32\n"
1977 ".size %1$s,.-%1$s\n"
1979 ".type .%1$s,@function\n"
1981 ".%1$s:\n", symbol);
1992 "lis 3, .Lglobals@h\n"
1993 "ori 3, 3, .Lglobals@l\n"
1994 "bl .mono_aot_register_module\n"
2002 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2004 ".size .%s,.-.%s\n", symbol, symbol);
2007 ".size .%1$s,.-.%1$s\n", symbol);
2013 /* END OF ARCH SPECIFIC CODE */
2016 mono_get_field_token (MonoClassField *field)
2018 MonoClass *klass = field->parent;
2021 for (i = 0; i < klass->field.count; ++i) {
2022 if (field == &klass->fields [i])
2023 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2026 g_assert_not_reached ();
2031 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2035 //printf ("ENCODE: %d 0x%x.\n", value, value);
2038 * Same encoding as the one used in the metadata, extended to handle values
2039 * greater than 0x1fffffff.
2041 if ((value >= 0) && (value <= 127))
2043 else if ((value >= 0) && (value <= 16383)) {
2044 p [0] = 0x80 | (value >> 8);
2045 p [1] = value & 0xff;
2047 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2048 p [0] = (value >> 24) | 0xc0;
2049 p [1] = (value >> 16) & 0xff;
2050 p [2] = (value >> 8) & 0xff;
2051 p [3] = value & 0xff;
2056 p [1] = (value >> 24) & 0xff;
2057 p [2] = (value >> 16) & 0xff;
2058 p [3] = (value >> 8) & 0xff;
2059 p [4] = value & 0xff;
2067 stream_init (MonoDynamicStream *sh)
2070 sh->alloc_size = 4096;
2071 sh->data = g_malloc (4096);
2073 /* So offsets are > 0 */
2079 make_room_in_stream (MonoDynamicStream *stream, int size)
2081 if (size <= stream->alloc_size)
2084 while (stream->alloc_size <= size) {
2085 if (stream->alloc_size < 4096)
2086 stream->alloc_size = 4096;
2088 stream->alloc_size *= 2;
2091 stream->data = g_realloc (stream->data, stream->alloc_size);
2095 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2099 make_room_in_stream (stream, stream->index + len);
2100 memcpy (stream->data + stream->index, data, len);
2101 idx = stream->index;
2102 stream->index += len;
2109 * Add data to the binary blob inside the aot image. Returns the offset inside the
2110 * blob where the data was stored.
2113 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2115 if (acfg->blob.alloc_size == 0)
2116 stream_init (&acfg->blob);
2118 return add_stream_data (&acfg->blob, (char*)data, data_len);
2122 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2127 if (acfg->blob.alloc_size == 0)
2128 stream_init (&acfg->blob);
2130 count = acfg->blob.index % align;
2132 /* we assume the stream data will be aligned */
2134 add_stream_data (&acfg->blob, buf, 4 - count);
2136 return add_stream_data (&acfg->blob, (char*)data, data_len);
2140 * emit_offset_table:
2142 * Emit a table of increasing offsets in a compact form using differential encoding.
2143 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2144 * group size, the more compact the table becomes, but the slower it becomes to compute
2145 * a given entry. Returns the size of the table.
2148 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2150 gint32 current_offset;
2151 int i, buf_size, ngroups, index_entry_size;
2153 guint32 *index_offsets;
2155 ngroups = (noffsets + (group_size - 1)) / group_size;
2157 index_offsets = g_new0 (guint32, ngroups);
2159 buf_size = noffsets * 4;
2160 p = buf = g_malloc0 (buf_size);
2163 for (i = 0; i < noffsets; ++i) {
2164 //printf ("D: %d -> %d\n", i, offsets [i]);
2165 if ((i % group_size) == 0) {
2166 index_offsets [i / group_size] = p - buf;
2167 /* Emit the full value for these entries */
2168 encode_value (offsets [i], p, &p);
2170 /* The offsets are allowed to be non-increasing */
2171 //g_assert (offsets [i] >= current_offset);
2172 encode_value (offsets [i] - current_offset, p, &p);
2174 current_offset = offsets [i];
2177 if (ngroups && index_offsets [ngroups - 1] < 65000)
2178 index_entry_size = 2;
2180 index_entry_size = 4;
2182 /* Emit the header */
2183 emit_int32 (acfg, noffsets);
2184 emit_int32 (acfg, group_size);
2185 emit_int32 (acfg, ngroups);
2186 emit_int32 (acfg, index_entry_size);
2188 /* Emit the index */
2189 for (i = 0; i < ngroups; ++i) {
2190 if (index_entry_size == 2)
2191 emit_int16 (acfg, index_offsets [i]);
2193 emit_int32 (acfg, index_offsets [i]);
2197 emit_bytes (acfg, buf, p - buf);
2199 return (int)(p - buf) + (ngroups * 4);
2203 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2207 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2211 index = g_hash_table_size (cfg->image_hash);
2212 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2213 g_ptr_array_add (cfg->image_table, image);
2219 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2222 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2224 /* FIXME: Search referenced images as well */
2225 if (!acfg->typespec_classes) {
2226 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2227 for (i = 0; i < len; ++i) {
2228 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2231 for (i = 0; i < len; ++i) {
2232 if (acfg->typespec_classes [i] == klass)
2237 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2243 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2246 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2249 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2252 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2255 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2260 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2264 if (klass->generic_class) {
2266 g_assert (klass->type_token);
2268 /* Find a typespec for a class if possible */
2269 token = find_typespec_for_class (acfg, klass);
2271 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2272 encode_value (token, p, &p);
2274 MonoClass *gclass = klass->generic_class->container_class;
2275 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2276 static int count = 0;
2279 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2280 encode_klass_ref (acfg, gclass, p, &p);
2281 encode_ginst (acfg, inst, p, &p);
2285 } else if (klass->type_token) {
2286 int iindex = get_image_index (acfg, klass->image);
2288 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2290 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2291 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2293 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2294 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2295 encode_value (get_image_index (acfg, klass->image), p, &p);
2297 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2298 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2299 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2301 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2302 encode_value (klass->byval_arg.type, p, &p);
2303 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2305 encode_value (container ? 1 : 0, p, &p);
2307 encode_value (container->is_method, p, &p);
2308 g_assert (par->serial == 0);
2309 if (container->is_method)
2310 encode_method_ref (acfg, container->owner.method, p, &p);
2312 encode_klass_ref (acfg, container->owner.klass, p, &p);
2314 encode_value (par->serial, p, &p);
2316 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2317 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2318 encode_type (acfg, &klass->byval_arg, p, &p);
2321 g_assert (klass->rank > 0);
2322 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2323 encode_value (klass->rank, p, &p);
2324 encode_klass_ref (acfg, klass->element_class, p, &p);
2332 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2333 * standard metadata encoding.
2336 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2338 gboolean shared = FALSE;
2341 * The encoding of generic instances is large so emit them only once.
2343 if (klass->generic_class) {
2345 g_assert (klass->type_token);
2347 /* Find a typespec for a class if possible */
2348 token = find_typespec_for_class (acfg, klass);
2351 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2356 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2360 buf2 = g_malloc (1024);
2363 encode_klass_ref_inner (acfg, klass, p, &p);
2364 g_assert (p - buf2 < 1024);
2366 offset = add_to_blob (acfg, buf2, p - buf2);
2369 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2375 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2376 encode_value (offset, p, &p);
2381 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2385 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2387 guint32 token = mono_get_field_token (field);
2390 encode_klass_ref (cfg, field->parent, p, &p);
2391 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2392 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2397 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2402 encode_value (inst->type_argc, p, &p);
2403 for (i = 0; i < inst->type_argc; ++i)
2404 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2409 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2412 MonoGenericInst *inst;
2414 inst = context->class_inst;
2416 g_assert (inst->type_argc);
2417 encode_ginst (acfg, inst, p, &p);
2419 encode_value (0, p, &p);
2421 inst = context->method_inst;
2423 g_assert (inst->type_argc);
2424 encode_ginst (acfg, inst, p, &p);
2426 encode_value (0, p, &p);
2432 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2436 g_assert (t->num_mods == 0);
2437 /* t->attrs can be ignored */
2438 //g_assert (t->attrs == 0);
2441 *p = MONO_TYPE_PINNED;
2445 *p = MONO_TYPE_BYREF;
2453 case MONO_TYPE_VOID:
2454 case MONO_TYPE_BOOLEAN:
2455 case MONO_TYPE_CHAR:
2468 case MONO_TYPE_STRING:
2469 case MONO_TYPE_OBJECT:
2470 case MONO_TYPE_TYPEDBYREF:
2472 case MONO_TYPE_VALUETYPE:
2473 case MONO_TYPE_CLASS:
2474 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2476 case MONO_TYPE_SZARRAY:
2477 encode_klass_ref (acfg, t->data.klass, p, &p);
2480 encode_type (acfg, t->data.type, p, &p);
2482 case MONO_TYPE_GENERICINST: {
2483 MonoClass *gclass = t->data.generic_class->container_class;
2484 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2486 encode_klass_ref (acfg, gclass, p, &p);
2487 encode_ginst (acfg, inst, p, &p);
2490 case MONO_TYPE_ARRAY: {
2491 MonoArrayType *array = t->data.array;
2494 encode_klass_ref (acfg, array->eklass, p, &p);
2495 encode_value (array->rank, p, &p);
2496 encode_value (array->numsizes, p, &p);
2497 for (i = 0; i < array->numsizes; ++i)
2498 encode_value (array->sizes [i], p, &p);
2499 encode_value (array->numlobounds, p, &p);
2500 for (i = 0; i < array->numlobounds; ++i)
2501 encode_value (array->lobounds [i], p, &p);
2505 case MONO_TYPE_MVAR:
2506 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2509 g_assert_not_reached ();
2516 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2522 /* Similar to the metadata encoding */
2523 if (sig->generic_param_count)
2527 if (sig->explicit_this)
2529 flags |= (sig->call_convention & 0x0F);
2533 if (sig->generic_param_count)
2534 encode_value (sig->generic_param_count, p, &p);
2535 encode_value (sig->param_count, p, &p);
2537 encode_type (acfg, sig->ret, p, &p);
2538 for (i = 0; i < sig->param_count; ++i) {
2539 if (sig->sentinelpos == i) {
2540 *p = MONO_TYPE_SENTINEL;
2543 encode_type (acfg, sig->params [i], p, &p);
2549 #define MAX_IMAGE_INDEX 250
2552 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2554 guint32 image_index = get_image_index (acfg, method->klass->image);
2555 guint32 token = method->token;
2556 MonoJumpInfoToken *ji;
2560 * The encoding for most methods is as follows:
2561 * - image index encoded as a leb128
2562 * - token index encoded as a leb128
2563 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2564 * types of method encodings.
2567 /* Mark methods which can't use aot trampolines because they need the further
2568 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2570 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2571 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2572 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2574 if (method->wrapper_type) {
2575 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2577 encode_value (method->wrapper_type, p, &p);
2579 switch (method->wrapper_type) {
2580 case MONO_WRAPPER_REMOTING_INVOKE:
2581 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2582 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2585 m = mono_marshal_method_from_wrapper (method);
2587 encode_method_ref (acfg, m, p, &p);
2590 case MONO_WRAPPER_PROXY_ISINST:
2591 case MONO_WRAPPER_LDFLD:
2592 case MONO_WRAPPER_LDFLDA:
2593 case MONO_WRAPPER_STFLD:
2594 case MONO_WRAPPER_ISINST: {
2595 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2596 encode_klass_ref (acfg, proxy_class, p, &p);
2599 case MONO_WRAPPER_LDFLD_REMOTE:
2600 case MONO_WRAPPER_STFLD_REMOTE:
2602 case MONO_WRAPPER_ALLOC: {
2603 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2605 /* The GC name is saved once in MonoAotFileInfo */
2606 g_assert (info->alloc_type != -1);
2607 encode_value (info->alloc_type, p, &p);
2610 case MONO_WRAPPER_WRITE_BARRIER:
2612 case MONO_WRAPPER_STELEMREF: {
2613 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2616 encode_value (info->subtype, p, &p);
2617 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2618 encode_value (info->d.virtual_stelemref.kind, p, &p);
2621 case MONO_WRAPPER_UNKNOWN: {
2622 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2625 encode_value (info->subtype, p, &p);
2626 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2627 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2628 encode_klass_ref (acfg, method->klass, p, &p);
2629 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2630 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2631 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2632 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2635 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2636 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2639 encode_value (info->subtype, p, &p);
2640 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2641 strcpy ((char*)p, method->name);
2642 p += strlen (method->name) + 1;
2643 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2644 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2646 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2647 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2651 case MONO_WRAPPER_SYNCHRONIZED: {
2654 m = mono_marshal_method_from_wrapper (method);
2656 g_assert (m != method);
2657 encode_method_ref (acfg, m, p, &p);
2660 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2661 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2664 encode_value (info->subtype, p, &p);
2666 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2667 encode_value (info->d.element_addr.rank, p, &p);
2668 encode_value (info->d.element_addr.elem_size, p, &p);
2669 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2670 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2672 g_assert_not_reached ();
2676 case MONO_WRAPPER_CASTCLASS: {
2677 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2680 encode_value (info->subtype, p, &p);
2683 case MONO_WRAPPER_RUNTIME_INVOKE: {
2684 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2687 encode_value (info->subtype, p, &p);
2688 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2689 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2690 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2691 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2694 case MONO_WRAPPER_DELEGATE_INVOKE:
2695 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2696 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2697 if (method->is_inflated) {
2698 /* These wrappers are identified by their class */
2699 encode_value (1, p, &p);
2700 encode_klass_ref (acfg, method->klass, p, &p);
2702 MonoMethodSignature *sig = mono_method_signature (method);
2703 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2705 encode_value (0, p, &p);
2706 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2707 encode_value (info ? info->subtype : 0, p, &p);
2708 encode_signature (acfg, sig, p, &p);
2712 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2713 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2716 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2717 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2721 g_assert_not_reached ();
2723 } else if (mono_method_signature (method)->is_inflated) {
2725 * This is a generic method, find the original token which referenced it and
2727 * Obtain the token from information recorded by the JIT.
2729 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2731 image_index = get_image_index (acfg, ji->image);
2732 g_assert (image_index < MAX_IMAGE_INDEX);
2735 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2736 encode_value (image_index, p, &p);
2737 encode_value (token, p, &p);
2739 MonoMethod *declaring;
2740 MonoGenericContext *context = mono_method_get_context (method);
2742 g_assert (method->is_inflated);
2743 declaring = ((MonoMethodInflated*)method)->declaring;
2746 * This might be a non-generic method of a generic instance, which
2747 * doesn't have a token since the reference is generated by the JIT
2748 * like Nullable:Box/Unbox, or by generic sharing.
2750 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2751 /* Encode the klass */
2752 encode_klass_ref (acfg, method->klass, p, &p);
2753 /* Encode the method */
2754 image_index = get_image_index (acfg, method->klass->image);
2755 g_assert (image_index < MAX_IMAGE_INDEX);
2756 g_assert (declaring->token);
2757 token = declaring->token;
2758 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2759 encode_value (image_index, p, &p);
2760 encode_value (token, p, &p);
2761 encode_generic_context (acfg, context, p, &p);
2763 } else if (token == 0) {
2764 /* This might be a method of a constructed type like int[,].Set */
2765 /* Obtain the token from information recorded by the JIT */
2766 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2768 image_index = get_image_index (acfg, ji->image);
2769 g_assert (image_index < MAX_IMAGE_INDEX);
2772 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2773 encode_value (image_index, p, &p);
2774 encode_value (token, p, &p);
2777 g_assert (method->klass->rank);
2779 /* Encode directly */
2780 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2781 encode_klass_ref (acfg, method->klass, p, &p);
2782 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2783 encode_value (0, p, &p);
2784 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2785 encode_value (1, p, &p);
2786 else if (!strcmp (method->name, "Get"))
2787 encode_value (2, p, &p);
2788 else if (!strcmp (method->name, "Address"))
2789 encode_value (3, p, &p);
2790 else if (!strcmp (method->name, "Set"))
2791 encode_value (4, p, &p);
2793 g_assert_not_reached ();
2796 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2798 if (image_index >= MONO_AOT_METHODREF_MIN) {
2799 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2800 encode_value (image_index, p, &p);
2801 encode_value (mono_metadata_token_index (token), p, &p);
2803 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2810 compare_patches (gconstpointer a, gconstpointer b)
2814 i = (*(MonoJumpInfo**)a)->ip.i;
2815 j = (*(MonoJumpInfo**)b)->ip.i;
2826 static G_GNUC_UNUSED char*
2827 patch_to_string (MonoJumpInfo *patch_info)
2831 str = g_string_new ("");
2833 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2835 switch (patch_info->type) {
2836 case MONO_PATCH_INFO_VTABLE:
2837 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2842 g_string_append_printf (str, ")");
2843 return g_string_free (str, FALSE);
2849 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2852 static inline gboolean
2853 is_plt_patch (MonoJumpInfo *patch_info)
2855 switch (patch_info->type) {
2856 case MONO_PATCH_INFO_METHOD:
2857 case MONO_PATCH_INFO_INTERNAL_METHOD:
2858 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2859 case MONO_PATCH_INFO_ICALL_ADDR:
2860 case MONO_PATCH_INFO_CLASS_INIT:
2861 case MONO_PATCH_INFO_RGCTX_FETCH:
2862 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2863 case MONO_PATCH_INFO_MONITOR_ENTER:
2864 case MONO_PATCH_INFO_MONITOR_EXIT:
2865 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2875 * Return the symbol identifying the plt entry PLT_OFFSET.
2878 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2882 * The Apple linker reorganizes object files, so it doesn't like branches to local
2883 * labels, since those have no relocations.
2885 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2887 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2894 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2896 static MonoPltEntry*
2897 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2901 if (!is_plt_patch (patch_info))
2904 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2906 // FIXME: This breaks the calculation of final_got_size
2907 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2909 * Allocate a separate PLT slot for each such patch, since some plt
2910 * entries will refer to the method itself, and some will refer to the
2917 MonoJumpInfo *new_ji;
2919 g_assert (!acfg->final_got_size);
2921 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2923 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2924 res->plt_offset = acfg->plt_offset;
2926 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2927 if (acfg->aot_opts.write_symbols)
2928 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2930 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2932 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2934 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2936 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2938 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2939 //mono_print_ji (patch_info); printf ("\n");
2940 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2942 acfg->plt_offset ++;
2951 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2952 * JI could be found if it exists, otherwise allocates a new one.
2955 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2959 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2961 return got_offset - 1;
2963 got_offset = acfg->got_offset;
2964 acfg->got_offset ++;
2966 if (acfg->final_got_size)
2967 g_assert (got_offset < acfg->final_got_size);
2969 acfg->stats.got_slots ++;
2970 acfg->stats.got_slot_types [ji->type] ++;
2972 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2973 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2974 g_ptr_array_add (acfg->got_patches, ji);
2979 /* Add a method to the list of methods which need to be emitted */
2981 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2984 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2985 g_ptr_array_add (acfg->methods, method);
2986 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2987 acfg->nmethods = acfg->methods->len + 1;
2990 if (method->wrapper_type || extra)
2991 g_ptr_array_add (acfg->extra_methods, method);
2995 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2997 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3005 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3009 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3013 index = acfg->method_index;
3014 add_method_with_index (acfg, method, index, extra);
3016 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3018 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3020 acfg->method_index ++;
3026 add_method (MonoAotCompile *acfg, MonoMethod *method)
3028 return add_method_full (acfg, method, FALSE, 0);
3032 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3034 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3035 method = mini_get_shared_method (method);
3037 if (acfg->aot_opts.log_generics)
3038 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3040 add_method_full (acfg, method, TRUE, depth);
3044 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3046 add_extra_method_with_depth (acfg, method, 0);
3050 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3052 MonoAotCompile *acfg = user_data;
3053 MonoJitICallInfo *callinfo = value;
3054 MonoMethod *wrapper;
3060 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3061 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3064 add_method (acfg, wrapper);
3068 get_runtime_invoke_sig (MonoMethodSignature *sig)
3070 MonoMethodBuilder *mb;
3073 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3074 m = mono_mb_create_method (mb, sig, 16);
3075 return mono_marshal_get_runtime_invoke (m, FALSE);
3079 can_marshal_struct (MonoClass *klass)
3081 MonoClassField *field;
3082 gboolean can_marshal = TRUE;
3083 gpointer iter = NULL;
3084 MonoMarshalType *info;
3087 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3090 info = mono_marshal_load_type_info (klass);
3092 /* Only allow a few field types to avoid asserts in the marshalling code */
3093 while ((field = mono_class_get_fields (klass, &iter))) {
3094 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3097 switch (field->type->type) {
3102 case MONO_TYPE_BOOLEAN:
3105 case MONO_TYPE_CHAR:
3113 case MONO_TYPE_STRING:
3115 case MONO_TYPE_VALUETYPE:
3116 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3117 can_marshal = FALSE;
3119 case MONO_TYPE_SZARRAY: {
3120 gboolean has_mspec = FALSE;
3123 for (i = 0; i < info->num_fields; ++i) {
3124 if (info->fields [i].field == field && info->fields [i].mspec)
3129 can_marshal = FALSE;
3133 can_marshal = FALSE;
3139 /* Its hard to compute whenever these can be marshalled or not */
3140 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3147 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3149 /* Create a vtype instantiation */
3150 MonoGenericContext shared_context;
3152 MonoGenericInst *inst;
3153 MonoGenericContainer *container;
3154 MonoClass **constraints;
3157 memset (ctx, 0, sizeof (MonoGenericContext));
3159 if (method->klass->generic_container) {
3160 shared_context = method->klass->generic_container->context;
3161 inst = shared_context.class_inst;
3163 args = g_new0 (MonoType*, inst->type_argc);
3164 for (i = 0; i < inst->type_argc; ++i) {
3165 args [i] = &mono_defaults.int_class->byval_arg;
3167 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3169 if (method->is_generic) {
3170 container = mono_method_get_generic_container (method);
3171 shared_context = container->context;
3172 inst = shared_context.method_inst;
3174 args = g_new0 (MonoType*, inst->type_argc);
3175 for (i = 0; i < container->type_argc; ++i) {
3176 MonoGenericParamInfo *info = &container->type_params [i].info;
3177 gboolean ref_only = FALSE;
3179 if (info && info->constraints) {
3180 constraints = info->constraints;
3182 while (*constraints) {
3183 MonoClass *cklass = *constraints;
3184 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3185 /* Inflaring the method with our vtype would not be valid */
3192 args [i] = &mono_defaults.object_class->byval_arg;
3194 args [i] = &mono_defaults.int_class->byval_arg;
3196 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3201 add_wrappers (MonoAotCompile *acfg)
3203 MonoMethod *method, *m;
3205 MonoMethodSignature *sig, *csig;
3209 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3210 * so there is only one wrapper of a given type, or inlining their contents into their
3215 * FIXME: This depends on the fact that different wrappers have different
3219 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3221 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3222 gboolean skip = FALSE;
3224 method = mono_get_method (acfg->image, token, NULL);
3226 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3227 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3228 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3231 if (method->is_generic || method->klass->generic_container)
3234 /* Skip methods which can not be handled by get_runtime_invoke () */
3235 sig = mono_method_signature (method);
3238 if ((sig->ret->type == MONO_TYPE_PTR) ||
3239 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3242 for (j = 0; j < sig->param_count; j++) {
3243 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3247 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3248 if (!mono_class_is_contextbound (method->klass)) {
3249 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3250 gboolean has_nullable = FALSE;
3252 for (j = 0; j < sig->param_count; j++) {
3253 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3254 has_nullable = TRUE;
3257 if (info && !has_nullable) {
3258 /* Supported by the dynamic runtime-invoke wrapper */
3266 //printf ("%s\n", mono_method_full_name (method, TRUE));
3267 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3271 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3272 MonoMethodDesc *desc;
3273 MonoMethod *orig_method;
3276 /* Runtime invoke wrappers */
3278 /* void runtime-invoke () [.cctor] */
3279 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3280 csig->ret = &mono_defaults.void_class->byval_arg;
3281 add_method (acfg, get_runtime_invoke_sig (csig));
3283 /* void runtime-invoke () [Finalize] */
3284 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3286 csig->ret = &mono_defaults.void_class->byval_arg;
3287 add_method (acfg, get_runtime_invoke_sig (csig));
3289 /* void runtime-invoke (string) [exception ctor] */
3290 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3292 csig->ret = &mono_defaults.void_class->byval_arg;
3293 csig->params [0] = &mono_defaults.string_class->byval_arg;
3294 add_method (acfg, get_runtime_invoke_sig (csig));
3296 /* void runtime-invoke (string, string) [exception ctor] */
3297 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3299 csig->ret = &mono_defaults.void_class->byval_arg;
3300 csig->params [0] = &mono_defaults.string_class->byval_arg;
3301 csig->params [1] = &mono_defaults.string_class->byval_arg;
3302 add_method (acfg, get_runtime_invoke_sig (csig));
3304 /* string runtime-invoke () [Exception.ToString ()] */
3305 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3307 csig->ret = &mono_defaults.string_class->byval_arg;
3308 add_method (acfg, get_runtime_invoke_sig (csig));
3310 /* void runtime-invoke (string, Exception) [exception ctor] */
3311 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3313 csig->ret = &mono_defaults.void_class->byval_arg;
3314 csig->params [0] = &mono_defaults.string_class->byval_arg;
3315 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3316 add_method (acfg, get_runtime_invoke_sig (csig));
3318 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3319 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3321 csig->ret = &(mono_class_from_name (
3322 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3323 csig->params [0] = &mono_defaults.string_class->byval_arg;
3324 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3325 add_method (acfg, get_runtime_invoke_sig (csig));
3327 /* runtime-invoke used by finalizers */
3328 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3330 /* This is used by mono_runtime_capture_context () */
3331 method = mono_get_context_capture_method ();
3333 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3335 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3336 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3339 /* JIT icall wrappers */
3340 /* FIXME: locking */
3341 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3344 add_method (acfg, mono_marshal_get_stelemref ());
3346 if (MONO_ARCH_HAVE_TLS_GET) {
3347 /* Managed Allocators */
3348 nallocators = mono_gc_get_managed_allocator_types ();
3349 for (i = 0; i < nallocators; ++i) {
3350 m = mono_gc_get_managed_allocator_by_type (i);
3352 add_method (acfg, m);
3355 /* Monitor Enter/Exit */
3356 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3357 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3358 /* This is a v4 method */
3360 method = mono_monitor_get_fast_path (orig_method);
3362 add_method (acfg, method);
3364 mono_method_desc_free (desc);
3366 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3367 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3368 g_assert (orig_method);
3369 mono_method_desc_free (desc);
3370 method = mono_monitor_get_fast_path (orig_method);
3372 add_method (acfg, method);
3375 /* Stelemref wrappers */
3377 MonoMethod **wrappers;
3380 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3381 for (i = 0; i < nwrappers; ++i)
3382 add_method (acfg, wrappers [i]);
3386 /* castclass_with_check wrapper */
3387 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3388 /* isinst_with_check wrapper */
3389 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3391 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3393 MonoMethodDesc *desc;
3396 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3397 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3398 mono_method_desc_free (desc);
3400 m = mono_monitor_get_fast_path (m);
3402 add_method (acfg, m);
3409 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3410 * we use the original method instead at runtime.
3411 * Since full-aot doesn't support remoting, this is not a problem.
3414 /* remoting-invoke wrappers */
3415 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3416 MonoMethodSignature *sig;
3418 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3419 method = mono_get_method (acfg->image, token, NULL);
3421 sig = mono_method_signature (method);
3423 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3424 m = mono_marshal_get_remoting_invoke_with_check (method);
3426 add_method (acfg, m);
3431 /* delegate-invoke wrappers */
3432 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3434 MonoCustomAttrInfo *cattr;
3436 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3437 klass = mono_class_get (acfg->image, token);
3440 mono_loader_clear_error ();
3444 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3447 if (!klass->generic_container) {
3448 method = mono_get_delegate_invoke (klass);
3450 m = mono_marshal_get_delegate_invoke (method, NULL);
3452 add_method (acfg, m);
3454 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3456 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3458 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3460 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3462 cattr = mono_custom_attrs_from_class (klass);
3467 for (j = 0; j < cattr->num_attrs; ++j)
3468 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3470 if (j < cattr->num_attrs)
3471 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3473 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3474 MonoGenericContext ctx;
3475 MonoMethod *inst, *gshared;
3478 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3481 method = mono_get_delegate_invoke (klass);
3482 create_gsharedvt_inst (acfg, method, &ctx);
3484 inst = mono_class_inflate_generic_method (method, &ctx);
3486 m = mono_marshal_get_delegate_invoke (inst, NULL);
3487 g_assert (m->is_inflated);
3489 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3490 add_extra_method (acfg, gshared);
3493 method = mono_get_delegate_begin_invoke (klass);
3494 create_gsharedvt_inst (acfg, method, &ctx);
3496 inst = mono_class_inflate_generic_method (method, &ctx);
3498 m = mono_marshal_get_delegate_begin_invoke (inst);
3499 g_assert (m->is_inflated);
3501 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3502 add_extra_method (acfg, gshared);
3505 method = mono_get_delegate_end_invoke (klass);
3506 create_gsharedvt_inst (acfg, method, &ctx);
3508 inst = mono_class_inflate_generic_method (method, &ctx);
3510 m = mono_marshal_get_delegate_end_invoke (inst);
3511 g_assert (m->is_inflated);
3513 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3514 add_extra_method (acfg, gshared);
3519 /* array access wrappers */
3520 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3523 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3524 klass = mono_class_get (acfg->image, token);
3527 mono_loader_clear_error ();
3531 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3532 MonoMethod *m, *wrapper;
3534 /* Add runtime-invoke wrappers too */
3536 m = mono_class_get_method_from_name (klass, "Get", -1);
3538 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3539 add_extra_method (acfg, wrapper);
3540 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3542 m = mono_class_get_method_from_name (klass, "Set", -1);
3544 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3545 add_extra_method (acfg, wrapper);
3546 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3550 /* Synchronized wrappers */
3551 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3552 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3553 method = mono_get_method (acfg->image, token, NULL);
3555 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3556 if (method->is_generic) {
3558 } else if (method->klass->generic_container) {
3559 MonoGenericContext ctx;
3560 MonoMethod *inst, *gshared, *m;
3563 * Create a generic wrapper for a generic instance, and AOT that.
3565 create_gsharedvt_inst (acfg, method, &ctx);
3566 inst = mono_class_inflate_generic_method (method, &ctx);
3567 m = mono_marshal_get_synchronized_wrapper (inst);
3568 g_assert (m->is_inflated);
3569 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3570 add_method (acfg, gshared);
3572 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3577 /* pinvoke wrappers */
3578 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3580 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3582 method = mono_get_method (acfg->image, token, NULL);
3584 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3585 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3586 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3590 /* native-to-managed wrappers */
3591 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3593 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3594 MonoCustomAttrInfo *cattr;
3597 method = mono_get_method (acfg->image, token, NULL);
3600 * Only generate native-to-managed wrappers for methods which have an
3601 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3602 * name to avoid defining a new assembly to contain it.
3604 cattr = mono_custom_attrs_from_method (method);
3607 for (j = 0; j < cattr->num_attrs; ++j)
3608 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3610 if (j < cattr->num_attrs) {
3611 MonoCustomAttrEntry *e = &cattr->attrs [j];
3612 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3613 const char *p = (const char*)e->data;
3615 int slen, num_named, named_type, data_type;
3619 char *export_name = NULL;
3620 MonoMethod *wrapper;
3622 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3623 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3624 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3625 mono_method_full_name (method, TRUE));
3629 g_assert (sig->param_count == 1);
3630 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3633 * Decode the cattr manually since we can't create objects
3634 * during aot compilation.
3640 /* From load_cattr_value () in reflection.c */
3641 slen = mono_metadata_decode_value (p, &p);
3642 n = g_memdup (p, slen + 1);
3644 t = mono_reflection_type_from_name (n, acfg->image);
3648 klass = mono_class_from_mono_type (t);
3649 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3653 num_named = read16 (p);
3656 g_assert (num_named < 2);
3657 if (num_named == 1) {
3660 MonoType *prop_type;
3662 /* parse ExportSymbol attribute */
3664 named_type = *named;
3669 name_len = mono_metadata_decode_blob_size (named, &named);
3670 name = g_malloc (name_len + 1);
3671 memcpy (name, named, name_len);
3672 name [name_len] = 0;
3675 g_assert (named_type == 0x54);
3676 g_assert (!strcmp (name, "ExportSymbol"));
3678 prop_type = &mono_defaults.string_class->byval_arg;
3680 /* load_cattr_value (), string case */
3681 g_assert (*named != (char)0xff);
3682 slen = mono_metadata_decode_value (named, &named);
3683 export_name = g_malloc (slen + 1);
3684 memcpy (export_name, named, slen);
3685 export_name [slen] = 0;
3689 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3690 add_method (acfg, wrapper);
3692 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3696 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3697 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3698 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3702 /* StructureToPtr/PtrToStructure wrappers */
3703 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3706 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3707 klass = mono_class_get (acfg->image, token);
3710 mono_loader_clear_error ();
3714 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3715 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3716 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3717 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3723 has_type_vars (MonoClass *klass)
3725 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3728 return has_type_vars (klass->element_class);
3729 if (klass->generic_class) {
3730 MonoGenericContext *context = &klass->generic_class->context;
3731 if (context->class_inst) {
3734 for (i = 0; i < context->class_inst->type_argc; ++i)
3735 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3739 if (klass->generic_container)
3745 is_vt_inst (MonoGenericInst *inst)
3749 for (i = 0; i < inst->type_argc; ++i) {
3750 MonoType *t = inst->type_argv [i];
3751 if (t->type == MONO_TYPE_VALUETYPE)
3758 method_has_type_vars (MonoMethod *method)
3760 if (has_type_vars (method->klass))
3763 if (method->is_inflated) {
3764 MonoGenericContext *context = mono_method_get_context (method);
3765 if (context->method_inst) {
3768 for (i = 0; i < context->method_inst->type_argc; ++i)
3769 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3776 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3779 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3781 /* This might lead to a huge code blowup so only do it if neccesary */
3782 if (!acfg->aot_opts.full_aot && !force)
3785 add_generic_class_with_depth (acfg, klass, 0, ref);
3789 check_type_depth (MonoType *t, int depth)
3797 case MONO_TYPE_GENERICINST: {
3798 MonoGenericClass *gklass = t->data.generic_class;
3799 MonoGenericInst *ginst = gklass->context.class_inst;
3802 for (i = 0; i < ginst->type_argc; ++i) {
3803 if (check_type_depth (ginst->type_argv [i], depth + 1))
3817 * add_generic_class:
3819 * Add all methods of a generic class.
3822 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3825 MonoClassField *field;
3827 gboolean use_gsharedvt = FALSE;
3829 if (!acfg->ginst_hash)
3830 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3832 mono_class_init (klass);
3834 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3837 if (has_type_vars (klass))
3840 if (!klass->generic_class && !klass->rank)
3843 if (klass->exception_type)
3846 if (!acfg->ginst_hash)
3847 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3849 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3852 if (check_type_depth (&klass->byval_arg, 0))
3855 if (acfg->aot_opts.log_generics)
3856 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3858 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3861 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3862 * Enable this only for some classes since gsharedvt might not support all methods.
3864 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) && (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1")))
3865 use_gsharedvt = TRUE;
3868 while ((method = mono_class_get_methods (klass, &iter))) {
3869 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3871 * This is partial sharing, and we can't handle it yet
3876 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt))
3880 if (method->is_generic)
3885 * FIXME: Instances which are referenced by these methods are not added,
3886 * for example Array.Resize<int> for List<int>.Add ().
3888 add_extra_method_with_depth (acfg, method, depth + 1);
3892 while ((field = mono_class_get_fields (klass, &iter))) {
3893 if (field->type->type == MONO_TYPE_GENERICINST)
3894 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3897 if (klass->delegate) {
3898 method = mono_get_delegate_invoke (klass);
3900 method = mono_marshal_get_delegate_invoke (method, NULL);
3902 if (acfg->aot_opts.log_generics)
3903 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3905 add_method (acfg, method);
3908 /* Add superclasses */
3910 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3913 * For ICollection<T>, add instances of the helper methods
3914 * in Array, since a T[] could be cast to ICollection<T>.
3916 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3917 (!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"))) {
3918 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3919 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3923 if (!strcmp (klass->name, "IEnumerator`1"))
3924 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3926 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3928 /* Add the T[]/InternalEnumerator class */
3929 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3933 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3934 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3938 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3939 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3943 while ((method = mono_class_get_methods (array_class, &iter))) {
3944 if (strstr (method->name, name_prefix)) {
3945 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3947 add_extra_method_with_depth (acfg, m, depth);
3951 g_free (name_prefix);
3954 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3955 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3956 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3957 MonoClass *icomparable, *gcomparer;
3958 MonoGenericContext ctx;
3959 MonoType *args [16];
3961 memset (&ctx, 0, sizeof (ctx));
3963 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3964 g_assert (icomparable);
3965 args [0] = &tclass->byval_arg;
3966 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3968 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3969 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3970 g_assert (gcomparer);
3971 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3975 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3976 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3977 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3978 MonoClass *iface, *gcomparer;
3979 MonoGenericContext ctx;
3980 MonoType *args [16];
3982 memset (&ctx, 0, sizeof (ctx));
3984 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3986 args [0] = &tclass->byval_arg;
3987 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3989 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3990 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3991 g_assert (gcomparer);
3992 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3998 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4001 MonoGenericContext ctx;
4002 MonoType *args [16];
4004 if (acfg->aot_opts.no_instances)
4007 memset (&ctx, 0, sizeof (ctx));
4009 for (i = 0; i < ninsts; ++i) {
4010 args [0] = insts [i];
4011 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4012 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4017 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4019 MonoMethodHeader *header;
4020 MonoMethodSignature *sig;
4023 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4025 sig = mono_method_signature (method);
4028 for (j = 0; j < sig->param_count; ++j)
4029 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4030 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4033 header = mono_method_get_header (method);
4036 for (j = 0; j < header->num_locals; ++j)
4037 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4038 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4040 mono_loader_clear_error ();
4045 * add_generic_instances:
4047 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4050 add_generic_instances (MonoAotCompile *acfg)
4055 MonoGenericContext *context;
4057 if (acfg->aot_opts.no_instances)
4060 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4061 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4062 method = mono_get_method (acfg->image, token, NULL);
4067 if (method->klass->image != acfg->image)
4070 context = mono_method_get_context (method);
4072 if (context && ((context->class_inst && context->class_inst->is_open)))
4076 * For open methods, create an instantiation which can be passed to the JIT.
4077 * FIXME: Handle class_inst as well.
4079 if (context && context->method_inst && context->method_inst->is_open) {
4080 MonoGenericContext shared_context;
4081 MonoGenericInst *inst;
4082 MonoType **type_argv;
4084 MonoMethod *declaring_method;
4085 gboolean supported = TRUE;
4087 /* Check that the context doesn't contain open constructed types */
4088 if (context->class_inst) {
4089 inst = context->class_inst;
4090 for (i = 0; i < inst->type_argc; ++i) {
4091 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)
4093 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4097 if (context->method_inst) {
4098 inst = context->method_inst;
4099 for (i = 0; i < inst->type_argc; ++i) {
4100 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)
4102 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4110 memset (&shared_context, 0, sizeof (MonoGenericContext));
4112 inst = context->class_inst;
4114 type_argv = g_new0 (MonoType*, inst->type_argc);
4115 for (i = 0; i < inst->type_argc; ++i) {
4116 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)
4117 type_argv [i] = &mono_defaults.object_class->byval_arg;
4119 type_argv [i] = inst->type_argv [i];
4122 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4126 inst = context->method_inst;
4128 type_argv = g_new0 (MonoType*, inst->type_argc);
4129 for (i = 0; i < inst->type_argc; ++i) {
4130 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)
4131 type_argv [i] = &mono_defaults.object_class->byval_arg;
4133 type_argv [i] = inst->type_argv [i];
4136 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4140 if (method->is_generic || method->klass->generic_container)
4141 declaring_method = method;
4143 declaring_method = mono_method_get_declaring_generic_method (method);
4145 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4149 * If the method is fully sharable, it was already added in place of its
4150 * generic definition.
4152 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4156 * FIXME: Partially shared methods are not shared here, so we end up with
4157 * many identical methods.
4159 add_extra_method (acfg, method);
4162 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4165 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4167 klass = mono_class_get (acfg->image, token);
4168 if (!klass || klass->rank) {
4169 mono_loader_clear_error ();
4173 add_generic_class (acfg, klass, FALSE, "typespec");
4176 /* Add types of args/locals */
4177 for (i = 0; i < acfg->methods->len; ++i) {
4178 method = g_ptr_array_index (acfg->methods, i);
4179 add_types_from_method_header (acfg, method);
4182 if (acfg->image == mono_defaults.corlib) {
4184 MonoType *insts [256];
4187 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4188 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4189 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4190 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4191 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4192 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4193 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4194 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4195 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4196 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4197 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4198 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4200 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4201 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4203 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4204 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4206 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4208 /* Add instances of the array generic interfaces for primitive types */
4209 /* This will add instances of the InternalArray_ helper methods in Array too */
4210 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4212 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4213 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4215 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4216 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4218 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4221 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4222 * used for all instances of GetGenericValueImpl by the AOT runtime.
4225 MonoGenericContext ctx;
4226 MonoType *args [16];
4227 MonoMethod *get_method;
4228 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4230 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4233 memset (&ctx, 0, sizeof (ctx));
4234 args [0] = &mono_defaults.object_class->byval_arg;
4235 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4236 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4240 /* Same for CompareExchange<T>/Exchange<T> */
4242 MonoGenericContext ctx;
4243 MonoType *args [16];
4245 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4246 gpointer iter = NULL;
4248 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4249 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4250 memset (&ctx, 0, sizeof (ctx));
4251 args [0] = &mono_defaults.object_class->byval_arg;
4252 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4253 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4258 /* Same for Volatile.Read/Write<T> */
4260 MonoGenericContext ctx;
4261 MonoType *args [16];
4263 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4264 gpointer iter = NULL;
4266 if (volatile_klass) {
4267 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4268 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4269 memset (&ctx, 0, sizeof (ctx));
4270 args [0] = &mono_defaults.object_class->byval_arg;
4271 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4272 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4281 * is_direct_callable:
4283 * Return whenever the method identified by JI is directly callable without
4284 * going through the PLT.
4287 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4289 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4290 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4292 gboolean direct_callable = TRUE;
4294 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4295 direct_callable = FALSE;
4296 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4297 // FIXME: Maybe call the wrapper directly ?
4298 direct_callable = FALSE;
4300 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4301 /* Disable this so all calls go through load_method (), see the
4302 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4303 * mono_debugger_agent_init ().
4305 direct_callable = FALSE;
4308 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4309 /* sgen does some initialization when the allocator method is created */
4310 direct_callable = FALSE;
4312 if (direct_callable)
4315 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4316 if (acfg->aot_opts.direct_pinvoke)
4318 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4319 if (acfg->aot_opts.direct_icalls)
4328 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4330 MonoImage *image = method->klass->image;
4331 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4332 MonoTableInfo *tables = image->tables;
4333 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4334 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4335 guint32 im_cols [MONO_IMPLMAP_SIZE];
4338 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4342 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4345 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4347 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4350 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4352 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4358 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4360 if (a->native_offset == b->native_offset)
4361 return a->il_offset - b->il_offset;
4363 return a->native_offset - b->native_offset;
4367 * compute_line_numbers:
4369 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4372 static MonoDebugSourceLocation**
4373 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4375 MonoDebugMethodInfo *minfo;
4376 MonoDebugLineNumberEntry *ln_array;
4377 MonoDebugSourceLocation *loc;
4378 int i, prev_line, prev_il_offset;
4379 int *native_to_il_offset = NULL;
4380 MonoDebugSourceLocation **res;
4383 minfo = mono_debug_lookup_method (method);
4386 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4387 if (debug_info->code_size != code_size)
4390 g_assert (code_size);
4392 /* Compute the native->IL offset mapping */
4394 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4395 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4397 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4399 native_to_il_offset = g_new0 (int, code_size + 1);
4401 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4403 MonoDebugLineNumberEntry *lne = &ln_array [i];
4406 for (j = 0; j < lne->native_offset; ++j)
4407 native_to_il_offset [j] = -1;
4410 if (i < debug_info->num_line_numbers - 1) {
4411 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4413 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4414 native_to_il_offset [j] = lne->il_offset;
4416 for (j = lne->native_offset; j < code_size; ++j)
4417 native_to_il_offset [j] = lne->il_offset;
4422 /* Compute the native->line number mapping */
4423 res = g_new0 (MonoDebugSourceLocation*, code_size);
4424 prev_il_offset = -1;
4427 for (i = 0; i < code_size; ++i) {
4428 int il_offset = native_to_il_offset [i];
4430 if (il_offset == -1 || il_offset == prev_il_offset)
4432 prev_il_offset = il_offset;
4433 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4434 if (!(loc && loc->source_file))
4436 if (loc->row == prev_line) {
4437 mono_debug_symfile_free_location (loc);
4440 prev_line = loc->row;
4441 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4443 /* This will cover the prolog too */
4453 get_file_index (MonoAotCompile *acfg, const char *source_file)
4457 // FIXME: Free these
4458 if (!acfg->dwarf_ln_filenames)
4459 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4460 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4462 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4463 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4464 emit_unset_mode (acfg);
4465 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4471 * emit_and_reloc_code:
4473 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4474 * is true, calls are made through the GOT too. This is used for emitting trampolines
4475 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4476 * since trampolines are needed to make PTL work.
4479 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4481 int i, pindex, start_index, method_index;
4483 MonoJumpInfo *patch_info;
4484 MonoMethodHeader *header;
4485 MonoDebugSourceLocation **locs = NULL;
4486 gboolean skip, direct_call, external_call;
4488 const char *direct_call_target = 0;
4489 const char *direct_pinvoke;
4492 header = mono_method_get_header (method);
4494 method_index = get_method_index (acfg, method);
4497 if (acfg->gas_line_numbers && method && debug_info) {
4498 locs = compute_line_numbers (method, code_len, debug_info);
4500 int findex = get_file_index (acfg, "<unknown>");
4501 emit_unset_mode (acfg);
4502 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4506 /* Collect and sort relocations */
4507 patches = g_ptr_array_new ();
4508 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4509 g_ptr_array_add (patches, patch_info);
4510 g_ptr_array_sort (patches, compare_patches);
4513 for (i = 0; i < code_len; i++) {
4515 for (pindex = start_index; pindex < patches->len; ++pindex) {
4516 patch_info = g_ptr_array_index (patches, pindex);
4517 if (patch_info->ip.i >= i)
4521 if (locs && locs [i]) {
4522 MonoDebugSourceLocation *loc = locs [i];
4525 findex = get_file_index (acfg, loc->source_file);
4526 emit_unset_mode (acfg);
4527 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4528 mono_debug_symfile_free_location (loc);
4532 #ifdef MONO_ARCH_AOT_SUPPORTED
4533 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4534 start_index = pindex;
4536 switch (patch_info->type) {
4537 case MONO_PATCH_INFO_NONE:
4539 case MONO_PATCH_INFO_GOT_OFFSET: {
4542 arch_emit_got_offset (acfg, code + i, &code_size);
4545 patch_info->type = MONO_PATCH_INFO_NONE;
4548 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4549 int code_size, index;
4550 char *selector = (void*)patch_info->data.target;
4552 if (!acfg->objc_selector_to_index)
4553 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4554 if (!acfg->objc_selectors)
4555 acfg->objc_selectors = g_ptr_array_new ();
4556 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4560 index = acfg->objc_selector_index;
4561 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4562 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4563 acfg->objc_selector_index ++;
4566 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4569 patch_info->type = MONO_PATCH_INFO_NONE;
4574 * If this patch is a call, try emitting a direct call instead of
4575 * through a PLT entry. This is possible if the called method is in
4576 * the same assembly and requires no initialization.
4578 direct_call = FALSE;
4579 external_call = FALSE;
4580 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4581 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4582 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4583 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4585 direct_call_target = callee_cfg->asm_symbol;
4586 patch_info->type = MONO_PATCH_INFO_NONE;
4587 acfg->stats.direct_calls ++;
4590 acfg->stats.all_calls ++;
4591 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4592 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4593 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4594 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4596 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4597 if (direct_pinvoke) {
4599 g_assert (strlen (direct_pinvoke) < 1000);
4600 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4603 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4604 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4605 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4606 /* Call to a C function implementing a jit icall */
4608 external_call = TRUE;
4609 g_assert (strlen (sym) < 1000);
4610 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4612 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4613 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4614 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4615 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4616 /* Call to a jit icall without a wrapper */
4618 external_call = TRUE;
4619 g_assert (strlen (sym) < 1000);
4620 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4625 patch_info->type = MONO_PATCH_INFO_NONE;
4626 acfg->stats.direct_calls ++;
4629 if (!got_only && !direct_call) {
4630 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4632 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4634 direct_call_target = plt_entry->symbol;
4636 /* Nullify the patch */
4637 patch_info->type = MONO_PATCH_INFO_NONE;
4638 plt_entry->jit_used = TRUE;
4645 arch_emit_direct_call (acfg, direct_call_target, external_call, &call_size);
4650 got_slot = get_got_offset (acfg, patch_info);
4652 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4659 #endif /* MONO_ARCH_AOT_SUPPORTED */
4662 /* Find next patch */
4664 for (pindex = start_index; pindex < patches->len; ++pindex) {
4665 patch_info = g_ptr_array_index (patches, pindex);
4666 if (patch_info->ip.i >= i)
4670 /* Try to emit multiple bytes at once */
4671 if (pindex < patches->len && patch_info->ip.i > i) {
4674 for (limit = i + 1; limit < patch_info->ip.i; ++limit) {
4675 if (locs && locs [limit])
4679 emit_bytes (acfg, code + i, limit - i);
4682 emit_bytes (acfg, code + i, 1);
4693 * Modify SYMBOL so it only includes characters permissible in symbols.
4696 sanitize_symbol (char *symbol)
4698 int i, len = strlen (symbol);
4700 for (i = 0; i < len; ++i)
4701 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4706 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4708 char *name1, *name2, *cached;
4709 int i, j, len, count;
4712 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4713 if (!prefix || !*prefix)
4717 name1 = mono_method_full_name (method, TRUE);
4718 len = strlen (name1);
4719 name2 = malloc (strlen (prefix) + len + 16);
4720 memcpy (name2, prefix, strlen (prefix));
4721 j = strlen (prefix);
4722 for (i = 0; i < len; ++i) {
4723 if (isalnum (name1 [i])) {
4724 name2 [j ++] = name1 [i];
4725 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4727 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4730 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4739 while (g_hash_table_lookup (cache, name2)) {
4740 sprintf (name2 + j, "_%d", count);
4744 cached = g_strdup (name2);
4745 g_hash_table_insert (cache, cached, cached);
4751 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4756 char *debug_sym = NULL;
4757 char *symbol = NULL;
4758 int func_alignment = AOT_FUNC_ALIGNMENT;
4759 MonoMethodHeader *header;
4762 method = cfg->orig_method;
4763 code = cfg->native_code;
4764 header = cfg->header;
4766 method_index = get_method_index (acfg, method);
4767 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4770 /* Make the labels local */
4771 emit_section_change (acfg, ".text", 0);
4772 emit_alignment (acfg, func_alignment);
4774 if (acfg->global_symbols && acfg->need_no_dead_strip)
4775 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4777 emit_label (acfg, cfg->asm_symbol);
4779 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4781 * Write a C style symbol for every method, this has two uses:
4782 * - it works on platforms where the dwarf debugging info is not
4784 * - it allows the setting of breakpoints of aot-ed methods.
4786 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4788 if (acfg->need_no_dead_strip)
4789 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4790 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4791 emit_label (acfg, debug_sym);
4794 export_name = g_hash_table_lookup (acfg->export_names, method);
4796 /* Emit a global symbol for the method */
4797 emit_global_inner (acfg, export_name, TRUE);
4798 emit_label (acfg, export_name);
4801 if (cfg->verbose_level > 0)
4802 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4804 acfg->stats.code_size += cfg->code_len;
4806 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4808 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 ()));
4812 if (acfg->aot_opts.write_symbols) {
4813 emit_symbol_size (acfg, debug_sym, ".");
4817 emit_label (acfg, symbol);
4824 * Encode PATCH_INFO into its disk representation.
4827 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4831 switch (patch_info->type) {
4832 case MONO_PATCH_INFO_NONE:
4834 case MONO_PATCH_INFO_IMAGE:
4835 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4837 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4838 case MONO_PATCH_INFO_JIT_TLS_ID:
4839 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4840 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4842 case MONO_PATCH_INFO_METHOD_REL:
4843 encode_value ((gint)patch_info->data.offset, p, &p);
4845 case MONO_PATCH_INFO_SWITCH: {
4846 gpointer *table = (gpointer *)patch_info->data.table->table;
4849 encode_value (patch_info->data.table->table_size, p, &p);
4850 for (k = 0; k < patch_info->data.table->table_size; k++)
4851 encode_value ((int)(gssize)table [k], p, &p);
4854 case MONO_PATCH_INFO_METHODCONST:
4855 case MONO_PATCH_INFO_METHOD:
4856 case MONO_PATCH_INFO_METHOD_JUMP:
4857 case MONO_PATCH_INFO_ICALL_ADDR:
4858 case MONO_PATCH_INFO_METHOD_RGCTX:
4859 encode_method_ref (acfg, patch_info->data.method, p, &p);
4861 case MONO_PATCH_INFO_INTERNAL_METHOD:
4862 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4863 guint32 len = strlen (patch_info->data.name);
4865 encode_value (len, p, &p);
4867 memcpy (p, patch_info->data.name, len);
4872 case MONO_PATCH_INFO_LDSTR: {
4873 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4874 guint32 token = patch_info->data.token->token;
4875 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4876 encode_value (image_index, p, &p);
4877 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4880 case MONO_PATCH_INFO_RVA:
4881 case MONO_PATCH_INFO_DECLSEC:
4882 case MONO_PATCH_INFO_LDTOKEN:
4883 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4884 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4885 encode_value (patch_info->data.token->token, p, &p);
4886 encode_value (patch_info->data.token->has_context, p, &p);
4887 if (patch_info->data.token->has_context)
4888 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4890 case MONO_PATCH_INFO_EXC_NAME: {
4891 MonoClass *ex_class;
4894 mono_class_from_name (mono_defaults.exception_class->image,
4895 "System", patch_info->data.target);
4896 g_assert (ex_class);
4897 encode_klass_ref (acfg, ex_class, p, &p);
4900 case MONO_PATCH_INFO_R4:
4901 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4903 case MONO_PATCH_INFO_R8:
4904 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4905 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4907 case MONO_PATCH_INFO_VTABLE:
4908 case MONO_PATCH_INFO_CLASS:
4909 case MONO_PATCH_INFO_IID:
4910 case MONO_PATCH_INFO_ADJUSTED_IID:
4911 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4913 case MONO_PATCH_INFO_CLASS_INIT:
4914 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4915 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4917 case MONO_PATCH_INFO_FIELD:
4918 case MONO_PATCH_INFO_SFLDA:
4919 encode_field_info (acfg, patch_info->data.field, p, &p);
4921 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4923 case MONO_PATCH_INFO_RGCTX_FETCH: {
4924 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4929 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4930 * reference the same method, so encode the method only once.
4932 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4934 buf2 = g_malloc (1024);
4937 encode_method_ref (acfg, entry->method, p2, &p2);
4938 g_assert (p2 - buf2 < 1024);
4940 offset = add_to_blob (acfg, buf2, p2 - buf2);
4943 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4948 encode_value (offset, p, &p);
4949 g_assert ((int)entry->info_type < 256);
4950 g_assert (entry->data->type < 256);
4951 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4952 encode_patch (acfg, entry->data, p, &p);
4955 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4956 case MONO_PATCH_INFO_MONITOR_ENTER:
4957 case MONO_PATCH_INFO_MONITOR_EXIT:
4958 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4960 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4961 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4962 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4964 case MONO_PATCH_INFO_SIGNATURE:
4965 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4967 case MONO_PATCH_INFO_TLS_OFFSET:
4968 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
4970 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4971 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4972 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4974 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
4975 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
4978 encode_method_ref (acfg, info->method, p, &p);
4979 encode_value (info->entries->len, p, &p);
4980 for (i = 0; i < info->entries->len; ++i) {
4981 MonoRuntimeGenericContextInfoTemplate *template = g_ptr_array_index (info->entries, i);
4983 encode_value (template->info_type, p, &p);
4984 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
4985 case MONO_PATCH_INFO_CLASS:
4986 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
4988 case MONO_PATCH_INFO_FIELD:
4989 encode_field_info (acfg, template->data, p, &p);
4992 g_assert_not_reached ();
4999 g_warning ("unable to handle jump info %d", patch_info->type);
5000 g_assert_not_reached ();
5007 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5010 guint32 pindex, offset;
5011 MonoJumpInfo *patch_info;
5013 encode_value (n_patches, p, &p);
5015 for (pindex = 0; pindex < patches->len; ++pindex) {
5016 patch_info = g_ptr_array_index (patches, pindex);
5018 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5022 offset = get_got_offset (acfg, patch_info);
5023 encode_value (offset, p, &p);
5030 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5034 int pindex, buf_size, n_patches;
5036 MonoJumpInfo *patch_info;
5037 MonoMethodHeader *header;
5038 guint32 method_index;
5040 guint32 first_got_offset;
5042 method = cfg->orig_method;
5043 header = mono_method_get_header (method);
5045 method_index = get_method_index (acfg, method);
5047 /* Sort relocations */
5048 patches = g_ptr_array_new ();
5049 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5050 g_ptr_array_add (patches, patch_info);
5051 g_ptr_array_sort (patches, compare_patches);
5053 first_got_offset = acfg->cfgs [method_index]->got_offset;
5055 /**********************/
5056 /* Encode method info */
5057 /**********************/
5059 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5060 p = buf = g_malloc (buf_size);
5062 if (mono_class_get_cctor (method->klass))
5063 encode_klass_ref (acfg, method->klass, p, &p);
5065 /* Not needed when loading the method */
5066 encode_value (0, p, &p);
5069 if (cfg->opt & MONO_OPT_SHARED) {
5070 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5071 for (l = cfg->ldstr_list; l; l = l->next) {
5072 encode_value ((long)l->data, p, &p);
5076 /* Used only in shared mode */
5077 g_assert (!cfg->ldstr_list);
5080 for (pindex = 0; pindex < patches->len; ++pindex) {
5081 patch_info = g_ptr_array_index (patches, pindex);
5083 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5084 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5085 patch_info->type = MONO_PATCH_INFO_NONE;
5090 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5091 /* Stored in a GOT slot initialized at module load time */
5092 patch_info->type = MONO_PATCH_INFO_NONE;
5096 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5097 /* Stored in a GOT slot initialized at module load time */
5098 patch_info->type = MONO_PATCH_INFO_NONE;
5102 if (is_plt_patch (patch_info)) {
5103 /* Calls are made through the PLT */
5104 patch_info->type = MONO_PATCH_INFO_NONE;
5112 g_assert (cfg->has_got_slots);
5114 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5116 acfg->stats.info_size += p - buf;
5118 g_assert (p - buf < buf_size);
5120 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5125 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5127 guint32 cache_index;
5130 /* Reuse the unwind module to canonize and store unwind info entries */
5131 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5133 /* Use +/- 1 to distinguish 0s from missing entries */
5134 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5142 * It would be easier to use assembler symbols, but the caller needs an
5145 offset = acfg->unwind_info_offset;
5146 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5147 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5150 encode_value (encoded_len, p, &p);
5152 acfg->unwind_info_offset += encoded_len + (p - buf);
5158 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5161 int i, k, buf_size, method_index;
5162 guint32 debug_info_size;
5164 MonoMethodHeader *header;
5165 guint8 *p, *buf, *debug_info;
5166 MonoJitInfo *jinfo = cfg->jit_info;
5168 gboolean use_unwind_ops = FALSE;
5169 MonoSeqPointInfo *seq_points;
5171 method = cfg->orig_method;
5172 code = cfg->native_code;
5173 header = cfg->header;
5175 method_index = get_method_index (acfg, method);
5177 if (!acfg->aot_opts.nodebug) {
5178 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5181 debug_info_size = 0;
5184 seq_points = cfg->seq_point_info;
5186 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
5187 p = buf = g_malloc (buf_size);
5189 #ifdef MONO_ARCH_HAVE_XP_UNWIND
5190 use_unwind_ops = cfg->unwind_ops != NULL;
5193 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);
5195 encode_value (flags, p, &p);
5197 if (use_unwind_ops) {
5198 guint32 encoded_len;
5202 * This is a duplicate of the data in the .debug_frame section, but that
5203 * section cannot be accessed using the dl interface.
5205 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5206 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5209 encode_value (jinfo->used_regs, p, &p);
5212 /*Encode the number of holes before the number of clauses to make decoding easier*/
5213 if (jinfo->has_try_block_holes) {
5214 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5215 encode_value (table->num_holes, p, &p);
5218 /* Exception table */
5219 if (cfg->compile_llvm) {
5221 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5222 * since the information is only available to llc. Instead, we let llc save the data
5223 * into the LSDA, and read it from there at runtime.
5225 /* The assembly might be CIL stripped so emit the data ourselves */
5226 if (header->num_clauses)
5227 encode_value (header->num_clauses, p, &p);
5229 for (k = 0; k < header->num_clauses; ++k) {
5230 MonoExceptionClause *clause;
5232 clause = &header->clauses [k];
5234 encode_value (clause->flags, p, &p);
5235 if (clause->data.catch_class) {
5236 encode_value (1, p, &p);
5237 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5239 encode_value (0, p, &p);
5242 /* Emit a list of nesting clauses */
5243 for (i = 0; i < header->num_clauses; ++i) {
5245 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5247 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5249 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5250 encode_value (i, p, &p);
5252 encode_value (-1, p, &p);
5255 if (jinfo->num_clauses)
5256 encode_value (jinfo->num_clauses, p, &p);
5258 for (k = 0; k < jinfo->num_clauses; ++k) {
5259 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5261 encode_value (ei->flags, p, &p);
5262 encode_value (ei->exvar_offset, p, &p);
5264 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5265 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5267 if (ei->data.catch_class) {
5271 buf2 = g_malloc (4096);
5273 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5275 g_assert (len < 4096);
5276 encode_value (len, p, &p);
5277 memcpy (p, buf2, len);
5281 encode_value (0, p, &p);
5285 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5286 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5287 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5291 if (jinfo->has_try_block_holes) {
5292 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5293 for (i = 0; i < table->num_holes; ++i) {
5294 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5295 encode_value (hole->clause, p, &p);
5296 encode_value (hole->length, p, &p);
5297 encode_value (hole->offset, p, &p);
5301 if (jinfo->has_arch_eh_info) {
5302 MonoArchEHJitInfo *eh_info;
5304 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5305 encode_value (eh_info->stack_size, p, &p);
5308 if (jinfo->has_generic_jit_info) {
5309 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5310 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5316 encode_value (gi->nlocs, p, &p);
5318 for (i = 0; i < gi->nlocs; ++i) {
5319 MonoDwarfLocListEntry *entry = &gi->locations [i];
5321 encode_value (entry->is_reg ? 1 : 0, p, &p);
5322 encode_value (entry->reg, p, &p);
5324 encode_value (entry->offset, p, &p);
5326 g_assert (entry->from == 0);
5328 encode_value (entry->from, p, &p);
5329 encode_value (entry->to, p, &p);
5332 if (!cfg->compile_llvm) {
5333 encode_value (gi->has_this ? 1 : 0, p, &p);
5334 encode_value (gi->this_reg, p, &p);
5335 encode_value (gi->this_offset, p, &p);
5340 * Need to encode jinfo->method too, since it is not equal to 'method'
5341 * when using generic sharing.
5343 buf2 = g_malloc (4096);
5345 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5347 g_assert (len < 4096);
5348 encode_value (len, p, &p);
5349 memcpy (p, buf2, len);
5353 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5354 MonoMethodInflated *inflated;
5355 MonoGenericContext *context;
5356 MonoGenericInst *inst;
5358 g_assert (jinfo->d.method->is_inflated);
5359 inflated = (MonoMethodInflated*)jinfo->d.method;
5360 context = &inflated->context;
5362 encode_value (1, p, &p);
5363 if (context->class_inst) {
5364 inst = context->class_inst;
5366 encode_value (inst->type_argc, p, &p);
5367 for (i = 0; i < inst->type_argc; ++i)
5368 encode_value (gsctx->var_is_vt [i], p, &p);
5370 encode_value (0, p, &p);
5372 if (context->method_inst) {
5373 inst = context->method_inst;
5375 encode_value (inst->type_argc, p, &p);
5376 for (i = 0; i < inst->type_argc; ++i)
5377 encode_value (gsctx->mvar_is_vt [i], p, &p);
5379 encode_value (0, p, &p);
5382 encode_value (0, p, &p);
5387 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5389 encode_value (seq_points->len, p, &p);
5390 last_il_offset = last_native_offset = 0;
5391 for (i = 0; i < seq_points->len; ++i) {
5392 SeqPoint *sp = &seq_points->seq_points [i];
5393 il_offset = sp->il_offset;
5394 native_offset = sp->native_offset;
5395 encode_value (il_offset - last_il_offset, p, &p);
5396 encode_value (native_offset - last_native_offset, p, &p);
5397 last_il_offset = il_offset;
5398 last_native_offset = native_offset;
5400 encode_value (sp->flags, p, &p);
5401 encode_value (sp->next_len, p, &p);
5402 for (j = 0; j < sp->next_len; ++j)
5403 encode_value (sp->next [j], p, &p);
5407 g_assert (debug_info_size < buf_size);
5409 encode_value (debug_info_size, p, &p);
5410 if (debug_info_size) {
5411 memcpy (p, debug_info, debug_info_size);
5412 p += debug_info_size;
5413 g_free (debug_info);
5418 encode_value (cfg->gc_map_size, p, &p);
5419 /* The GC map requires 4 bytes of alignment */
5420 while ((gsize)p % 4)
5422 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5423 p += cfg->gc_map_size;
5426 acfg->stats.ex_info_size += p - buf;
5428 g_assert (p - buf < buf_size);
5431 /* The GC Map requires 4 byte alignment */
5432 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5437 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5439 MonoClass *klass = mono_class_get (acfg->image, token);
5441 int i, buf_size, res;
5442 gboolean no_special_static, cant_encode;
5443 gpointer iter = NULL;
5446 mono_loader_clear_error ();
5450 p = buf = g_malloc (buf_size);
5452 /* Mark as unusable */
5453 encode_value (-1, p, &p);
5455 res = add_to_blob (acfg, buf, p - buf);
5461 buf_size = 10240 + (klass->vtable_size * 16);
5462 p = buf = g_malloc (buf_size);
5466 mono_class_init (klass);
5468 mono_class_get_nested_types (klass, &iter);
5469 g_assert (klass->nested_classes_inited);
5471 mono_class_setup_vtable (klass);
5474 * Emit all the information which is required for creating vtables so
5475 * the runtime does not need to create the MonoMethod structures which
5476 * take up a lot of space.
5479 no_special_static = !mono_class_has_special_static_fields (klass);
5481 /* Check whenever we have enough info to encode the vtable */
5482 cant_encode = FALSE;
5483 for (i = 0; i < klass->vtable_size; ++i) {
5484 MonoMethod *cm = klass->vtable [i];
5486 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5490 mono_class_has_finalizer (klass);
5492 if (klass->generic_container || cant_encode) {
5493 encode_value (-1, p, &p);
5495 encode_value (klass->vtable_size, p, &p);
5496 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);
5497 if (klass->has_cctor)
5498 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5499 if (klass->has_finalize)
5500 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5502 encode_value (klass->instance_size, p, &p);
5503 encode_value (mono_class_data_size (klass), p, &p);
5504 encode_value (klass->packing_size, p, &p);
5505 encode_value (klass->min_align, p, &p);
5507 for (i = 0; i < klass->vtable_size; ++i) {
5508 MonoMethod *cm = klass->vtable [i];
5511 encode_method_ref (acfg, cm, p, &p);
5513 encode_value (0, p, &p);
5517 acfg->stats.class_info_size += p - buf;
5519 g_assert (p - buf < buf_size);
5520 res = add_to_blob (acfg, buf, p - buf);
5527 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5529 char *debug_sym = NULL;
5532 case MONO_PATCH_INFO_METHOD:
5533 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5535 case MONO_PATCH_INFO_INTERNAL_METHOD:
5536 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5538 case MONO_PATCH_INFO_CLASS_INIT:
5539 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5540 sanitize_symbol (debug_sym);
5542 case MONO_PATCH_INFO_RGCTX_FETCH:
5543 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5545 case MONO_PATCH_INFO_ICALL_ADDR: {
5546 char *s = get_debug_sym (ji->data.method, "", cache);
5548 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5552 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5553 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5555 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5556 debug_sym = g_strdup_printf ("plt__generic_class_init");
5566 * Calls made from AOTed code are routed through a table of jumps similar to the
5567 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5568 * control to the AOT runtime through a trampoline.
5571 emit_plt (MonoAotCompile *acfg)
5577 sprintf (symbol, "plt");
5579 emit_section_change (acfg, ".text", 0);
5580 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5581 emit_label (acfg, symbol);
5582 emit_label (acfg, acfg->plt_symbol);
5584 for (i = 0; i < acfg->plt_offset; ++i) {
5585 char *debug_sym = NULL;
5586 MonoPltEntry *plt_entry = NULL;
5591 * The first plt entry is unused.
5595 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5600 * If the target is directly callable, alias the plt symbol to point to
5602 * FIXME: Use this to simplify emit_and_reloc_code ().
5603 * FIXME: Avoid the got slot.
5604 * FIXME: Add support to the binary writer.
5606 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5607 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5610 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5611 /* LLVM calls the PLT entries using bl, so emit a stub */
5612 emit_set_thumb_mode (acfg);
5613 fprintf (acfg->fp, "\n.thumb_func\n");
5614 emit_label (acfg, plt_entry->llvm_symbol);
5615 fprintf (acfg->fp, "bx pc\n");
5616 fprintf (acfg->fp, "nop\n");
5617 emit_set_arm_mode (acfg);
5618 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5620 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5627 debug_sym = plt_entry->debug_sym;
5629 if (acfg->thumb_mixed && !plt_entry->jit_used)
5630 /* Emit only a thumb version */
5633 if (acfg->llvm && !acfg->thumb_mixed)
5634 emit_label (acfg, plt_entry->llvm_symbol);
5637 if (acfg->need_no_dead_strip) {
5638 emit_unset_mode (acfg);
5639 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5641 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5642 emit_label (acfg, debug_sym);
5645 emit_label (acfg, plt_entry->symbol);
5647 arch_emit_plt_entry (acfg, i);
5650 emit_symbol_size (acfg, debug_sym, ".");
5653 if (acfg->thumb_mixed) {
5654 /* Make sure the ARM symbols don't alias the thumb ones */
5655 emit_zero_bytes (acfg, 16);
5658 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5661 for (i = 0; i < acfg->plt_offset; ++i) {
5662 char *debug_sym = NULL;
5663 MonoPltEntry *plt_entry = NULL;
5669 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5672 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5675 /* Skip plt entries not actually called by LLVM code */
5676 if (!plt_entry->llvm_used)
5679 if (acfg->aot_opts.write_symbols) {
5680 if (plt_entry->debug_sym)
5681 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5685 #if defined(TARGET_MACH)
5686 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5687 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5689 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5690 emit_label (acfg, debug_sym);
5692 fprintf (acfg->fp, "\n.thumb_func\n");
5694 emit_label (acfg, plt_entry->llvm_symbol);
5696 arch_emit_llvm_plt_entry (acfg, i);
5699 emit_symbol_size (acfg, debug_sym, ".");
5705 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5707 sprintf (symbol, "plt_end");
5708 emit_label (acfg, symbol);
5712 * emit_trampoline_full:
5714 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5715 * create_jit_info_for_trampoline ().
5717 static G_GNUC_UNUSED void
5718 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5720 char start_symbol [256];
5721 char end_symbol [256];
5723 guint32 buf_size, info_offset;
5724 MonoJumpInfo *patch_info;
5735 code_size = info->code_size;
5737 unwind_ops = info->unwind_ops;
5739 #ifdef __native_client_codegen__
5740 mono_nacl_fix_patches (code, ji);
5745 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5747 emit_section_change (acfg, ".text", 0);
5748 emit_global (acfg, start_symbol, TRUE);
5749 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5750 emit_label (acfg, start_symbol);
5752 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5753 emit_label (acfg, symbol);
5756 * The code should access everything through the GOT, so we pass
5759 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5761 emit_symbol_size (acfg, start_symbol, ".");
5764 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5765 emit_label (acfg, end_symbol);
5770 /* Sort relocations */
5771 patches = g_ptr_array_new ();
5772 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5773 if (patch_info->type != MONO_PATCH_INFO_NONE)
5774 g_ptr_array_add (patches, patch_info);
5775 g_ptr_array_sort (patches, compare_patches);
5777 buf_size = patches->len * 128 + 128;
5778 buf = g_malloc (buf_size);
5781 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5782 g_assert (p - buf < buf_size);
5784 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5786 info_offset = add_to_blob (acfg, buf, p - buf);
5788 emit_section_change (acfg, RODATA_SECT, 0);
5789 emit_global (acfg, symbol, FALSE);
5790 emit_label (acfg, symbol);
5792 emit_int32 (acfg, info_offset);
5796 guint32 encoded_len;
5800 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5802 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5803 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5806 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5807 emit_int32 (acfg, uw_offset);
5810 /* Emit debug info */
5814 sprintf (symbol, "%s", name);
5815 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5818 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5822 static G_GNUC_UNUSED void
5823 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5825 emit_trampoline_full (acfg, got_offset, info, FALSE);
5829 emit_trampolines (MonoAotCompile *acfg)
5832 char end_symbol [256];
5833 int i, tramp_got_offset;
5834 MonoAotTrampoline ntype;
5835 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5839 if (!acfg->aot_opts.full_aot)
5842 g_assert (acfg->image->assembly);
5844 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5845 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5846 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5847 MonoTrampInfo *info;
5850 * Emit the generic trampolines.
5852 * We could save some code by treating the generic trampolines as a wrapper
5853 * method, but that approach has its own complexities, so we choose the simpler
5856 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5857 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5858 #ifdef DISABLE_REMOTING
5859 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5862 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5863 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5866 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5867 emit_trampoline (acfg, acfg->got_offset, info);
5870 mono_arch_get_nullified_class_init_trampoline (&info);
5871 emit_trampoline (acfg, acfg->got_offset, info);
5872 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5873 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5874 emit_trampoline (acfg, acfg->got_offset, info);
5875 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5876 emit_trampoline (acfg, acfg->got_offset, info);
5879 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5880 emit_trampoline (acfg, acfg->got_offset, info);
5882 /* Emit the exception related code pieces */
5883 mono_arch_get_restore_context (&info, TRUE);
5884 emit_trampoline (acfg, acfg->got_offset, info);
5885 mono_arch_get_call_filter (&info, TRUE);
5886 emit_trampoline (acfg, acfg->got_offset, info);
5887 mono_arch_get_throw_exception (&info, TRUE);
5888 emit_trampoline (acfg, acfg->got_offset, info);
5889 mono_arch_get_rethrow_exception (&info, TRUE);
5890 emit_trampoline (acfg, acfg->got_offset, info);
5891 mono_arch_get_throw_corlib_exception (&info, TRUE);
5892 emit_trampoline (acfg, acfg->got_offset, info);
5894 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5895 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5897 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5899 /* Create a separate out trampoline for more information in stack traces */
5900 info->name = g_strdup ("gsharedvt_out_trampoline");
5901 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5905 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5907 GSList *l = mono_arch_get_trampolines (TRUE);
5910 MonoTrampInfo *info = l->data;
5912 emit_trampoline (acfg, acfg->got_offset, info);
5918 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5921 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5922 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5923 emit_trampoline (acfg, acfg->got_offset, info);
5925 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5926 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5927 emit_trampoline (acfg, acfg->got_offset, info);
5930 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5931 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5932 emit_trampoline (acfg, acfg->got_offset, info);
5938 /* delegate_invoke_impl trampolines */
5939 l = mono_arch_get_delegate_invoke_impls ();
5941 MonoTrampInfo *info = l->data;
5943 emit_trampoline (acfg, acfg->got_offset, info);
5948 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5950 /* Emit trampolines which are numerous */
5953 * These include the following:
5954 * - specific trampolines
5955 * - static rgctx invoke trampolines
5957 * These trampolines have the same code, they are parameterized by GOT
5959 * They are defined in this file, in the arch_... routines instead of
5960 * in tramp-<ARCH>.c, since it is easier to do it this way.
5964 * When running in aot-only mode, we can't create specific trampolines at
5965 * runtime, so we create a few, and save them in the AOT file.
5966 * Normal trampolines embed their argument as a literal inside the
5967 * trampoline code, we can't do that here, so instead we embed an offset
5968 * which needs to be added to the trampoline address to get the address of
5969 * the GOT slot which contains the argument value.
5970 * The generated trampolines jump to the generic trampolines using another
5971 * GOT slot, which will be setup by the AOT loader to point to the
5972 * generic trampoline code of the given type.
5976 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5980 emit_section_change (acfg, ".text", 0);
5982 tramp_got_offset = acfg->got_offset;
5984 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5986 case MONO_AOT_TRAMP_SPECIFIC:
5987 sprintf (symbol, "specific_trampolines");
5989 case MONO_AOT_TRAMP_STATIC_RGCTX:
5990 sprintf (symbol, "static_rgctx_trampolines");
5992 case MONO_AOT_TRAMP_IMT_THUNK:
5993 sprintf (symbol, "imt_thunks");
5995 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5996 sprintf (symbol, "gsharedvt_arg_trampolines");
5999 g_assert_not_reached ();
6002 sprintf (end_symbol, "%s_e", symbol);
6004 if (acfg->aot_opts.write_symbols)
6005 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6007 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6008 emit_label (acfg, symbol);
6010 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6012 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6016 case MONO_AOT_TRAMP_SPECIFIC:
6017 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6018 tramp_got_offset += 2;
6020 case MONO_AOT_TRAMP_STATIC_RGCTX:
6021 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6022 tramp_got_offset += 2;
6024 case MONO_AOT_TRAMP_IMT_THUNK:
6025 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6026 tramp_got_offset += 1;
6028 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6029 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6030 tramp_got_offset += 2;
6033 g_assert_not_reached ();
6035 #ifdef __native_client_codegen__
6036 /* align to avoid 32-byte boundary crossings */
6037 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6040 if (!acfg->trampoline_size [ntype]) {
6041 g_assert (tramp_size);
6042 acfg->trampoline_size [ntype] = tramp_size;
6046 emit_label (acfg, end_symbol);
6049 arch_emit_specific_trampoline_pages (acfg);
6051 /* Reserve some entries at the end of the GOT for our use */
6052 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6055 acfg->got_offset += acfg->num_trampoline_got_entries;
6059 str_begins_with (const char *str1, const char *str2)
6061 int len = strlen (str2);
6062 return strncmp (str1, str2, len) == 0;
6066 mono_aot_readonly_field_override (MonoClassField *field)
6069 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6070 char *p = rdv->name;
6072 len = strlen (field->parent->name_space);
6073 if (strncmp (p, field->parent->name_space, len))
6078 len = strlen (field->parent->name);
6079 if (strncmp (p, field->parent->name, len))
6084 if (strcmp (p, field->name))
6086 switch (rdv->type) {
6088 return &rdv->value.i1;
6090 return &rdv->value.i2;
6092 return &rdv->value.i4;
6101 add_readonly_value (MonoAotOptions *opts, const char *val)
6106 /* the format of val is:
6107 * namespace.typename.fieldname=type/value
6108 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6110 fval = strrchr (val, '/');
6112 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6115 tval = strrchr (val, '=');
6117 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6120 rdv = g_new0 (ReadOnlyValue, 1);
6121 rdv->name = g_malloc0 (tval - val + 1);
6122 memcpy (rdv->name, val, tval - val);
6125 if (strncmp (tval, "i1", 2) == 0) {
6126 rdv->value.i1 = atoi (fval);
6127 rdv->type = MONO_TYPE_I1;
6128 } else if (strncmp (tval, "i2", 2) == 0) {
6129 rdv->value.i2 = atoi (fval);
6130 rdv->type = MONO_TYPE_I2;
6131 } else if (strncmp (tval, "i4", 2) == 0) {
6132 rdv->value.i4 = atoi (fval);
6133 rdv->type = MONO_TYPE_I4;
6135 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6138 rdv->next = readonly_values;
6139 readonly_values = rdv;
6143 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6145 gchar **args, **ptr;
6147 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6148 for (ptr = args; ptr && *ptr; ptr ++) {
6149 const char *arg = *ptr;
6151 if (str_begins_with (arg, "outfile=")) {
6152 opts->outfile = g_strdup (arg + strlen ("outfile="));
6153 } else if (str_begins_with (arg, "save-temps")) {
6154 opts->save_temps = TRUE;
6155 } else if (str_begins_with (arg, "keep-temps")) {
6156 opts->save_temps = TRUE;
6157 } else if (str_begins_with (arg, "write-symbols")) {
6158 opts->write_symbols = TRUE;
6159 } else if (str_begins_with (arg, "no-write-symbols")) {
6160 opts->write_symbols = FALSE;
6161 } else if (str_begins_with (arg, "metadata-only")) {
6162 opts->metadata_only = TRUE;
6163 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6164 opts->bind_to_runtime_version = TRUE;
6165 } else if (str_begins_with (arg, "full")) {
6166 opts->full_aot = TRUE;
6167 } else if (str_begins_with (arg, "threads=")) {
6168 opts->nthreads = atoi (arg + strlen ("threads="));
6169 } else if (str_begins_with (arg, "static")) {
6170 opts->static_link = TRUE;
6171 opts->no_dlsym = TRUE;
6172 } else if (str_begins_with (arg, "asmonly")) {
6173 opts->asm_only = TRUE;
6174 } else if (str_begins_with (arg, "asmwriter")) {
6175 opts->asm_writer = TRUE;
6176 } else if (str_begins_with (arg, "nodebug")) {
6177 opts->nodebug = TRUE;
6178 } else if (str_begins_with (arg, "dwarfdebug")) {
6179 opts->dwarf_debug = TRUE;
6180 } else if (str_begins_with (arg, "nopagetrampolines")) {
6181 opts->use_trampolines_page = FALSE;
6182 } else if (str_begins_with (arg, "ntrampolines=")) {
6183 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6184 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6185 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6186 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6187 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6188 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6189 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6190 } else if (str_begins_with (arg, "autoreg")) {
6191 opts->autoreg = TRUE;
6192 } else if (str_begins_with (arg, "tool-prefix=")) {
6193 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6194 } else if (str_begins_with (arg, "soft-debug")) {
6195 opts->soft_debug = TRUE;
6196 } else if (str_begins_with (arg, "direct-pinvoke")) {
6197 opts->direct_pinvoke = TRUE;
6198 } else if (str_begins_with (arg, "direct-icalls")) {
6199 opts->direct_icalls = TRUE;
6200 #if defined(TARGET_ARM)
6201 } else if (str_begins_with (arg, "iphone-abi")) {
6202 // older full-aot users did depend on this.
6204 } else if (str_begins_with (arg, "no-direct-calls")) {
6205 opts->no_direct_calls = TRUE;
6206 } else if (str_begins_with (arg, "print-skipped")) {
6207 opts->print_skipped_methods = TRUE;
6208 } else if (str_begins_with (arg, "stats")) {
6210 } else if (str_begins_with (arg, "no-instances")) {
6211 opts->no_instances = TRUE;
6212 } else if (str_begins_with (arg, "log-generics")) {
6213 opts->log_generics = TRUE;
6214 } else if (str_begins_with (arg, "mtriple=")) {
6215 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6216 } else if (str_begins_with (arg, "llvm-path=")) {
6217 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6218 } else if (str_begins_with (arg, "readonly-value=")) {
6219 add_readonly_value (opts, arg + strlen ("readonly-value="));
6220 } else if (str_begins_with (arg, "info")) {
6221 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6223 } else if (str_begins_with (arg, "gc-maps")) {
6224 mini_gc_enable_gc_maps_for_aot ();
6225 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6226 printf ("Supported options for --aot:\n");
6227 printf (" outfile=\n");
6228 printf (" save-temps\n");
6229 printf (" keep-temps\n");
6230 printf (" write-symbols\n");
6231 printf (" metadata-only\n");
6232 printf (" bind-to-runtime-version\n");
6234 printf (" threads=\n");
6235 printf (" static\n");
6236 printf (" asmonly\n");
6237 printf (" asmwriter\n");
6238 printf (" nodebug\n");
6239 printf (" dwarfdebug\n");
6240 printf (" ntrampolines=\n");
6241 printf (" nrgctx-trampolines=\n");
6242 printf (" nimt-trampolines=\n");
6243 printf (" ngsharedvt-trampolines=\n");
6244 printf (" autoreg\n");
6245 printf (" tool-prefix=\n");
6246 printf (" readonly-value=\n");
6247 printf (" soft-debug\n");
6248 printf (" gc-maps\n");
6249 printf (" print-skipped\n");
6250 printf (" no-instances\n");
6251 printf (" stats\n");
6253 printf (" help/?\n");
6256 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6261 if (opts->use_trampolines_page) {
6262 opts->ntrampolines = 0;
6263 opts->nrgctx_trampolines = 0;
6264 opts->nimt_trampolines = 0;
6265 opts->ngsharedvt_arg_trampolines = 0;
6271 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6273 MonoMethod *method = (MonoMethod*)key;
6274 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6275 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6276 MonoAotCompile *acfg = user_data;
6278 new_ji->image = ji->image;
6279 new_ji->token = ji->token;
6280 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6284 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6286 if (klass->type_token)
6288 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6291 return can_encode_class (acfg, klass->element_class);
6296 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6298 if (method->wrapper_type) {
6299 switch (method->wrapper_type) {
6300 case MONO_WRAPPER_NONE:
6301 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6302 case MONO_WRAPPER_XDOMAIN_INVOKE:
6303 case MONO_WRAPPER_STFLD:
6304 case MONO_WRAPPER_LDFLD:
6305 case MONO_WRAPPER_LDFLDA:
6306 case MONO_WRAPPER_LDFLD_REMOTE:
6307 case MONO_WRAPPER_STFLD_REMOTE:
6308 case MONO_WRAPPER_STELEMREF:
6309 case MONO_WRAPPER_ISINST:
6310 case MONO_WRAPPER_PROXY_ISINST:
6311 case MONO_WRAPPER_ALLOC:
6312 case MONO_WRAPPER_REMOTING_INVOKE:
6313 case MONO_WRAPPER_UNKNOWN:
6314 case MONO_WRAPPER_WRITE_BARRIER:
6315 case MONO_WRAPPER_DELEGATE_INVOKE:
6316 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6317 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6318 case MONO_WRAPPER_SYNCHRONIZED:
6320 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6321 case MONO_WRAPPER_CASTCLASS: {
6322 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6331 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6335 if (!method->token) {
6336 /* The method is part of a constructed type like Int[,].Set (). */
6337 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6338 if (method->klass->rank)
6348 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6350 switch (patch_info->type) {
6351 case MONO_PATCH_INFO_METHOD:
6352 case MONO_PATCH_INFO_METHODCONST: {
6353 MonoMethod *method = patch_info->data.method;
6355 return can_encode_method (acfg, method);
6357 case MONO_PATCH_INFO_VTABLE:
6358 case MONO_PATCH_INFO_CLASS_INIT:
6359 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
6360 case MONO_PATCH_INFO_CLASS:
6361 case MONO_PATCH_INFO_IID:
6362 case MONO_PATCH_INFO_ADJUSTED_IID:
6363 if (!can_encode_class (acfg, patch_info->data.klass)) {
6364 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6368 case MONO_PATCH_INFO_RGCTX_FETCH: {
6369 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6371 if (!can_encode_method (acfg, entry->method))
6373 if (!can_encode_patch (acfg, entry->data))
6387 * AOT compile a given method.
6388 * This function might be called by multiple threads, so it must be thread-safe.
6391 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6394 MonoJumpInfo *patch_info;
6397 MonoMethod *wrapped;
6399 if (acfg->aot_opts.metadata_only)
6402 mono_acfg_lock (acfg);
6403 index = get_method_index (acfg, method);
6404 mono_acfg_unlock (acfg);
6406 /* fixme: maybe we can also precompile wrapper methods */
6407 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6408 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6409 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6410 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6414 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6417 wrapped = mono_marshal_method_from_wrapper (method);
6418 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6419 // FIXME: The wrapper should be generic too, but it is not
6422 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6425 InterlockedIncrement (&acfg->stats.mcount);
6428 if (method->is_generic || method->klass->generic_container) {
6429 InterlockedIncrement (&acfg->stats.genericcount);
6434 //acfg->aot_opts.print_skipped_methods = TRUE;
6437 * Since these methods are the only ones which are compiled with
6438 * AOT support, and they are not used by runtime startup/shutdown code,
6439 * the runtime will not see AOT methods during AOT compilation,so it
6440 * does not need to support them by creating a fake GOT etc.
6442 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6443 mono_loader_clear_error ();
6445 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6446 if (acfg->aot_opts.print_skipped_methods)
6447 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6448 InterlockedIncrement (&acfg->stats.genericcount);
6451 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6452 if (acfg->aot_opts.print_skipped_methods)
6453 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6454 /* Let the exception happen at runtime */
6458 if (cfg->disable_aot) {
6459 if (acfg->aot_opts.print_skipped_methods)
6460 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6461 InterlockedIncrement (&acfg->stats.ocount);
6462 mono_destroy_compile (cfg);
6465 cfg->method_index = index;
6467 /* Nullify patches which need no aot processing */
6468 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6469 switch (patch_info->type) {
6470 case MONO_PATCH_INFO_LABEL:
6471 case MONO_PATCH_INFO_BB:
6472 patch_info->type = MONO_PATCH_INFO_NONE;
6479 /* Collect method->token associations from the cfg */
6480 mono_acfg_lock (acfg);
6481 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6482 mono_acfg_unlock (acfg);
6485 * Check for absolute addresses.
6488 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6489 switch (patch_info->type) {
6490 case MONO_PATCH_INFO_ABS:
6491 /* unable to handle this */
6500 if (acfg->aot_opts.print_skipped_methods)
6501 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6502 InterlockedIncrement (&acfg->stats.abscount);
6503 mono_destroy_compile (cfg);
6507 /* Lock for the rest of the code */
6508 mono_acfg_lock (acfg);
6511 * Check for methods/klasses we can't encode.
6514 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6515 if (!can_encode_patch (acfg, patch_info))
6520 if (acfg->aot_opts.print_skipped_methods)
6521 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6522 acfg->stats.ocount++;
6523 mono_destroy_compile (cfg);
6524 mono_acfg_unlock (acfg);
6528 /* Adds generic instances referenced by this method */
6530 * The depth is used to avoid infinite loops when generic virtual recursion is
6533 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6534 if (!acfg->aot_opts.no_instances && depth < 32) {
6535 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6536 switch (patch_info->type) {
6537 case MONO_PATCH_INFO_METHOD: {
6538 MonoMethod *m = patch_info->data.method;
6539 if (m->is_inflated) {
6540 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6541 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6542 !method_has_type_vars (m)) {
6543 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6544 if (acfg->aot_opts.full_aot)
6545 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6547 add_extra_method_with_depth (acfg, m, depth + 1);
6548 add_types_from_method_header (acfg, m);
6551 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6553 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6554 add_extra_method_with_depth (acfg, m, depth + 1);
6557 case MONO_PATCH_INFO_VTABLE: {
6558 MonoClass *klass = patch_info->data.klass;
6560 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6561 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6564 case MONO_PATCH_INFO_SFLDA: {
6565 MonoClass *klass = patch_info->data.field->parent;
6567 /* The .cctor needs to run at runtime. */
6568 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6569 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6578 /* Determine whenever the method has GOT slots */
6579 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6580 switch (patch_info->type) {
6581 case MONO_PATCH_INFO_GOT_OFFSET:
6582 case MONO_PATCH_INFO_NONE:
6583 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6585 case MONO_PATCH_INFO_IMAGE:
6586 /* The assembly is stored in GOT slot 0 */
6587 if (patch_info->data.image != acfg->image)
6588 cfg->has_got_slots = TRUE;
6591 if (!is_plt_patch (patch_info))
6592 cfg->has_got_slots = TRUE;
6597 if (!cfg->has_got_slots)
6598 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6601 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6603 /* Make a copy of the patch info which is in the mempool */
6605 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6607 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6608 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6611 patches = new_patch_info;
6613 patches_end->next = new_patch_info;
6614 patches_end = new_patch_info;
6616 cfg->patch_info = patches;
6618 /* Make a copy of the unwind info */
6620 GSList *l, *unwind_ops;
6624 for (l = cfg->unwind_ops; l; l = l->next) {
6625 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6626 memcpy (op, l->data, sizeof (MonoUnwindOp));
6627 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6629 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6631 /* Make a copy of the argument/local info */
6633 MonoInst **args, **locals;
6634 MonoMethodSignature *sig;
6635 MonoMethodHeader *header;
6638 sig = mono_method_signature (method);
6639 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6640 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6641 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6642 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6646 header = mono_method_get_header (method);
6647 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6648 for (i = 0; i < header->num_locals; ++i) {
6649 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6650 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6652 cfg->locals = locals;
6655 /* Free some fields used by cfg to conserve memory */
6656 mono_mempool_destroy (cfg->mempool);
6657 cfg->mempool = NULL;
6658 g_free (cfg->varinfo);
6659 cfg->varinfo = NULL;
6663 mono_regstate_free (cfg->rs);
6667 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6669 while (index >= acfg->cfgs_size) {
6670 MonoCompile **new_cfgs;
6673 new_size = acfg->cfgs_size * 2;
6674 new_cfgs = g_new0 (MonoCompile*, new_size);
6675 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6676 g_free (acfg->cfgs);
6677 acfg->cfgs = new_cfgs;
6678 acfg->cfgs_size = new_size;
6680 acfg->cfgs [index] = cfg;
6682 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6685 if (cfg->orig_method->wrapper_type)
6686 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6689 mono_acfg_unlock (acfg);
6691 InterlockedIncrement (&acfg->stats.ccount);
6695 compile_thread_main (gpointer *user_data)
6697 MonoDomain *domain = user_data [0];
6698 MonoAotCompile *acfg = user_data [1];
6699 GPtrArray *methods = user_data [2];
6702 mono_thread_attach (domain);
6704 for (i = 0; i < methods->len; ++i)
6705 compile_method (acfg, g_ptr_array_index (methods, i));
6709 load_profile_files (MonoAotCompile *acfg)
6713 int file_index, res, method_index, i;
6716 GList *unordered, *l;
6721 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6723 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6728 infile = fopen (tmp, "r");
6731 printf ("Using profile data file '%s'\n", tmp);
6736 res = fscanf (infile, "%32s\n", ver);
6737 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6738 printf ("Profile file has wrong version or invalid.\n");
6745 MonoMethodDesc *desc;
6748 if (fgets (name, 1023, infile) == NULL)
6751 /* Kill the newline */
6752 if (strlen (name) > 0)
6753 name [strlen (name) - 1] = '\0';
6755 desc = mono_method_desc_new (name, TRUE);
6757 method = mono_method_desc_search_in_image (desc, acfg->image);
6759 if (method && mono_method_get_token (method)) {
6760 token = mono_method_get_token (method);
6761 method_index = mono_metadata_token_index (token) - 1;
6764 for (i = 0; i < acfg->method_order->len; ++i) {
6765 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6771 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6773 //printf ("No method found matching '%s'.\n", name);
6779 /* Add missing methods */
6781 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6783 for (i = 0; i < acfg->method_order->len; ++i) {
6784 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6790 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6792 unordered = g_list_reverse (unordered);
6793 for (l = unordered; l; l = l->next)
6794 g_ptr_array_add (acfg->method_order, l->data);
6797 /* Used by the LLVM backend */
6799 mono_aot_get_got_offset (MonoJumpInfo *ji)
6801 return get_got_offset (llvm_acfg, ji);
6805 mono_aot_get_method_name (MonoCompile *cfg)
6807 if (llvm_acfg->aot_opts.static_link)
6808 /* Include the assembly name too to avoid duplicate symbol errors */
6809 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6811 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6815 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6817 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6818 MonoPltEntry *plt_entry;
6821 ji->data.target = data;
6823 if (!can_encode_patch (llvm_acfg, ji))
6826 plt_entry = get_plt_entry (llvm_acfg, ji);
6827 plt_entry->llvm_used = TRUE;
6829 #if defined(TARGET_MACH)
6830 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6832 return g_strdup_printf (plt_entry->llvm_symbol);
6837 mono_aot_get_method_index (MonoMethod *method)
6839 g_assert (llvm_acfg);
6840 return get_method_index (llvm_acfg, method);
6844 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6848 mono_acfg_lock (llvm_acfg);
6849 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6850 mono_acfg_unlock (llvm_acfg);
6860 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6864 emit_llvm_file (MonoAotCompile *acfg)
6866 char *command, *opts, *tempbc;
6868 MonoJumpInfo *patch_info;
6871 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6875 /* Compute the final size of the got */
6876 for (i = 0; i < acfg->nmethods; ++i) {
6877 if (acfg->cfgs [i]) {
6878 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6879 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6880 if (!is_plt_patch (patch_info))
6881 get_got_offset (acfg, patch_info);
6883 get_plt_entry (acfg, patch_info);
6889 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6891 if (acfg->aot_opts.full_aot) {
6895 * Need to add the got entries used by the trampolines.
6896 * This is only a conservative approximation.
6898 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6899 /* For the generic + rgctx trampolines */
6900 acfg->final_got_size += 400;
6901 /* For the specific trampolines */
6902 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6903 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6908 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6909 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6913 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6914 * a lot of time, and doesn't seem to save much space.
6915 * The following optimizations cannot be enabled:
6917 * - 'jump-threading' changes our blockaddress references to int constants.
6918 * - 'basiccg' fails because it contains:
6919 * if (CS && !isa<IntrinsicInst>(II)) {
6920 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6921 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6922 * The opt list below was produced by taking the output of:
6923 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6924 * then removing tailcallelim + the global opts, and adding a second gvn.
6926 opts = g_strdup ("-instcombine -simplifycfg");
6927 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
6929 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6930 printf ("Executing opt: %s\n", command);
6931 if (system (command) != 0) {
6937 if (!acfg->llc_args)
6938 acfg->llc_args = g_string_new ("");
6940 /* Verbose asm slows down llc greatly */
6941 g_string_append (acfg->llc_args, " -asm-verbose=false");
6943 if (acfg->aot_opts.mtriple)
6944 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6946 #if defined(TARGET_MACH) && defined(TARGET_ARM)
6947 /* ios requires PIC code now */
6948 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6950 if (llvm_acfg->aot_opts.static_link)
6951 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6953 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6955 unlink (acfg->tmpfname);
6957 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
6959 printf ("Executing llc: %s\n", command);
6961 if (system (command) != 0) {
6968 emit_code (MonoAotCompile *acfg)
6970 int oindex, i, prev_index;
6972 char end_symbol [256];
6974 #if defined(TARGET_POWERPC64)
6975 sprintf (symbol, ".Lgot_addr");
6976 emit_section_change (acfg, ".text", 0);
6977 emit_alignment (acfg, 8);
6978 emit_label (acfg, symbol);
6979 emit_pointer (acfg, acfg->got_symbol);
6983 * This global symbol is used to compute the address of each method using the
6984 * code_offsets array. It is also used to compute the memory ranges occupied by
6985 * AOT code, so it must be equal to the address of the first emitted method.
6987 sprintf (symbol, "methods");
6988 emit_section_change (acfg, ".text", 0);
6989 emit_alignment (acfg, 8);
6991 for (i = 0; i < acfg->nmethods; ++i) {
6992 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6993 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6997 if (i == acfg->nmethods)
6998 /* No LLVM compiled methods */
6999 emit_label (acfg, symbol);
7001 emit_label (acfg, symbol);
7005 * Emit some padding so the local symbol for the first method doesn't have the
7006 * same address as 'methods'.
7008 #if defined(__default_codegen__)
7009 emit_zero_bytes (acfg, 16);
7010 #elif defined(__native_client_codegen__)
7012 const int kPaddingSize = 16;
7013 guint8 pad_buffer[kPaddingSize];
7014 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7015 emit_bytes (acfg, pad_buffer, kPaddingSize);
7019 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7023 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7025 cfg = acfg->cfgs [i];
7030 method = cfg->orig_method;
7032 /* Emit unbox trampoline */
7033 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7034 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7036 emit_section_change (acfg, ".text", 0);
7037 #ifdef __native_client_codegen__
7038 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7041 if (acfg->thumb_mixed && cfg->compile_llvm) {
7042 emit_set_thumb_mode (acfg);
7043 fprintf (acfg->fp, "\n.thumb_func\n");
7046 emit_label (acfg, symbol);
7048 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7050 if (acfg->thumb_mixed && cfg->compile_llvm) {
7051 emit_set_arm_mode (acfg);
7055 if (cfg->compile_llvm)
7056 acfg->stats.llvm_count ++;
7058 emit_method_code (acfg, cfg);
7061 sprintf (symbol, "methods_end");
7062 emit_section_change (acfg, ".text", 0);
7063 emit_alignment (acfg, 8);
7064 emit_label (acfg, symbol);
7065 /* To distinguish it from the next symbol */
7066 emit_int32 (acfg, 0);
7069 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7070 * from optimizing them away, since it doesn't see that code_offsets references them.
7071 * JITted methods don't need this since they are referenced using assembler local
7073 * FIXME: This is why write-symbols doesn't work on OSX ?
7075 if (acfg->llvm && acfg->need_no_dead_strip) {
7076 fprintf (acfg->fp, "\n");
7077 for (i = 0; i < acfg->nmethods; ++i) {
7078 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7079 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7084 if (acfg->direct_method_addresses) {
7085 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7088 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7089 * This is PIE code, and the linker can update it if needed.
7091 sprintf (symbol, "method_addresses");
7092 emit_section_change (acfg, ".text", 1);
7093 emit_alignment (acfg, 8);
7094 emit_label (acfg, symbol);
7095 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7096 emit_unset_mode (acfg);
7097 if (acfg->need_no_dead_strip)
7098 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7100 for (i = 0; i < acfg->nmethods; ++i) {
7101 if (acfg->cfgs [i]) {
7102 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
7103 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
7105 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
7107 fprintf (acfg->fp, "\tbl method_addresses\n");
7111 sprintf (symbol, "method_addresses_end");
7112 emit_label (acfg, symbol);
7115 sprintf (symbol, "code_offsets");
7116 emit_section_change (acfg, RODATA_SECT, 1);
7117 emit_alignment (acfg, 8);
7118 emit_label (acfg, symbol);
7119 emit_int32 (acfg, 0);
7121 sprintf (symbol, "code_offsets");
7122 emit_section_change (acfg, RODATA_SECT, 1);
7123 emit_alignment (acfg, 8);
7124 emit_label (acfg, symbol);
7126 acfg->stats.offsets_size += acfg->nmethods * 4;
7128 sprintf (end_symbol, "methods");
7129 for (i = 0; i < acfg->nmethods; ++i) {
7130 if (acfg->cfgs [i]) {
7131 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
7133 emit_int32 (acfg, 0xffffffff);
7138 sprintf (symbol, "code_offsets");
7139 emit_section_change (acfg, RODATA_SECT, 1);
7140 emit_alignment (acfg, 8);
7141 emit_label (acfg, symbol);
7143 acfg->stats.offsets_size += acfg->nmethods * 4;
7145 sprintf (end_symbol, "methods");
7146 for (i = 0; i < acfg->nmethods; ++i) {
7147 if (acfg->cfgs [i]) {
7148 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
7150 emit_int32 (acfg, 0xffffffff);
7156 /* Emit a sorted table mapping methods to their unbox trampolines */
7157 sprintf (symbol, "unbox_trampolines");
7158 if (acfg->direct_method_addresses)
7159 emit_section_change (acfg, ".text", 0);
7161 emit_section_change (acfg, RODATA_SECT, 0);
7162 emit_alignment (acfg, 8);
7163 emit_label (acfg, symbol);
7165 sprintf (end_symbol, "methods");
7167 for (i = 0; i < acfg->nmethods; ++i) {
7172 cfg = acfg->cfgs [i];
7176 method = cfg->orig_method;
7178 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7179 index = get_method_index (acfg, method);
7180 sprintf (symbol, "ut_%d", index);
7182 emit_int32 (acfg, index);
7183 if (acfg->direct_method_addresses) {
7184 emit_unset_mode (acfg);
7185 if (acfg->thumb_mixed && cfg->compile_llvm)
7186 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7188 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7190 emit_symbol_diff (acfg, symbol, end_symbol, 0);
7192 /* Make sure the table is sorted by index */
7193 g_assert (index > prev_index);
7197 sprintf (symbol, "unbox_trampolines_end");
7198 emit_label (acfg, symbol);
7202 emit_info (MonoAotCompile *acfg)
7208 offsets = g_new0 (gint32, acfg->nmethods);
7210 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7211 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7213 if (acfg->cfgs [i]) {
7214 emit_method_info (acfg, acfg->cfgs [i]);
7215 offsets [i] = acfg->cfgs [i]->method_info_offset;
7221 sprintf (symbol, "method_info_offsets");
7222 emit_section_change (acfg, RODATA_SECT, 1);
7223 emit_alignment (acfg, 8);
7224 emit_label (acfg, symbol);
7226 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7231 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7233 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7234 #define mix(a,b,c) { \
7235 a -= c; a ^= rot(c, 4); c += b; \
7236 b -= a; b ^= rot(a, 6); a += c; \
7237 c -= b; c ^= rot(b, 8); b += a; \
7238 a -= c; a ^= rot(c,16); c += b; \
7239 b -= a; b ^= rot(a,19); a += c; \
7240 c -= b; c ^= rot(b, 4); b += a; \
7242 #define final(a,b,c) { \
7243 c ^= b; c -= rot(b,14); \
7244 a ^= c; a -= rot(c,11); \
7245 b ^= a; b -= rot(a,25); \
7246 c ^= b; c -= rot(b,16); \
7247 a ^= c; a -= rot(c,4); \
7248 b ^= a; b -= rot(a,14); \
7249 c ^= b; c -= rot(b,24); \
7253 mono_aot_type_hash (MonoType *t1)
7255 guint hash = t1->type;
7257 hash |= t1->byref << 6; /* do not collide with t1->type values */
7259 case MONO_TYPE_VALUETYPE:
7260 case MONO_TYPE_CLASS:
7261 case MONO_TYPE_SZARRAY:
7262 /* check if the distribution is good enough */
7263 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7265 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7266 case MONO_TYPE_ARRAY:
7267 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7268 case MONO_TYPE_GENERICINST:
7269 return ((hash << 5) - hash) ^ 0;
7276 * mono_aot_method_hash:
7278 * Return a hash code for methods which only depends on metadata.
7281 mono_aot_method_hash (MonoMethod *method)
7283 MonoMethodSignature *sig;
7287 guint32 *hashes_start, *hashes;
7289 MonoGenericInst *ginst = NULL;
7291 /* Similar to the hash in mono_method_get_imt_slot () */
7293 sig = mono_method_signature (method);
7295 if (method->is_inflated)
7296 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7298 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7299 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7300 hashes = hashes_start;
7302 /* Some wrappers are assigned to random classes */
7303 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7304 klass = method->klass;
7306 klass = mono_defaults.object_class;
7308 if (!method->wrapper_type) {
7309 char *full_name = mono_type_full_name (&klass->byval_arg);
7311 hashes [0] = mono_metadata_str_hash (full_name);
7315 hashes [0] = mono_metadata_str_hash (klass->name);
7316 hashes [1] = mono_metadata_str_hash (klass->name_space);
7318 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7319 /* The method name includes a stringified pointer */
7322 hashes [2] = mono_metadata_str_hash (method->name);
7323 hashes [3] = method->wrapper_type;
7324 hashes [4] = mono_aot_type_hash (sig->ret);
7326 for (i = 0; i < sig->param_count; i++) {
7327 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7330 for (i = 0; i < ginst->type_argc; ++i)
7331 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7333 g_assert (hindex == hashes_count);
7335 /* Setup internal state */
7336 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7338 /* Handle most of the hashes */
7339 while (hashes_count > 3) {
7348 /* Handle the last 3 hashes (all the case statements fall through) */
7349 switch (hashes_count) {
7350 case 3 : c += hashes [2];
7351 case 2 : b += hashes [1];
7352 case 1 : a += hashes [0];
7354 case 0: /* nothing left to add */
7358 free (hashes_start);
7367 * mono_aot_get_array_helper_from_wrapper;
7369 * Get the helper method in Array called by an array wrapper method.
7372 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7376 MonoGenericContext ctx;
7377 MonoType *args [16];
7378 char *mname, *iname, *s, *s2, *helper_name = NULL;
7380 prefix = "System.Collections.Generic";
7381 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7382 s2 = strstr (s, "`1.");
7388 //printf ("X: %s %s\n", iname, mname);
7390 if (!strcmp (iname, "IList"))
7391 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7393 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7394 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7396 g_free (helper_name);
7399 if (m->is_generic) {
7400 memset (&ctx, 0, sizeof (ctx));
7401 args [0] = &method->klass->element_class->byval_arg;
7402 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7403 m = mono_class_inflate_generic_method (m, &ctx);
7409 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7411 typedef struct HashEntry {
7412 guint32 key, value, index;
7413 struct HashEntry *next;
7417 * emit_extra_methods:
7419 * Emit methods which are not in the METHOD table, like wrappers.
7422 emit_extra_methods (MonoAotCompile *acfg)
7424 int i, table_size, buf_size;
7427 guint32 *info_offsets;
7430 HashEntry *entry, *new_entry;
7431 int nmethods, max_chain_length;
7434 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7436 /* Emit method info */
7438 for (i = 0; i < acfg->extra_methods->len; ++i) {
7439 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7440 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7446 p = buf = g_malloc (buf_size);
7450 method = cfg->method_to_register;
7452 encode_method_ref (acfg, method, p, &p);
7454 g_assert ((p - buf) < buf_size);
7456 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7461 * Construct a chained hash table for mapping indexes in extra_method_info to
7464 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7465 table = g_ptr_array_sized_new (table_size);
7466 for (i = 0; i < table_size; ++i)
7467 g_ptr_array_add (table, NULL);
7468 chain_lengths = g_new0 (int, table_size);
7469 max_chain_length = 0;
7470 for (i = 0; i < acfg->extra_methods->len; ++i) {
7471 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7472 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7478 key = info_offsets [i];
7479 value = get_method_index (acfg, method);
7481 hash = mono_aot_method_hash (method) % table_size;
7482 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7484 chain_lengths [hash] ++;
7485 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7487 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7488 new_entry->key = key;
7489 new_entry->value = value;
7491 entry = g_ptr_array_index (table, hash);
7492 if (entry == NULL) {
7493 new_entry->index = hash;
7494 g_ptr_array_index (table, hash) = new_entry;
7497 entry = entry->next;
7499 entry->next = new_entry;
7500 new_entry->index = table->len;
7501 g_ptr_array_add (table, new_entry);
7505 //printf ("MAX: %d\n", max_chain_length);
7507 /* Emit the table */
7508 sprintf (symbol, "extra_method_table");
7509 emit_section_change (acfg, RODATA_SECT, 0);
7510 emit_alignment (acfg, 8);
7511 emit_label (acfg, symbol);
7513 emit_int32 (acfg, table_size);
7514 for (i = 0; i < table->len; ++i) {
7515 HashEntry *entry = g_ptr_array_index (table, i);
7517 if (entry == NULL) {
7518 emit_int32 (acfg, 0);
7519 emit_int32 (acfg, 0);
7520 emit_int32 (acfg, 0);
7522 //g_assert (entry->key > 0);
7523 emit_int32 (acfg, entry->key);
7524 emit_int32 (acfg, entry->value);
7526 emit_int32 (acfg, entry->next->index);
7528 emit_int32 (acfg, 0);
7533 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7534 * This is used by mono_aot_find_jit_info ().
7536 sprintf (symbol, "extra_method_info_offsets");
7537 emit_section_change (acfg, RODATA_SECT, 0);
7538 emit_alignment (acfg, 8);
7539 emit_label (acfg, symbol);
7541 emit_int32 (acfg, acfg->extra_methods->len);
7542 for (i = 0; i < acfg->extra_methods->len; ++i) {
7543 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7545 emit_int32 (acfg, get_method_index (acfg, method));
7546 emit_int32 (acfg, info_offsets [i]);
7551 emit_exception_info (MonoAotCompile *acfg)
7557 offsets = g_new0 (gint32, acfg->nmethods);
7558 for (i = 0; i < acfg->nmethods; ++i) {
7559 if (acfg->cfgs [i]) {
7560 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7561 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7567 sprintf (symbol, "ex_info_offsets");
7568 emit_section_change (acfg, RODATA_SECT, 1);
7569 emit_alignment (acfg, 8);
7570 emit_label (acfg, symbol);
7572 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7577 emit_unwind_info (MonoAotCompile *acfg)
7583 * The unwind info contains a lot of duplicates so we emit each unique
7584 * entry once, and only store the offset from the start of the table in the
7588 sprintf (symbol, "unwind_info");
7589 emit_section_change (acfg, RODATA_SECT, 1);
7590 emit_alignment (acfg, 8);
7591 emit_label (acfg, symbol);
7593 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7594 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7595 guint8 *unwind_info;
7596 guint32 unwind_info_len;
7600 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7603 encode_value (unwind_info_len, p, &p);
7604 emit_bytes (acfg, buf, p - buf);
7605 emit_bytes (acfg, unwind_info, unwind_info_len);
7607 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7612 emit_class_info (MonoAotCompile *acfg)
7618 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7619 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7620 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7622 sprintf (symbol, "class_info_offsets");
7623 emit_section_change (acfg, RODATA_SECT, 1);
7624 emit_alignment (acfg, 8);
7625 emit_label (acfg, symbol);
7627 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7631 typedef struct ClassNameTableEntry {
7632 guint32 token, index;
7633 struct ClassNameTableEntry *next;
7634 } ClassNameTableEntry;
7637 emit_class_name_table (MonoAotCompile *acfg)
7640 guint32 token, hash;
7645 ClassNameTableEntry *entry, *new_entry;
7648 * Construct a chained hash table for mapping class names to typedef tokens.
7650 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7651 table = g_ptr_array_sized_new (table_size);
7652 for (i = 0; i < table_size; ++i)
7653 g_ptr_array_add (table, NULL);
7654 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7655 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7656 klass = mono_class_get (acfg->image, token);
7658 mono_loader_clear_error ();
7661 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7662 hash = mono_metadata_str_hash (full_name) % table_size;
7665 /* FIXME: Allocate from the mempool */
7666 new_entry = g_new0 (ClassNameTableEntry, 1);
7667 new_entry->token = token;
7669 entry = g_ptr_array_index (table, hash);
7670 if (entry == NULL) {
7671 new_entry->index = hash;
7672 g_ptr_array_index (table, hash) = new_entry;
7675 entry = entry->next;
7677 entry->next = new_entry;
7678 new_entry->index = table->len;
7679 g_ptr_array_add (table, new_entry);
7683 /* Emit the table */
7684 sprintf (symbol, "class_name_table");
7685 emit_section_change (acfg, RODATA_SECT, 0);
7686 emit_alignment (acfg, 8);
7687 emit_label (acfg, symbol);
7689 /* FIXME: Optimize memory usage */
7690 g_assert (table_size < 65000);
7691 emit_int16 (acfg, table_size);
7692 g_assert (table->len < 65000);
7693 for (i = 0; i < table->len; ++i) {
7694 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7696 if (entry == NULL) {
7697 emit_int16 (acfg, 0);
7698 emit_int16 (acfg, 0);
7700 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7702 emit_int16 (acfg, entry->next->index);
7704 emit_int16 (acfg, 0);
7710 emit_image_table (MonoAotCompile *acfg)
7716 * The image table is small but referenced in a lot of places.
7717 * So we emit it at once, and reference its elements by an index.
7720 sprintf (symbol, "image_table");
7721 emit_section_change (acfg, RODATA_SECT, 1);
7722 emit_alignment (acfg, 8);
7723 emit_label (acfg, symbol);
7725 emit_int32 (acfg, acfg->image_table->len);
7726 for (i = 0; i < acfg->image_table->len; i++) {
7727 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7728 MonoAssemblyName *aname = &image->assembly->aname;
7730 /* FIXME: Support multi-module assemblies */
7731 g_assert (image->assembly->image == image);
7733 emit_string (acfg, image->assembly_name);
7734 emit_string (acfg, image->guid);
7735 emit_string (acfg, aname->culture ? aname->culture : "");
7736 emit_string (acfg, (const char*)aname->public_key_token);
7738 emit_alignment (acfg, 8);
7739 emit_int32 (acfg, aname->flags);
7740 emit_int32 (acfg, aname->major);
7741 emit_int32 (acfg, aname->minor);
7742 emit_int32 (acfg, aname->build);
7743 emit_int32 (acfg, aname->revision);
7748 emit_got_info (MonoAotCompile *acfg)
7751 int i, first_plt_got_patch, buf_size;
7753 guint32 *got_info_offsets;
7755 /* Add the patches needed by the PLT to the GOT */
7756 acfg->plt_got_offset_base = acfg->got_offset;
7757 first_plt_got_patch = acfg->got_patches->len;
7758 for (i = 1; i < acfg->plt_offset; ++i) {
7759 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7761 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7763 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7766 acfg->got_offset += acfg->plt_offset;
7770 * - optimize offsets table.
7771 * - reduce number of exported symbols.
7772 * - emit info for a klass only once.
7773 * - determine when a method uses a GOT slot which is guaranteed to be already
7775 * - clean up and document the code.
7776 * - use String.Empty in class libs.
7779 /* Encode info required to decode shared GOT entries */
7780 buf_size = acfg->got_patches->len * 128;
7781 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7782 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7783 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7785 if (acfg->plt_offset)
7786 acfg->plt_got_info_offsets [0] = 0;
7787 for (i = 0; i < acfg->got_patches->len; ++i) {
7788 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7793 encode_value (ji->type, p, &p);
7795 encode_patch (acfg, ji, p, &p);
7796 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7797 g_assert (p - buf <= buf_size);
7798 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7800 if (i >= first_plt_got_patch)
7801 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7802 acfg->stats.got_info_size += p - buf;
7805 /* Emit got_info_offsets table */
7806 sprintf (symbol, "got_info_offsets");
7807 emit_section_change (acfg, RODATA_SECT, 1);
7808 emit_alignment (acfg, 8);
7809 emit_label (acfg, symbol);
7811 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7812 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7816 emit_got (MonoAotCompile *acfg)
7821 /* Don't make GOT global so accesses to it don't need relocations */
7822 sprintf (symbol, "%s", acfg->got_symbol);
7823 emit_section_change (acfg, ".bss", 0);
7824 emit_alignment (acfg, 8);
7825 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7826 emit_label (acfg, symbol);
7827 if (acfg->got_offset > 0)
7828 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7830 sprintf (symbol, "got_end");
7831 emit_label (acfg, symbol);
7835 typedef struct GlobalsTableEntry {
7836 guint32 value, index;
7837 struct GlobalsTableEntry *next;
7838 } GlobalsTableEntry;
7841 emit_globals (MonoAotCompile *acfg)
7847 GlobalsTableEntry *entry, *new_entry;
7849 if (!acfg->aot_opts.static_link)
7853 * When static linking, we emit a table containing our globals.
7857 * Construct a chained hash table for mapping global names to their index in
7858 * the globals table.
7860 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7861 table = g_ptr_array_sized_new (table_size);
7862 for (i = 0; i < table_size; ++i)
7863 g_ptr_array_add (table, NULL);
7864 for (i = 0; i < acfg->globals->len; ++i) {
7865 char *name = g_ptr_array_index (acfg->globals, i);
7867 hash = mono_metadata_str_hash (name) % table_size;
7869 /* FIXME: Allocate from the mempool */
7870 new_entry = g_new0 (GlobalsTableEntry, 1);
7871 new_entry->value = i;
7873 entry = g_ptr_array_index (table, hash);
7874 if (entry == NULL) {
7875 new_entry->index = hash;
7876 g_ptr_array_index (table, hash) = new_entry;
7879 entry = entry->next;
7881 entry->next = new_entry;
7882 new_entry->index = table->len;
7883 g_ptr_array_add (table, new_entry);
7887 /* Emit the table */
7888 sprintf (symbol, ".Lglobals_hash");
7889 emit_section_change (acfg, RODATA_SECT, 0);
7890 emit_alignment (acfg, 8);
7891 emit_label (acfg, symbol);
7893 /* FIXME: Optimize memory usage */
7894 g_assert (table_size < 65000);
7895 emit_int16 (acfg, table_size);
7896 for (i = 0; i < table->len; ++i) {
7897 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7899 if (entry == NULL) {
7900 emit_int16 (acfg, 0);
7901 emit_int16 (acfg, 0);
7903 emit_int16 (acfg, entry->value + 1);
7905 emit_int16 (acfg, entry->next->index);
7907 emit_int16 (acfg, 0);
7911 /* Emit the names */
7912 for (i = 0; i < acfg->globals->len; ++i) {
7913 char *name = g_ptr_array_index (acfg->globals, i);
7915 sprintf (symbol, "name_%d", i);
7916 emit_section_change (acfg, RODATA_SECT, 1);
7918 emit_alignment (acfg, 4);
7920 emit_label (acfg, symbol);
7921 emit_string (acfg, name);
7924 /* Emit the globals table */
7925 sprintf (symbol, "globals");
7926 emit_section_change (acfg, ".data", 0);
7927 /* This is not a global, since it is accessed by the init function */
7928 emit_alignment (acfg, 8);
7929 emit_label (acfg, symbol);
7931 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7932 emit_pointer (acfg, symbol);
7934 for (i = 0; i < acfg->globals->len; ++i) {
7935 char *name = g_ptr_array_index (acfg->globals, i);
7937 sprintf (symbol, "name_%d", i);
7938 emit_pointer (acfg, symbol);
7940 sprintf (symbol, "%s", name);
7941 emit_pointer (acfg, symbol);
7943 /* Null terminate the table */
7944 emit_int32 (acfg, 0);
7945 emit_int32 (acfg, 0);
7949 emit_autoreg (MonoAotCompile *acfg)
7954 * Emit a function into the .ctor section which will be called by the ELF
7955 * loader to register this module with the runtime.
7957 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7960 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7962 arch_emit_autoreg (acfg, symbol);
7968 emit_mem_end (MonoAotCompile *acfg)
7972 sprintf (symbol, "mem_end");
7973 emit_section_change (acfg, ".text", 1);
7974 emit_alignment (acfg, 8);
7975 emit_label (acfg, symbol);
7979 * Emit a structure containing all the information not stored elsewhere.
7982 emit_file_info (MonoAotCompile *acfg)
7987 const char *gc_name;
7990 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7992 if (acfg->aot_opts.bind_to_runtime_version) {
7993 build_info = mono_get_runtime_build_info ();
7994 emit_string_symbol (acfg, "runtime_version", build_info);
7995 g_free (build_info);
7997 emit_string_symbol (acfg, "runtime_version", "");
8000 /* Emit a string holding the assembly name */
8001 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8004 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8007 gc_name = mono_gc_get_gc_name ();
8008 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8010 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8011 emit_section_change (acfg, ".data", 0);
8012 emit_alignment (acfg, 8);
8013 emit_label (acfg, symbol);
8014 if (!acfg->aot_opts.static_link)
8015 emit_global (acfg, symbol, FALSE);
8017 /* The data emitted here must match MonoAotFileInfo. */
8019 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8020 emit_int32 (acfg, 0);
8023 * We emit pointers to our data structures instead of emitting global symbols which
8024 * point to them, to reduce the number of globals, and because using globals leads to
8025 * various problems (i.e. arm/thumb).
8027 emit_pointer (acfg, acfg->got_symbol);
8028 emit_pointer (acfg, "methods");
8031 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8033 emit_pointer (acfg, "mono_eh_frame");
8035 emit_pointer (acfg, NULL);
8037 emit_pointer (acfg, "blob");
8038 emit_pointer (acfg, "class_name_table");
8039 emit_pointer (acfg, "class_info_offsets");
8040 emit_pointer (acfg, "method_info_offsets");
8041 emit_pointer (acfg, "ex_info_offsets");
8042 emit_pointer (acfg, "code_offsets");
8043 if (acfg->direct_method_addresses)
8044 emit_pointer (acfg, "method_addresses");
8046 emit_pointer (acfg, NULL);
8047 emit_pointer (acfg, "extra_method_info_offsets");
8048 emit_pointer (acfg, "extra_method_table");
8049 emit_pointer (acfg, "got_info_offsets");
8050 emit_pointer (acfg, "methods_end");
8051 emit_pointer (acfg, "unwind_info");
8052 emit_pointer (acfg, "mem_end");
8053 emit_pointer (acfg, "image_table");
8054 emit_pointer (acfg, "plt");
8055 emit_pointer (acfg, "plt_end");
8056 emit_pointer (acfg, "assembly_guid");
8057 emit_pointer (acfg, "runtime_version");
8058 if (acfg->num_trampoline_got_entries) {
8059 emit_pointer (acfg, "specific_trampolines");
8060 emit_pointer (acfg, "static_rgctx_trampolines");
8061 emit_pointer (acfg, "imt_thunks");
8062 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8064 emit_pointer (acfg, NULL);
8065 emit_pointer (acfg, NULL);
8066 emit_pointer (acfg, NULL);
8067 emit_pointer (acfg, NULL);
8069 if (acfg->thumb_mixed) {
8070 emit_pointer (acfg, "thumb_end");
8072 emit_pointer (acfg, NULL);
8074 if (acfg->aot_opts.static_link) {
8075 emit_pointer (acfg, "globals");
8077 emit_pointer (acfg, NULL);
8079 emit_pointer (acfg, "assembly_name");
8080 emit_pointer (acfg, "unbox_trampolines");
8081 emit_pointer (acfg, "unbox_trampolines_end");
8083 emit_int32 (acfg, acfg->plt_got_offset_base);
8084 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8085 emit_int32 (acfg, acfg->plt_offset);
8086 emit_int32 (acfg, acfg->nmethods);
8087 emit_int32 (acfg, acfg->flags);
8088 emit_int32 (acfg, acfg->opts);
8089 emit_int32 (acfg, acfg->simd_opts);
8090 emit_int32 (acfg, gc_name_offset);
8092 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8093 emit_int32 (acfg, acfg->num_trampolines [i]);
8094 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8095 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8096 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8097 emit_int32 (acfg, acfg->trampoline_size [i]);
8098 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8100 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8105 memset (&t, 0, sizeof (MonoType));
8106 t.type = MONO_TYPE_R8;
8107 mono_type_size (&t, &align);
8108 emit_int32 (acfg, align);
8110 memset (&t, 0, sizeof (MonoType));
8111 t.type = MONO_TYPE_I8;
8112 mono_type_size (&t, &align);
8114 emit_int32 (acfg, align);
8117 emit_int32 (acfg, __alignof__ (double));
8118 emit_int32 (acfg, __alignof__ (gint64));
8120 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8122 if (acfg->aot_opts.static_link) {
8126 * Emit a global symbol which can be passed by an embedding app to
8127 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8130 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8132 /* Get rid of characters which cannot occur in symbols */
8134 for (p = symbol; *p; ++p) {
8135 if (!(isalnum (*p) || *p == '_'))
8138 acfg->static_linking_symbol = g_strdup (symbol);
8139 emit_global_inner (acfg, symbol, FALSE);
8140 emit_alignment (acfg, sizeof (gpointer));
8141 emit_label (acfg, symbol);
8142 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8147 emit_blob (MonoAotCompile *acfg)
8151 sprintf (symbol, "blob");
8152 emit_section_change (acfg, RODATA_SECT, 1);
8153 emit_alignment (acfg, 8);
8154 emit_label (acfg, symbol);
8156 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8160 emit_objc_selectors (MonoAotCompile *acfg)
8164 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8169 * cat > foo.m << EOF
8172 * return @selector(print:);
8177 img_writer_emit_unset_mode (acfg->w);
8178 g_assert (acfg->fp);
8179 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8180 fprintf (acfg->fp, ".align 2\n");
8181 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8182 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8183 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8185 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8186 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8187 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8188 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8191 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8192 fprintf (acfg->fp, ".align 2\n");
8193 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8194 fprintf (acfg->fp, ".long 0\n");
8195 fprintf (acfg->fp, ".long 16\n");
8199 emit_dwarf_info (MonoAotCompile *acfg)
8201 #ifdef EMIT_DWARF_INFO
8205 /* DIEs for methods */
8206 for (i = 0; i < acfg->nmethods; ++i) {
8207 MonoCompile *cfg = acfg->cfgs [i];
8212 // FIXME: LLVM doesn't define .Lme_...
8213 if (cfg->compile_llvm)
8216 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8218 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 ()));
8224 collect_methods (MonoAotCompile *acfg)
8227 MonoImage *image = acfg->image;
8229 /* Collect methods */
8230 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8232 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8234 method = mono_get_method (acfg->image, token, NULL);
8237 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8241 /* Load all methods eagerly to skip the slower lazy loading code */
8242 mono_class_setup_methods (method->klass);
8244 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8245 /* Compile the wrapper instead */
8246 /* We do this here instead of add_wrappers () because it is easy to do it here */
8247 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8251 /* FIXME: Some mscorlib methods don't have debug info */
8253 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8254 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8255 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8256 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8257 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8258 if (!mono_debug_lookup_method (method)) {
8259 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8266 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8267 add_method_with_index (acfg, method, i, FALSE);
8268 acfg->method_index ++;
8271 /* gsharedvt methods */
8272 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8274 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8276 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8279 method = mono_get_method (acfg->image, token, NULL);
8283 if (strcmp (method->name, "gshared2"))
8287 if (!strstr (method->klass->image->name, "mini"))
8290 if (method->is_generic || method->klass->generic_container) {
8291 MonoMethod *gshared;
8293 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8294 add_extra_method (acfg, gshared);
8298 add_generic_instances (acfg);
8300 if (acfg->aot_opts.full_aot)
8301 add_wrappers (acfg);
8305 compile_methods (MonoAotCompile *acfg)
8309 if (acfg->aot_opts.nthreads > 0) {
8314 gpointer *user_data;
8315 MonoMethod **methods;
8317 methods_len = acfg->methods->len;
8319 len = acfg->methods->len / acfg->aot_opts.nthreads;
8322 * Partition the list of methods into fragments, and hand it to threads to
8325 threads = g_ptr_array_new ();
8326 /* Make a copy since acfg->methods is modified by compile_method () */
8327 methods = g_new0 (MonoMethod*, methods_len);
8328 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8329 for (i = 0; i < methods_len; ++i)
8330 methods [i] = g_ptr_array_index (acfg->methods, i);
8332 while (i < methods_len) {
8333 frag = g_ptr_array_new ();
8334 for (j = 0; j < len; ++j) {
8335 if (i < methods_len) {
8336 g_ptr_array_add (frag, methods [i]);
8341 user_data = g_new0 (gpointer, 3);
8342 user_data [0] = mono_domain_get ();
8343 user_data [1] = acfg;
8344 user_data [2] = frag;
8346 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
8347 g_ptr_array_add (threads, handle);
8351 for (i = 0; i < threads->len; ++i) {
8352 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8358 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8359 for (i = methods_len; i < acfg->methods->len; ++i) {
8360 /* This can new methods to acfg->methods */
8361 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8366 compile_asm (MonoAotCompile *acfg)
8368 char *command, *objfile;
8369 char *outfile_name, *tmp_outfile_name;
8370 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8372 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8373 #define AS_OPTIONS "--64"
8374 #elif defined(TARGET_POWERPC64)
8375 #define AS_OPTIONS "-a64 -mppc64"
8376 #define LD_OPTIONS "-m elf64ppc"
8377 #elif defined(sparc) && SIZEOF_VOID_P == 8
8378 #define AS_OPTIONS "-xarch=v9"
8379 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8380 #define AS_OPTIONS "-arch i386 -W"
8382 #define AS_OPTIONS ""
8385 #ifdef __native_client_codegen__
8386 #if defined(TARGET_AMD64)
8387 #define AS_NAME "nacl64-as"
8389 #define AS_NAME "nacl-as"
8392 #define AS_NAME "as"
8396 #define LD_OPTIONS ""
8399 #define EH_LD_OPTIONS ""
8401 if (acfg->aot_opts.asm_only) {
8402 printf ("Output file: '%s'.\n", acfg->tmpfname);
8403 if (acfg->aot_opts.static_link)
8404 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8408 if (acfg->aot_opts.static_link) {
8409 if (acfg->aot_opts.outfile)
8410 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8412 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8414 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8416 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);
8417 printf ("Executing the native assembler: %s\n", command);
8418 if (system (command) != 0) {
8426 if (acfg->aot_opts.static_link) {
8427 printf ("Output file: '%s'.\n", objfile);
8428 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8433 if (acfg->aot_opts.outfile)
8434 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8436 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8438 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8441 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8442 #elif defined(__ppc__) && defined(TARGET_MACH)
8443 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8444 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8445 command = g_strdup_printf ("gcc --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8446 #elif defined(HOST_WIN32)
8447 command = g_strdup_printf ("gcc -shared --dll -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8448 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8449 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
8451 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8453 printf ("Executing the native linker: %s\n", command);
8454 if (system (command) != 0) {
8455 g_free (tmp_outfile_name);
8456 g_free (outfile_name);
8464 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8465 printf ("Stripping the binary: %s\n", com);
8469 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8471 * gas generates 'mapping symbols' each time code and data is mixed, which
8472 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8474 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8475 printf ("Stripping the binary: %s\n", command);
8476 if (system (command) != 0) {
8477 g_free (tmp_outfile_name);
8478 g_free (outfile_name);
8485 rename (tmp_outfile_name, outfile_name);
8487 #if defined(TARGET_MACH)
8488 command = g_strdup_printf ("dsymutil %s", outfile_name);
8489 printf ("Generating debug symbols: %s\n", command);
8490 if (system (command) != 0) {
8495 if (!acfg->aot_opts.save_temps)
8498 g_free (tmp_outfile_name);
8499 g_free (outfile_name);
8502 if (acfg->aot_opts.save_temps)
8503 printf ("Retained input file.\n");
8505 unlink (acfg->tmpfname);
8510 static MonoAotCompile*
8511 acfg_create (MonoAssembly *ass, guint32 opts)
8513 MonoImage *image = ass->image;
8514 MonoAotCompile *acfg;
8517 acfg = g_new0 (MonoAotCompile, 1);
8518 acfg->methods = g_ptr_array_new ();
8519 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8520 acfg->method_depth = g_hash_table_new (NULL, NULL);
8521 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8522 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8523 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8524 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8525 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8526 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8527 acfg->got_patches = g_ptr_array_new ();
8528 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8529 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8530 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8531 acfg->image_hash = g_hash_table_new (NULL, NULL);
8532 acfg->image_table = g_ptr_array_new ();
8533 acfg->globals = g_ptr_array_new ();
8534 acfg->image = image;
8536 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8537 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8538 acfg->mempool = mono_mempool_new ();
8539 acfg->extra_methods = g_ptr_array_new ();
8540 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8541 acfg->unwind_ops = g_ptr_array_new ();
8542 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8543 acfg->method_order = g_ptr_array_new ();
8544 acfg->export_names = g_hash_table_new (NULL, NULL);
8545 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8546 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8547 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8548 InitializeCriticalSection (&acfg->mutex);
8554 acfg_free (MonoAotCompile *acfg)
8558 img_writer_destroy (acfg->w);
8559 for (i = 0; i < acfg->nmethods; ++i)
8561 g_free (acfg->cfgs [i]);
8562 g_free (acfg->cfgs);
8563 g_free (acfg->static_linking_symbol);
8564 g_free (acfg->got_symbol);
8565 g_free (acfg->plt_symbol);
8566 g_ptr_array_free (acfg->methods, TRUE);
8567 g_ptr_array_free (acfg->got_patches, TRUE);
8568 g_ptr_array_free (acfg->image_table, TRUE);
8569 g_ptr_array_free (acfg->globals, TRUE);
8570 g_ptr_array_free (acfg->unwind_ops, TRUE);
8571 g_hash_table_destroy (acfg->method_indexes);
8572 g_hash_table_destroy (acfg->method_depth);
8573 g_hash_table_destroy (acfg->plt_offset_to_entry);
8574 g_hash_table_destroy (acfg->patch_to_plt_entry);
8575 g_hash_table_destroy (acfg->patch_to_got_offset);
8576 g_hash_table_destroy (acfg->method_to_cfg);
8577 g_hash_table_destroy (acfg->token_info_hash);
8578 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8579 g_hash_table_destroy (acfg->image_hash);
8580 g_hash_table_destroy (acfg->unwind_info_offsets);
8581 g_hash_table_destroy (acfg->method_label_hash);
8582 g_hash_table_destroy (acfg->export_names);
8583 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8584 g_hash_table_destroy (acfg->klass_blob_hash);
8585 g_hash_table_destroy (acfg->method_blob_hash);
8586 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8587 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8588 g_free (acfg->patch_to_got_offset_by_type);
8589 mono_mempool_destroy (acfg->mempool);
8594 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8596 MonoImage *image = ass->image;
8598 MonoAotCompile *acfg;
8599 char *outfile_name, *tmp_outfile_name, *p;
8600 char llvm_stats_msg [256];
8604 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || (!defined(MONO_EXTENSIONS) && !defined(MONOTOUCH))
8605 if (opts & MONO_OPT_GSHAREDVT) {
8606 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8611 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8613 acfg = acfg_create (ass, opts);
8615 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8616 acfg->aot_opts.write_symbols = TRUE;
8617 acfg->aot_opts.ntrampolines = 1024;
8618 acfg->aot_opts.nrgctx_trampolines = 1024;
8619 acfg->aot_opts.nimt_trampolines = 128;
8620 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8621 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8622 acfg->aot_opts.llvm_path = g_strdup ("");
8624 acfg->aot_opts.use_trampolines_page = TRUE;
8627 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8629 if (acfg->aot_opts.static_link)
8630 acfg->aot_opts.autoreg = TRUE;
8632 //acfg->aot_opts.print_skipped_methods = TRUE;
8634 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8635 if (acfg->aot_opts.full_aot) {
8636 printf ("--aot=full is not supported on this platform.\n");
8641 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8642 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8646 if (acfg->aot_opts.static_link)
8647 acfg->aot_opts.asm_writer = TRUE;
8649 if (acfg->aot_opts.soft_debug) {
8650 MonoDebugOptions *opt = mini_get_debug_options ();
8652 opt->mdb_optimizations = TRUE;
8653 opt->gen_seq_points = TRUE;
8655 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8656 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8659 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8662 if (mono_use_llvm) {
8664 acfg->aot_opts.asm_writer = TRUE;
8665 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8667 if (acfg->aot_opts.soft_debug) {
8668 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8673 if (acfg->aot_opts.full_aot)
8674 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8676 load_profile_files (acfg);
8678 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8679 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8680 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8682 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8683 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8684 if (acfg->opts & MONO_OPT_GSHAREDVT)
8685 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8688 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8692 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8693 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8694 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8696 /* Get rid of characters which cannot occur in symbols */
8697 for (p = acfg->got_symbol_base; *p; ++p) {
8698 if (!(isalnum (*p) || *p == '_'))
8701 for (p = acfg->plt_symbol; *p; ++p) {
8702 if (!(isalnum (*p) || *p == '_'))
8705 for (p = acfg->assembly_name_sym; *p; ++p) {
8706 if (!(isalnum (*p) || *p == '_'))
8710 acfg->method_index = 1;
8714 if (acfg->aot_opts.full_aot)
8715 mono_set_partial_sharing_supported (TRUE);
8718 collect_methods (acfg);
8720 acfg->cfgs_size = acfg->methods->len + 32;
8721 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8723 /* PLT offset 0 is reserved for the PLT trampoline */
8724 acfg->plt_offset = 1;
8729 mono_llvm_create_aot_module (acfg->got_symbol_base);
8733 /* GOT offset 0 is reserved for the address of the current assembly */
8737 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8738 ji->type = MONO_PATCH_INFO_IMAGE;
8739 ji->data.image = acfg->image;
8741 get_got_offset (acfg, ji);
8743 /* Slot 1 is reserved for the mscorlib got addr */
8744 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8745 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8746 get_got_offset (acfg, ji);
8748 /* This is very common */
8749 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8750 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8751 get_got_offset (acfg, ji);
8753 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8754 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8755 get_got_offset (acfg, ji);
8760 compile_methods (acfg);
8764 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8770 if (acfg->aot_opts.asm_only) {
8771 if (acfg->aot_opts.outfile)
8772 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8774 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8776 acfg->tmpfname = g_strdup ("temp.s");
8779 emit_llvm_file (acfg);
8783 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8784 if (acfg->aot_opts.outfile)
8785 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8787 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8790 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8791 * it might be in another file system so the rename () won't work.
8793 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8795 acfg->fp = fopen (tmp_outfile_name, "w");
8797 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8801 acfg->w = img_writer_create (acfg->fp, TRUE);
8802 acfg->use_bin_writer = TRUE;
8805 /* Append to the .s file created by llvm */
8806 /* FIXME: Use multiple files instead */
8807 acfg->fp = fopen (acfg->tmpfname, "a+");
8809 if (acfg->aot_opts.asm_only) {
8810 if (acfg->aot_opts.outfile)
8811 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8813 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8814 acfg->fp = fopen (acfg->tmpfname, "w+");
8816 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8817 acfg->fp = fdopen (i, "w+");
8819 if (acfg->fp == 0) {
8820 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8824 acfg->w = img_writer_create (acfg->fp, FALSE);
8826 tmp_outfile_name = NULL;
8827 outfile_name = NULL;
8830 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8832 /* Compute symbols for methods */
8833 for (i = 0; i < acfg->nmethods; ++i) {
8834 if (acfg->cfgs [i]) {
8835 MonoCompile *cfg = acfg->cfgs [i];
8836 int method_index = get_method_index (acfg, cfg->orig_method);
8838 if (COMPILE_LLVM (cfg))
8839 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8840 else if (acfg->global_symbols)
8841 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8843 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8847 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8849 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8851 acfg->gas_line_numbers = TRUE;
8854 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8855 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8856 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8859 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8862 img_writer_emit_start (acfg->w);
8865 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8867 if (acfg->thumb_mixed) {
8870 * This global symbol marks the end of THUMB code, and the beginning of ARM
8871 * code generated by our JIT.
8873 sprintf (symbol, "thumb_end");
8874 emit_section_change (acfg, ".text", 0);
8875 emit_alignment (acfg, 8);
8876 emit_label (acfg, symbol);
8877 emit_zero_bytes (acfg, 16);
8879 fprintf (acfg->fp, ".arm\n");
8886 emit_extra_methods (acfg);
8888 emit_trampolines (acfg);
8890 emit_class_name_table (acfg);
8892 emit_got_info (acfg);
8894 emit_exception_info (acfg);
8896 emit_unwind_info (acfg);
8898 emit_class_info (acfg);
8902 emit_image_table (acfg);
8906 emit_file_info (acfg);
8910 emit_objc_selectors (acfg);
8912 emit_globals (acfg);
8914 emit_autoreg (acfg);
8917 emit_dwarf_info (acfg);
8918 mono_dwarf_writer_close (acfg->dwarf);
8921 emit_mem_end (acfg);
8923 if (acfg->need_pt_gnu_stack) {
8924 /* This is required so the .so doesn't have an executable stack */
8925 /* The bin writer already emits this */
8926 if (!acfg->use_bin_writer)
8927 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8932 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8935 g_assert (acfg->got_offset <= acfg->final_got_size);
8938 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8940 strcpy (llvm_stats_msg, "");
8941 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
8942 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8943 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8945 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8946 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8947 if (acfg->stats.genericcount)
8948 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8949 if (acfg->stats.abscount)
8950 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8951 if (acfg->stats.lmfcount)
8952 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8953 if (acfg->stats.ocount)
8954 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8957 res = img_writer_emit_writeout (acfg->w);
8962 if (acfg->use_bin_writer) {
8963 int err = rename (tmp_outfile_name, outfile_name);
8966 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8970 res = compile_asm (acfg);
8977 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8979 if (acfg->aot_opts.stats) {
8982 printf ("GOT slot distribution:\n");
8983 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8984 if (acfg->stats.got_slot_types [i])
8985 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8988 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);
9000 mono_aot_readonly_field_override (MonoClassField *field)
9006 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)