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;
191 guint32 tramp_page_size;
193 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
194 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
195 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
196 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
198 MonoAotOptions aot_opts;
202 MonoMemPool *mempool;
205 char *static_linking_symbol;
206 CRITICAL_SECTION mutex;
207 gboolean use_bin_writer;
208 gboolean gas_line_numbers;
210 MonoDwarfWriter *dwarf;
215 GHashTable *unwind_info_offsets;
216 GPtrArray *unwind_ops;
217 guint32 unwind_info_offset;
218 char *got_symbol_base;
221 char *methods_symbol;
222 GHashTable *method_label_hash;
223 const char *temp_prefix;
224 const char *user_symbol_prefix;
225 const char *llvm_label_prefix;
226 guint32 label_generator;
228 MonoAotFileFlags flags;
229 MonoDynamicStream blob;
230 MonoClass **typespec_classes;
233 char *assembly_name_sym;
234 GHashTable *plt_entry_debug_sym_cache;
235 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
236 GHashTable *ginst_hash;
237 GHashTable *dwarf_ln_filenames;
238 gboolean global_symbols;
239 gboolean direct_method_addresses;
240 int objc_selector_index, objc_selector_index_2;
241 GPtrArray *objc_selectors;
242 GHashTable *objc_selector_to_index;
247 char *symbol, *llvm_symbol, *debug_sym;
249 gboolean jit_used, llvm_used;
252 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
253 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
255 /* This points to the current acfg in LLVM mode */
256 static MonoAotCompile *llvm_acfg;
258 #ifdef HAVE_ARRAY_ELEM_INIT
259 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
260 #define MSGSTRFIELD1(line) str##line
261 static const struct msgstr_t {
262 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
263 #include "patch-info.h"
266 #define PATCH_INFO(a,b) b,
267 #include "patch-info.h"
270 static const gint16 opidx [] = {
271 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
272 #include "patch-info.h"
276 static G_GNUC_UNUSED const char*
277 get_patch_name (int info)
279 return (const char*)&opstr + opidx [info];
283 #define PATCH_INFO(a,b) b,
284 static const char* const
285 patch_types [MONO_PATCH_INFO_NUM + 1] = {
286 #include "patch-info.h"
290 static G_GNUC_UNUSED const char*
291 get_patch_name (int info)
293 return patch_types [info];
299 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
301 /* Wrappers around the image writer functions */
304 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
306 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
310 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
312 img_writer_emit_push_section (acfg->w, section_name, subsection);
316 emit_pop_section (MonoAotCompile *acfg)
318 img_writer_emit_pop_section (acfg->w);
322 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
324 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
328 emit_label (MonoAotCompile *acfg, const char *name)
330 img_writer_emit_label (acfg->w, name);
334 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
336 img_writer_emit_bytes (acfg->w, buf, size);
340 emit_string (MonoAotCompile *acfg, const char *value)
342 img_writer_emit_string (acfg->w, value);
346 emit_line (MonoAotCompile *acfg)
348 img_writer_emit_line (acfg->w);
352 emit_alignment (MonoAotCompile *acfg, int size)
354 img_writer_emit_alignment (acfg->w, size);
358 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
360 img_writer_emit_pointer_unaligned (acfg->w, target);
364 emit_pointer (MonoAotCompile *acfg, const char *target)
366 img_writer_emit_pointer (acfg->w, target);
370 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
372 if (prefix [0] != '\0') {
373 char *s = g_strdup_printf ("%s%s", prefix, target);
374 img_writer_emit_pointer (acfg->w, s);
377 img_writer_emit_pointer (acfg->w, target);
382 emit_int16 (MonoAotCompile *acfg, int value)
384 img_writer_emit_int16 (acfg->w, value);
388 emit_int32 (MonoAotCompile *acfg, int value)
390 img_writer_emit_int32 (acfg->w, value);
394 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
396 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
400 emit_zero_bytes (MonoAotCompile *acfg, int num)
402 img_writer_emit_zero_bytes (acfg->w, num);
406 emit_byte (MonoAotCompile *acfg, guint8 val)
408 img_writer_emit_byte (acfg->w, val);
411 #ifdef __native_client_codegen__
413 emit_nacl_call_alignment (MonoAotCompile *acfg)
415 img_writer_emit_nacl_call_alignment (acfg->w);
419 static G_GNUC_UNUSED void
420 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
422 img_writer_emit_global (acfg->w, name, func);
426 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
428 if (acfg->aot_opts.no_dlsym) {
429 g_ptr_array_add (acfg->globals, g_strdup (name));
430 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
432 img_writer_emit_global (acfg->w, name, func);
437 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
439 img_writer_emit_symbol_size (acfg->w, name, end_label);
443 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
445 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
447 /* On apple, all symbols need to be aligned to avoid warnings from ld */
448 emit_alignment (acfg, 4);
450 img_writer_emit_label (acfg->w, name);
451 img_writer_emit_string (acfg->w, value);
454 static G_GNUC_UNUSED void
455 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
458 guint8 b = value & 0x7f;
460 if (value != 0) /* more bytes to come */
466 static G_GNUC_UNUSED void
467 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
470 gboolean negative = (value < 0);
477 /* the following is unnecessary if the
478 * implementation of >>= uses an arithmetic rather
479 * than logical shift for a signed left operand
483 value |= - ((gint64)1 <<(size - 7));
484 /* sign bit of byte is second high order bit (0x40) */
485 if ((value == 0 && !(byte & 0x40)) ||
486 (value == -1 && (byte & 0x40)))
490 emit_byte (acfg, byte);
494 static G_GNUC_UNUSED void
495 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
500 guint8 b = value & 0x7f;
502 if (value != 0) /* more bytes to come */
510 static G_GNUC_UNUSED void
511 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
514 gboolean negative = (value < 0);
522 /* the following is unnecessary if the
523 * implementation of >>= uses an arithmetic rather
524 * than logical shift for a signed left operand
528 value |= - (1 <<(size - 7));
529 /* sign bit of byte is second high order bit (0x40) */
530 if ((value == 0 && !(byte & 0x40)) ||
531 (value == -1 && (byte & 0x40)))
542 emit_unset_mode (MonoAotCompile *acfg)
544 img_writer_emit_unset_mode (acfg->w);
547 static G_GNUC_UNUSED void
548 emit_set_thumb_mode (MonoAotCompile *acfg)
550 emit_unset_mode (acfg);
551 fprintf (acfg->fp, ".code 16\n");
554 static G_GNUC_UNUSED void
555 emit_set_arm_mode (MonoAotCompile *acfg)
557 emit_unset_mode (acfg);
558 fprintf (acfg->fp, ".code 32\n");
562 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
564 emit_bytes (acfg, buf, size);
567 /* ARCHITECTURE SPECIFIC CODE */
569 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
570 #define EMIT_DWARF_INFO 1
573 #if defined(TARGET_ARM)
574 #define AOT_FUNC_ALIGNMENT 4
576 #define AOT_FUNC_ALIGNMENT 16
578 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
579 #undef AOT_FUNC_ALIGNMENT
580 #define AOT_FUNC_ALIGNMENT 32
583 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
584 #define PPC_LD_OP "ld"
585 #define PPC_LDX_OP "ldx"
587 #define PPC_LD_OP "lwz"
588 #define PPC_LDX_OP "lwzx"
592 #define AOT_TARGET_STR "AMD64"
597 #define AOT_TARGET_STR "ARM (MACH)"
599 #define AOT_TARGET_STR "ARM (!MACH)"
603 #ifdef TARGET_POWERPC64
604 #ifdef __mono_ilp32__
605 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
607 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
610 #ifdef TARGET_POWERPC
611 #ifdef __mono_ilp32__
612 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
614 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
621 #define AOT_TARGET_STR "X86 (WIN32)"
622 #elif defined(__native_client_codegen__)
623 #define AOT_TARGET_STR "X86 (native client codegen)"
625 #define AOT_TARGET_STR "X86 (!native client codegen)"
629 #ifndef AOT_TARGET_STR
630 #define AOT_TARGET_STR ""
634 arch_init (MonoAotCompile *acfg)
636 acfg->llc_args = g_string_new ("");
637 acfg->as_args = g_string_new ("");
640 * The prefix LLVM likes to put in front of symbol names on darwin.
641 * The mach-os specs require this for globals, but LLVM puts them in front of all
642 * symbols. We need to handle this, since we need to refer to LLVM generated
645 acfg->llvm_label_prefix = "";
646 acfg->user_symbol_prefix = "";
648 #if defined(TARGET_AMD64)
649 g_string_append (acfg->llc_args, " -march=x86-64");
653 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
654 g_string_append (acfg->llc_args, "-mattr=+v6");
657 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
658 g_string_append (acfg->as_args, " -mfpu=vfp3");
660 g_string_append (acfg->llc_args, " -soft-float");
663 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
664 acfg->thumb_mixed = TRUE;
666 if (acfg->aot_opts.mtriple)
667 mono_arch_set_target (acfg->aot_opts.mtriple);
671 acfg->user_symbol_prefix = "_";
672 acfg->llvm_label_prefix = "_";
673 acfg->need_no_dead_strip = TRUE;
674 acfg->aot_opts.gnu_asm = TRUE;
677 #if defined(__linux__) && !defined(TARGET_ARM)
678 acfg->need_pt_gnu_stack = TRUE;
682 acfg->direct_method_addresses = TRUE;
683 acfg->global_symbols = TRUE;
687 #ifdef MONO_ARCH_AOT_SUPPORTED
689 * arch_emit_direct_call:
691 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
695 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
697 #if defined(TARGET_X86) || defined(TARGET_AMD64)
698 /* Need to make sure this is exactly 5 bytes long */
699 if (external && !acfg->use_bin_writer) {
700 emit_unset_mode (acfg);
701 fprintf (acfg->fp, "call %s\n", target);
703 emit_byte (acfg, '\xe8');
704 emit_symbol_diff (acfg, target, ".", -4);
707 #elif defined(TARGET_ARM)
708 if (acfg->use_bin_writer) {
715 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
716 emit_bytes (acfg, buf, 4);
718 emit_unset_mode (acfg);
720 fprintf (acfg->fp, "blx %s\n", target);
722 fprintf (acfg->fp, "bl %s\n", target);
725 #elif defined(TARGET_POWERPC)
726 if (acfg->use_bin_writer) {
727 g_assert_not_reached ();
729 emit_unset_mode (acfg);
730 fprintf (acfg->fp, "bl %s\n", target);
734 g_assert_not_reached ();
741 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
743 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
744 * in in the 2. slot of every GOT, and require every method to place the GOT
745 * address in r30, even when it doesn't access the GOT otherwise. This way,
746 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
751 * PPC64 uses function descriptors which greatly complicate all code, since
752 * these are used very inconsistently in the runtime. Some functions like
753 * mono_compile_method () return ftn descriptors, while others like the
754 * trampoline creation functions do not.
755 * We assume that all GOT slots contain function descriptors, and create
756 * descriptors in aot-runtime.c when needed.
757 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
758 * from function descriptors, we could do the same, but it would require
759 * rewriting all the ppc/aot code to handle function descriptors properly.
760 * So instead, we use the same approach as on PPC32.
761 * This is a horrible mess, but fixing it would probably lead to an even bigger
767 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
770 #ifdef MONO_ARCH_AOT_SUPPORTED
772 * arch_emit_got_offset:
774 * The memory pointed to by CODE should hold native code for computing the GOT
775 * address. Emit this code while patching it with the offset between code and
776 * the GOT. CODE_SIZE is set to the number of bytes emitted.
779 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
781 #if defined(TARGET_POWERPC64)
782 g_assert (!acfg->use_bin_writer);
783 emit_unset_mode (acfg);
785 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
786 * unsupported relocations. So we store the got address into the .Lgot_addr
787 * symbol which is in the text segment, compute its address, and load it.
789 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
790 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
791 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
792 fprintf (acfg->fp, "add 30, 30, 0\n");
793 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
794 acfg->label_generator ++;
796 #elif defined(TARGET_POWERPC)
797 g_assert (!acfg->use_bin_writer);
798 emit_unset_mode (acfg);
799 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
800 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
801 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
802 acfg->label_generator ++;
805 guint32 offset = mono_arch_get_patch_offset (code);
806 emit_bytes (acfg, code, offset);
807 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
809 *code_size = offset + 4;
814 * arch_emit_got_access:
816 * The memory pointed to by CODE should hold native code for loading a GOT
817 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
818 * CODE_SIZE is set to the number of bytes emitted.
821 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
823 /* Emit beginning of instruction */
824 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
826 /* Emit the offset */
828 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
829 *code_size = mono_arch_get_patch_offset (code) + 4;
830 #elif defined(TARGET_X86)
831 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
832 *code_size = mono_arch_get_patch_offset (code) + 4;
833 #elif defined(TARGET_ARM)
834 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
835 *code_size = mono_arch_get_patch_offset (code) + 4;
836 #elif defined(TARGET_POWERPC)
842 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
843 g_assert (code - buf == 8);
844 emit_bytes (acfg, buf, code - buf);
845 *code_size = code - buf;
848 g_assert_not_reached ();
854 #ifdef MONO_ARCH_AOT_SUPPORTED
856 * arch_emit_objc_selector_ref:
858 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
861 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
863 #if defined(TARGET_ARM)
866 int lindex = acfg->objc_selector_index_2 ++;
869 emit_bytes (acfg, code, 8);
871 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
872 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
874 emit_label (acfg, symbol1);
875 img_writer_emit_unset_mode (acfg->w);
876 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
880 g_assert_not_reached ();
886 * arch_emit_plt_entry:
888 * Emit code for the PLT entry with index INDEX.
891 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
893 #if defined(TARGET_X86)
894 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
895 #if defined(__default_codegen__)
896 /* jmp *<offset>(%ebx) */
897 emit_byte (acfg, 0xff);
898 emit_byte (acfg, 0xa3);
899 emit_int32 (acfg, offset);
900 /* Used by mono_aot_get_plt_info_offset */
901 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
902 #elif defined(__native_client_codegen__)
903 const guint8 kSizeOfNaClJmp = 11;
904 guint8 bytes[kSizeOfNaClJmp];
905 guint8 *pbytes = &bytes[0];
907 x86_jump_membase32 (pbytes, X86_EBX, offset);
908 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
909 /* four bytes of data, used by mono_arch_patch_plt_entry */
910 /* For Native Client, make this work with data embedded in push. */
911 emit_byte (acfg, 0x68); /* hide data in a push */
912 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
913 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
914 #endif /*__native_client_codegen__*/
915 #elif defined(TARGET_AMD64)
916 #if defined(__default_codegen__)
918 * We can't emit jumps because they are 32 bits only so they can't be patched.
919 * So we make indirect calls through GOT entries which are patched by the AOT
920 * loader to point to .Lpd entries.
922 /* jmpq *<offset>(%rip) */
923 emit_byte (acfg, '\xff');
924 emit_byte (acfg, '\x25');
925 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
926 /* Used by mono_aot_get_plt_info_offset */
927 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
928 #elif defined(__native_client_codegen__)
930 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
931 guint8 *code = buf_aligned;
933 /* mov <OFFSET>(%rip), %r11d */
934 emit_byte (acfg, '\x45');
935 emit_byte (acfg, '\x8b');
936 emit_byte (acfg, '\x1d');
937 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
939 amd64_jump_reg (code, AMD64_R11);
940 /* This should be constant for the plt patch */
941 g_assert ((size_t)(code-buf_aligned) == 10);
942 emit_bytes (acfg, buf_aligned, code - buf_aligned);
944 /* Hide data in a push imm32 so it passes validation */
945 emit_byte (acfg, 0x68); /* push */
946 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
947 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
948 #endif /*__native_client_codegen__*/
949 #elif defined(TARGET_ARM)
954 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
955 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
956 emit_bytes (acfg, buf, code - buf);
957 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
958 /* Used by mono_aot_get_plt_info_offset */
959 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
960 #elif defined(TARGET_POWERPC)
961 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
963 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
964 g_assert (!acfg->use_bin_writer);
965 emit_unset_mode (acfg);
966 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
967 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
968 fprintf (acfg->fp, "add 11, 11, 30\n");
969 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
970 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
971 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
972 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
974 fprintf (acfg->fp, "mtctr 11\n");
975 fprintf (acfg->fp, "bctr\n");
976 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
978 g_assert_not_reached ();
983 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
985 #if defined(TARGET_ARM)
987 /* LLVM calls the PLT entries using bl, so emit a stub */
988 /* FIXME: Too much overhead on every call */
989 fprintf (acfg->fp, ".thumb_func\n");
990 fprintf (acfg->fp, "bx pc\n");
991 fprintf (acfg->fp, "nop\n");
992 fprintf (acfg->fp, ".arm\n");
994 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
995 /* The caller already transitioned to thumb */
996 /* The code below should be 12 bytes long */
997 /* clang has trouble encoding these instructions, so emit the binary */
999 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1000 /* thumb can't encode ld pc, [pc, ip] */
1001 fprintf (acfg->fp, "add ip, pc, ip\n");
1002 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1003 fprintf (acfg->fp, "bx ip\n");
1005 emit_set_thumb_mode (acfg);
1006 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1007 fprintf (acfg->fp, ".2byte 0x44fc\n");
1008 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1009 fprintf (acfg->fp, ".2byte 0x4760\n");
1010 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
1011 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
1012 emit_unset_mode (acfg);
1013 emit_set_arm_mode (acfg);
1015 g_assert_not_reached ();
1020 * arch_emit_specific_trampoline_pages:
1022 * Emits a page full of trampolines: each trampoline uses its own address to
1023 * lookup both the generic trampoline code and the data argument.
1024 * This page can be remapped in process multiple times so we can get an
1025 * unlimited number of trampolines.
1026 * Specifically this implementation uses the following trick: two memory pages
1027 * are allocated, with the first containing the data and the second containing the trampolines.
1028 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1029 * implementation does all the lifting.
1030 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1031 * on the arm 32 bit system.
1034 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1036 #if defined(TARGET_ARM)
1039 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1041 #define COMMON_TRAMP_SIZE 16
1042 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1043 int imm8, rot_amount;
1046 if (!acfg->aot_opts.use_trampolines_page)
1049 acfg->tramp_page_size = mono_pagesize ();
1051 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1052 emit_alignment (acfg, mono_pagesize ());
1053 emit_global (acfg, symbol, TRUE);
1054 emit_label (acfg, symbol);
1056 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1058 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1059 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1060 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1061 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1063 g_assert (code - buf == COMMON_TRAMP_SIZE);
1066 emit_bytes (acfg, buf, code - buf);
1068 for (i = 0; i < count; ++i) {
1070 ARM_PUSH (code, 0x5fff);
1072 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1073 g_assert (code - buf == 8);
1074 emit_bytes (acfg, buf, code - buf);
1077 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1078 * the instruction pointer address, so the generic trampoline at the start of the page
1079 * subtracts 4096 to get to the data page and loads the values
1080 * We again fit the generic trampiline in 16 bytes.
1082 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1083 emit_global (acfg, symbol, TRUE);
1084 emit_label (acfg, symbol);
1086 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1087 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1088 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1089 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1091 g_assert (code - buf == COMMON_TRAMP_SIZE);
1094 emit_bytes (acfg, buf, code - buf);
1096 for (i = 0; i < count; ++i) {
1098 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1100 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1101 g_assert (code - buf == 8);
1102 emit_bytes (acfg, buf, code - buf);
1106 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1108 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1109 emit_global (acfg, symbol, TRUE);
1110 emit_label (acfg, symbol);
1112 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1113 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1114 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1115 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1116 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1117 g_assert (code - buf == COMMON_TRAMP_SIZE);
1119 emit_bytes (acfg, buf, code - buf);
1121 for (i = 0; i < count; ++i) {
1123 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1125 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1126 g_assert (code - buf == 8);
1127 emit_bytes (acfg, buf, code - buf);
1130 /* now the imt trampolines: each specific trampolines puts in the ip register
1131 * the instruction pointer address, so the generic trampoline at the start of the page
1132 * subtracts 4096 to get to the data page and loads the values
1133 * We again fit the generic trampiline in 16 bytes.
1135 #define IMT_TRAMP_SIZE 72
1136 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1137 emit_global (acfg, symbol, TRUE);
1138 emit_label (acfg, symbol);
1140 /* Need at least two free registers, plus a slot for storing the pc */
1141 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1143 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1144 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1145 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1147 /* The IMT method is in v5, r0 has the imt array address */
1150 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1151 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1152 imt_found_check = code;
1153 ARM_B_COND (code, ARMCOND_EQ, 0);
1155 /* End-of-loop check */
1156 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1157 loop_end_check = code;
1158 ARM_B_COND (code, ARMCOND_EQ, 0);
1161 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1162 loop_branch_back = code;
1164 arm_patch (loop_branch_back, loop_start);
1167 arm_patch (imt_found_check, code);
1168 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1169 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1170 /* Save it to the third stack slot */
1171 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1172 /* Restore the registers and branch */
1173 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1176 arm_patch (loop_end_check, code);
1177 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1178 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1179 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1183 g_assert (code - buf == IMT_TRAMP_SIZE);
1184 emit_bytes (acfg, buf, code - buf);
1186 for (i = 0; i < count; ++i) {
1188 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1190 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1191 g_assert (code - buf == 8);
1192 emit_bytes (acfg, buf, code - buf);
1198 * arch_emit_specific_trampoline:
1200 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1201 * two GOT slots which contain the generic trampoline address and the trampoline
1202 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1205 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1208 * The trampolines created here are variations of the specific
1209 * trampolines created in mono_arch_create_specific_trampoline (). The
1211 * - the generic trampoline address is taken from a got slot.
1212 * - the offset of the got slot where the trampoline argument is stored
1213 * is embedded in the instruction stream, and the generic trampoline
1214 * can load the argument by loading the offset, adding it to the
1215 * address of the trampoline to get the address of the got slot, and
1216 * loading the argument from there.
1217 * - all the trampolines should be of the same length.
1219 #if defined(TARGET_AMD64)
1220 #if defined(__default_codegen__)
1221 /* This should be exactly 16 bytes long */
1223 /* call *<offset>(%rip) */
1224 emit_byte (acfg, '\x41');
1225 emit_byte (acfg, '\xff');
1226 emit_byte (acfg, '\x15');
1227 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1228 /* This should be relative to the start of the trampoline */
1229 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1230 emit_zero_bytes (acfg, 5);
1231 #elif defined(__native_client_codegen__)
1233 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1234 guint8 *code = buf_aligned;
1239 /* Emit this call in 'code' so we can find out how long it is. */
1240 amd64_call_reg (code, AMD64_R11);
1241 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1242 call_len = code - call_start;
1244 /* The tramp_size is twice the NaCl alignment because it starts with */
1245 /* a call which needs to be aligned to the end of the boundary. */
1246 *tramp_size = kNaClAlignment*2;
1248 /* Emit nops to align call site below which is 7 bytes plus */
1249 /* the length of the call sequence emitted above. */
1250 /* Note: this requires the specific trampoline starts on a */
1251 /* kNaclAlignedment aligned address, which it does because */
1252 /* it's its own function that is aligned. */
1253 guint8 nop_buf[256];
1254 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1255 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1256 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1258 /* The trampoline is stored at the offset'th pointer, the -4 is */
1259 /* present because RIP relative addressing starts at the end of */
1260 /* the current instruction, while the label "." is relative to */
1261 /* the beginning of the current asm location, which in this case */
1262 /* is not the mov instruction, but the offset itself, due to the */
1263 /* way the bytes and ints are emitted here. */
1264 got_offset = (offset * sizeof(gpointer)) - 4;
1266 /* mov <OFFSET>(%rip), %r11d */
1267 emit_byte (acfg, '\x45');
1268 emit_byte (acfg, '\x8b');
1269 emit_byte (acfg, '\x1d');
1270 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1273 emit_bytes (acfg, call_start, call_len);
1275 /* The arg is stored at the offset+1 pointer, relative to beginning */
1276 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1277 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1279 /* We can't emit this data directly, hide in a "push imm32" */
1280 emit_byte (acfg, '\x68'); /* push */
1281 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1282 emit_alignment (acfg, kNaClAlignment);
1283 #endif /*__native_client_codegen__*/
1284 #elif defined(TARGET_ARM)
1288 /* This should be exactly 20 bytes long */
1291 ARM_PUSH (code, 0x5fff);
1292 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1293 /* Load the value from the GOT */
1294 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1296 ARM_BLX_REG (code, ARMREG_R1);
1298 g_assert (code - buf == 16);
1301 emit_bytes (acfg, buf, code - buf);
1303 * Only one offset is needed, since the second one would be equal to the
1306 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1307 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1308 #elif defined(TARGET_POWERPC)
1315 g_assert (!acfg->use_bin_writer);
1318 * PPC has no ip relative addressing, so we need to compute the address
1319 * of the mscorlib got. That is slow and complex, so instead, we store it
1320 * in the second got slot of every aot image. The caller already computed
1321 * the address of its got and placed it into r30.
1323 emit_unset_mode (acfg);
1324 /* Load mscorlib got address */
1325 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1326 /* Load generic trampoline address */
1327 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1328 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1329 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1330 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1331 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1333 fprintf (acfg->fp, "mtctr 11\n");
1334 /* Load trampoline argument */
1335 /* On ppc, we pass it normally to the generic trampoline */
1336 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1337 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1338 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1339 /* Branch to generic trampoline */
1340 fprintf (acfg->fp, "bctr\n");
1342 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1343 *tramp_size = 10 * 4;
1345 *tramp_size = 9 * 4;
1347 #elif defined(TARGET_X86)
1351 /* Similar to the PPC code above */
1353 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1355 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1356 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1357 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1361 /* Load mscorlib got address */
1362 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1363 /* Push trampoline argument */
1364 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1365 /* Load generic trampoline address */
1366 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1367 /* Branch to generic trampoline */
1368 x86_jump_reg (code, X86_ECX);
1370 #ifdef __native_client_codegen__
1372 /* emit nops to next 32 byte alignment */
1373 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1374 while (code < (buf + a)) x86_nop(code);
1377 emit_bytes (acfg, buf, code - buf);
1379 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1380 g_assert (code - buf == *tramp_size);
1382 g_assert_not_reached ();
1387 * arch_emit_unbox_trampoline:
1389 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1390 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1393 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1395 #if defined(TARGET_AMD64)
1400 this_reg = mono_arch_get_this_arg_reg (NULL);
1402 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1404 emit_bytes (acfg, buf, code - buf);
1406 emit_byte (acfg, '\xe9');
1407 emit_symbol_diff (acfg, call_target, ".", -4);
1408 #elif defined(TARGET_X86)
1415 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1417 emit_bytes (acfg, buf, code - buf);
1420 emit_byte (acfg, '\xe9');
1421 emit_symbol_diff (acfg, call_target, ".", -4);
1422 #elif defined(TARGET_ARM)
1426 if (acfg->thumb_mixed && cfg->compile_llvm) {
1427 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1428 fprintf (acfg->fp, "b %s\n", call_target);
1429 fprintf (acfg->fp, ".arm\n");
1430 fprintf (acfg->fp, ".align 2\n");
1436 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1438 emit_bytes (acfg, buf, code - buf);
1439 /* jump to method */
1440 if (acfg->use_bin_writer) {
1447 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1448 emit_bytes (acfg, buf, 4);
1450 if (acfg->thumb_mixed && cfg->compile_llvm)
1451 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1453 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1455 #elif defined(TARGET_POWERPC)
1458 g_assert (!acfg->use_bin_writer);
1460 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1461 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1463 g_assert_not_reached ();
1468 * arch_emit_static_rgctx_trampoline:
1470 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1471 * two GOT slots which contain the rgctx argument, and the method to jump to.
1472 * TRAMP_SIZE is set to the size of the emitted trampoline.
1473 * These kinds of trampolines cannot be enumerated statically, since there could
1474 * be one trampoline per method instantiation, so we emit the same code for all
1475 * trampolines, and parameterize them using two GOT slots.
1478 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1480 #if defined(TARGET_AMD64)
1481 #if defined(__default_codegen__)
1482 /* This should be exactly 13 bytes long */
1485 /* mov <OFFSET>(%rip), %r10 */
1486 emit_byte (acfg, '\x4d');
1487 emit_byte (acfg, '\x8b');
1488 emit_byte (acfg, '\x15');
1489 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1491 /* jmp *<offset>(%rip) */
1492 emit_byte (acfg, '\xff');
1493 emit_byte (acfg, '\x25');
1494 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1495 #elif defined(__native_client_codegen__)
1497 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1498 guint8 *code = buf_aligned;
1500 /* mov <OFFSET>(%rip), %r10d */
1501 emit_byte (acfg, '\x45');
1502 emit_byte (acfg, '\x8b');
1503 emit_byte (acfg, '\x15');
1504 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1506 /* mov <OFFSET>(%rip), %r11d */
1507 emit_byte (acfg, '\x45');
1508 emit_byte (acfg, '\x8b');
1509 emit_byte (acfg, '\x1d');
1510 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1513 amd64_jump_reg (code, AMD64_R11);
1514 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1516 emit_alignment (acfg, kNaClAlignment);
1517 *tramp_size = kNaClAlignment;
1518 #endif /*__native_client_codegen__*/
1520 #elif defined(TARGET_ARM)
1524 /* This should be exactly 24 bytes long */
1527 /* Load rgctx value */
1528 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1529 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1530 /* Load branch addr + branch */
1531 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1532 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1534 g_assert (code - buf == 16);
1537 emit_bytes (acfg, buf, code - buf);
1538 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1539 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1540 #elif defined(TARGET_POWERPC)
1547 g_assert (!acfg->use_bin_writer);
1550 * PPC has no ip relative addressing, so we need to compute the address
1551 * of the mscorlib got. That is slow and complex, so instead, we store it
1552 * in the second got slot of every aot image. The caller already computed
1553 * the address of its got and placed it into r30.
1555 emit_unset_mode (acfg);
1556 /* Load mscorlib got address */
1557 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1559 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1560 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1561 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1562 /* Load target address */
1563 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1564 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1565 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1566 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1567 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1568 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1570 fprintf (acfg->fp, "mtctr 11\n");
1571 /* Branch to the target address */
1572 fprintf (acfg->fp, "bctr\n");
1574 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1575 *tramp_size = 11 * 4;
1577 *tramp_size = 9 * 4;
1580 #elif defined(TARGET_X86)
1584 /* Similar to the PPC code above */
1586 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1589 /* Load mscorlib got address */
1590 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1592 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1593 /* Branch to the target address */
1594 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1596 #ifdef __native_client_codegen__
1598 /* emit nops to next 32 byte alignment */
1599 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1600 while (code < (buf + a)) x86_nop(code);
1604 emit_bytes (acfg, buf, code - buf);
1606 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1607 g_assert (code - buf == *tramp_size);
1609 g_assert_not_reached ();
1614 * arch_emit_imt_thunk:
1616 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1617 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1618 * key is the IMT key, and ptr holds the address of a memory location holding
1619 * the address to branch to if the IMT arg matches the key. The array is
1620 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1622 * TRAMP_SIZE is set to the size of the emitted trampoline.
1625 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1627 #if defined(TARGET_AMD64)
1629 #if defined(__native_client_codegen__)
1632 guint8 *labels [16];
1634 guint8 *mov_buf_ptr = mov_buf;
1636 const int kSizeOfMove = 7;
1637 #if defined(__default_codegen__)
1638 code = buf = g_malloc (256);
1639 #elif defined(__native_client_codegen__)
1640 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1641 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1642 /* The RIP relative move below is emitted first */
1647 /* FIXME: Optimize this, i.e. use binary search etc. */
1648 /* Maybe move the body into a separate function (slower, but much smaller) */
1650 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1653 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1655 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1658 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1660 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1663 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1664 amd64_jump_code (code, labels [0]);
1667 mono_amd64_patch (labels [2], code);
1668 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1669 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1672 mono_amd64_patch (labels [1], code);
1673 /* Load fail tramp */
1674 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1675 /* Check if there is a fail tramp */
1676 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1678 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1679 /* Jump to fail tramp */
1680 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1683 mono_amd64_patch (labels [3], code);
1684 x86_breakpoint (code);
1686 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1687 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1688 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1689 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1690 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1691 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1693 emit_bytes (acfg, buf, code - buf);
1695 *tramp_size = code - buf + kSizeOfMove;
1696 #if defined(__native_client_codegen__)
1697 /* The tramp will be padded to the next kNaClAlignment bundle. */
1698 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1701 #if defined(__default_codegen__)
1703 #elif defined(__native_client_codegen__)
1707 #elif defined(TARGET_X86)
1709 #ifdef __native_client_codegen__
1712 guint8 *labels [16];
1714 #if defined(__default_codegen__)
1715 code = buf = g_malloc (256);
1716 #elif defined(__native_client_codegen__)
1717 buf_alloc = g_malloc (256 + kNaClAlignment);
1718 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1721 /* Allocate a temporary stack slot */
1722 x86_push_reg (code, X86_EAX);
1724 x86_push_reg (code, X86_EAX);
1726 /* Load mscorlib got address */
1727 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1729 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1732 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1734 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1737 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1739 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1742 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1743 x86_jump_code (code, labels [0]);
1746 mono_x86_patch (labels [2], code);
1747 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1748 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1749 /* Save the target address to the temporary stack location */
1750 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1752 x86_pop_reg (code, X86_EAX);
1753 /* Jump to the target address */
1757 mono_x86_patch (labels [1], code);
1758 /* Load fail tramp */
1759 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1760 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1762 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1763 /* Jump to fail tramp */
1764 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1765 x86_pop_reg (code, X86_EAX);
1769 mono_x86_patch (labels [3], code);
1770 x86_breakpoint (code);
1772 #ifdef __native_client_codegen__
1774 /* emit nops to next 32 byte alignment */
1775 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1776 while (code < (buf + a)) x86_nop(code);
1779 emit_bytes (acfg, buf, code - buf);
1781 *tramp_size = code - buf;
1783 #if defined(__default_codegen__)
1785 #elif defined(__native_client_codegen__)
1789 #elif defined(TARGET_ARM)
1791 guint8 *code, *code2, *labels [16];
1795 /* The IMT method is in v5 */
1797 /* Need at least two free registers, plus a slot for storing the pc */
1798 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1800 /* Load the parameter from the GOT */
1801 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1802 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1805 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1806 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1808 ARM_B_COND (code, ARMCOND_EQ, 0);
1810 /* End-of-loop check */
1811 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1813 ARM_B_COND (code, ARMCOND_EQ, 0);
1816 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1819 arm_patch (labels [4], labels [1]);
1822 arm_patch (labels [2], code);
1823 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1824 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1825 /* Save it to the third stack slot */
1826 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1827 /* Restore the registers and branch */
1828 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1831 arm_patch (labels [3], code);
1832 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1833 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1834 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1838 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1840 emit_bytes (acfg, buf, code - buf);
1841 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1843 *tramp_size = code - buf + 4;
1844 #elif defined(TARGET_POWERPC)
1846 guint8 *code, *labels [16];
1850 /* Load the mscorlib got address */
1851 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1852 /* Load the parameter from the GOT */
1853 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1854 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1856 /* Load and check key */
1858 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1859 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1861 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1863 /* End-of-loop check */
1864 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1866 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1869 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1872 mono_ppc_patch (labels [4], labels [1]);
1875 mono_ppc_patch (labels [2], code);
1876 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1877 /* r11 now contains the value of the vtable slot */
1878 /* this is not a function descriptor on ppc64 */
1879 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1880 ppc_mtctr (code, ppc_r11);
1881 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1884 mono_ppc_patch (labels [3], code);
1888 *tramp_size = code - buf;
1890 emit_bytes (acfg, buf, code - buf);
1892 g_assert_not_reached ();
1897 * arch_emit_gsharedvt_arg_trampoline:
1899 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1900 * two GOT slots which contain the argument, and the code to jump to.
1901 * TRAMP_SIZE is set to the size of the emitted trampoline.
1902 * These kinds of trampolines cannot be enumerated statically, since there could
1903 * be one trampoline per method instantiation, so we emit the same code for all
1904 * trampolines, and parameterize them using two GOT slots.
1907 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1909 #if defined(TARGET_X86)
1913 /* Similar to the PPC code above */
1915 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1918 /* Load mscorlib got address */
1919 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1921 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1922 /* Branch to the target address */
1923 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1925 #ifdef __native_client_codegen__
1927 /* emit nops to next 32 byte alignment */
1928 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1929 while (code < (buf + a)) x86_nop(code);
1933 emit_bytes (acfg, buf, code - buf);
1935 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1936 g_assert (code - buf == *tramp_size);
1937 #elif defined(TARGET_ARM)
1941 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1942 /* Similar to arch_emit_specific_trampoline () */
1945 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1946 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1947 /* Load the arg value from the GOT */
1948 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1949 /* Load the addr from the GOT */
1950 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1952 ARM_BX (code, ARMREG_R1);
1954 g_assert (code - buf == 20);
1957 emit_bytes (acfg, buf, code - buf);
1958 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1960 g_assert_not_reached ();
1965 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1967 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1968 /* Based on code generated by gcc */
1969 emit_unset_mode (acfg);
1972 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1973 ".section .ctors,\"aw\",@progbits\n"
1977 ".section .opd,\"aw\"\n"
1980 ".long .%s,.TOC.@tocbase32\n"
1983 ".type .%s,@function\n"
1985 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1987 ".section .ctors,\"aw\",@progbits\n"
1991 ".section .opd,\"aw\"\n"
1994 ".long .%1$s,.TOC.@tocbase32\n"
1995 ".size %1$s,.-%1$s\n"
1997 ".type .%1$s,@function\n"
1999 ".%1$s:\n", symbol);
2010 "lis 3, .Lglobals@h\n"
2011 "ori 3, 3, .Lglobals@l\n"
2012 "bl .mono_aot_register_module\n"
2020 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2022 ".size .%s,.-.%s\n", symbol, symbol);
2025 ".size .%1$s,.-.%1$s\n", symbol);
2031 /* END OF ARCH SPECIFIC CODE */
2034 mono_get_field_token (MonoClassField *field)
2036 MonoClass *klass = field->parent;
2039 for (i = 0; i < klass->field.count; ++i) {
2040 if (field == &klass->fields [i])
2041 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2044 g_assert_not_reached ();
2049 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2053 //printf ("ENCODE: %d 0x%x.\n", value, value);
2056 * Same encoding as the one used in the metadata, extended to handle values
2057 * greater than 0x1fffffff.
2059 if ((value >= 0) && (value <= 127))
2061 else if ((value >= 0) && (value <= 16383)) {
2062 p [0] = 0x80 | (value >> 8);
2063 p [1] = value & 0xff;
2065 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2066 p [0] = (value >> 24) | 0xc0;
2067 p [1] = (value >> 16) & 0xff;
2068 p [2] = (value >> 8) & 0xff;
2069 p [3] = value & 0xff;
2074 p [1] = (value >> 24) & 0xff;
2075 p [2] = (value >> 16) & 0xff;
2076 p [3] = (value >> 8) & 0xff;
2077 p [4] = value & 0xff;
2085 stream_init (MonoDynamicStream *sh)
2088 sh->alloc_size = 4096;
2089 sh->data = g_malloc (4096);
2091 /* So offsets are > 0 */
2097 make_room_in_stream (MonoDynamicStream *stream, int size)
2099 if (size <= stream->alloc_size)
2102 while (stream->alloc_size <= size) {
2103 if (stream->alloc_size < 4096)
2104 stream->alloc_size = 4096;
2106 stream->alloc_size *= 2;
2109 stream->data = g_realloc (stream->data, stream->alloc_size);
2113 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2117 make_room_in_stream (stream, stream->index + len);
2118 memcpy (stream->data + stream->index, data, len);
2119 idx = stream->index;
2120 stream->index += len;
2127 * Add data to the binary blob inside the aot image. Returns the offset inside the
2128 * blob where the data was stored.
2131 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2133 if (acfg->blob.alloc_size == 0)
2134 stream_init (&acfg->blob);
2136 return add_stream_data (&acfg->blob, (char*)data, data_len);
2140 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2145 if (acfg->blob.alloc_size == 0)
2146 stream_init (&acfg->blob);
2148 count = acfg->blob.index % align;
2150 /* we assume the stream data will be aligned */
2152 add_stream_data (&acfg->blob, buf, 4 - count);
2154 return add_stream_data (&acfg->blob, (char*)data, data_len);
2158 * emit_offset_table:
2160 * Emit a table of increasing offsets in a compact form using differential encoding.
2161 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2162 * group size, the more compact the table becomes, but the slower it becomes to compute
2163 * a given entry. Returns the size of the table.
2166 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2168 gint32 current_offset;
2169 int i, buf_size, ngroups, index_entry_size;
2171 guint32 *index_offsets;
2173 ngroups = (noffsets + (group_size - 1)) / group_size;
2175 index_offsets = g_new0 (guint32, ngroups);
2177 buf_size = noffsets * 4;
2178 p = buf = g_malloc0 (buf_size);
2181 for (i = 0; i < noffsets; ++i) {
2182 //printf ("D: %d -> %d\n", i, offsets [i]);
2183 if ((i % group_size) == 0) {
2184 index_offsets [i / group_size] = p - buf;
2185 /* Emit the full value for these entries */
2186 encode_value (offsets [i], p, &p);
2188 /* The offsets are allowed to be non-increasing */
2189 //g_assert (offsets [i] >= current_offset);
2190 encode_value (offsets [i] - current_offset, p, &p);
2192 current_offset = offsets [i];
2195 if (ngroups && index_offsets [ngroups - 1] < 65000)
2196 index_entry_size = 2;
2198 index_entry_size = 4;
2200 /* Emit the header */
2201 emit_int32 (acfg, noffsets);
2202 emit_int32 (acfg, group_size);
2203 emit_int32 (acfg, ngroups);
2204 emit_int32 (acfg, index_entry_size);
2206 /* Emit the index */
2207 for (i = 0; i < ngroups; ++i) {
2208 if (index_entry_size == 2)
2209 emit_int16 (acfg, index_offsets [i]);
2211 emit_int32 (acfg, index_offsets [i]);
2215 emit_bytes (acfg, buf, p - buf);
2217 return (int)(p - buf) + (ngroups * 4);
2221 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2225 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2229 index = g_hash_table_size (cfg->image_hash);
2230 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2231 g_ptr_array_add (cfg->image_table, image);
2237 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2240 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2242 /* FIXME: Search referenced images as well */
2243 if (!acfg->typespec_classes) {
2244 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2245 for (i = 0; i < len; ++i) {
2246 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2249 for (i = 0; i < len; ++i) {
2250 if (acfg->typespec_classes [i] == klass)
2255 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2261 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2264 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2267 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2270 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2273 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2278 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2282 if (klass->generic_class) {
2284 g_assert (klass->type_token);
2286 /* Find a typespec for a class if possible */
2287 token = find_typespec_for_class (acfg, klass);
2289 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2290 encode_value (token, p, &p);
2292 MonoClass *gclass = klass->generic_class->container_class;
2293 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2294 static int count = 0;
2297 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2298 encode_klass_ref (acfg, gclass, p, &p);
2299 encode_ginst (acfg, inst, p, &p);
2303 } else if (klass->type_token) {
2304 int iindex = get_image_index (acfg, klass->image);
2306 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2308 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2309 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2311 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2312 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2313 encode_value (get_image_index (acfg, klass->image), p, &p);
2315 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2316 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2317 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2319 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2320 encode_value (klass->byval_arg.type, p, &p);
2321 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2323 encode_value (container ? 1 : 0, p, &p);
2325 encode_value (container->is_method, p, &p);
2326 g_assert (par->serial == 0);
2327 if (container->is_method)
2328 encode_method_ref (acfg, container->owner.method, p, &p);
2330 encode_klass_ref (acfg, container->owner.klass, p, &p);
2332 encode_value (par->serial, p, &p);
2334 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2335 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2336 encode_type (acfg, &klass->byval_arg, p, &p);
2339 g_assert (klass->rank > 0);
2340 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2341 encode_value (klass->rank, p, &p);
2342 encode_klass_ref (acfg, klass->element_class, p, &p);
2350 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2351 * standard metadata encoding.
2354 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2356 gboolean shared = FALSE;
2359 * The encoding of generic instances is large so emit them only once.
2361 if (klass->generic_class) {
2363 g_assert (klass->type_token);
2365 /* Find a typespec for a class if possible */
2366 token = find_typespec_for_class (acfg, klass);
2369 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2374 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2378 buf2 = g_malloc (1024);
2381 encode_klass_ref_inner (acfg, klass, p, &p);
2382 g_assert (p - buf2 < 1024);
2384 offset = add_to_blob (acfg, buf2, p - buf2);
2387 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2393 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2394 encode_value (offset, p, &p);
2399 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2403 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2405 guint32 token = mono_get_field_token (field);
2408 encode_klass_ref (cfg, field->parent, p, &p);
2409 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2410 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2415 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2420 encode_value (inst->type_argc, p, &p);
2421 for (i = 0; i < inst->type_argc; ++i)
2422 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2427 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2430 MonoGenericInst *inst;
2432 inst = context->class_inst;
2434 g_assert (inst->type_argc);
2435 encode_ginst (acfg, inst, p, &p);
2437 encode_value (0, p, &p);
2439 inst = context->method_inst;
2441 g_assert (inst->type_argc);
2442 encode_ginst (acfg, inst, p, &p);
2444 encode_value (0, p, &p);
2450 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2454 g_assert (t->num_mods == 0);
2455 /* t->attrs can be ignored */
2456 //g_assert (t->attrs == 0);
2459 *p = MONO_TYPE_PINNED;
2463 *p = MONO_TYPE_BYREF;
2471 case MONO_TYPE_VOID:
2472 case MONO_TYPE_BOOLEAN:
2473 case MONO_TYPE_CHAR:
2486 case MONO_TYPE_STRING:
2487 case MONO_TYPE_OBJECT:
2488 case MONO_TYPE_TYPEDBYREF:
2490 case MONO_TYPE_VALUETYPE:
2491 case MONO_TYPE_CLASS:
2492 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2494 case MONO_TYPE_SZARRAY:
2495 encode_klass_ref (acfg, t->data.klass, p, &p);
2498 encode_type (acfg, t->data.type, p, &p);
2500 case MONO_TYPE_GENERICINST: {
2501 MonoClass *gclass = t->data.generic_class->container_class;
2502 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2504 encode_klass_ref (acfg, gclass, p, &p);
2505 encode_ginst (acfg, inst, p, &p);
2508 case MONO_TYPE_ARRAY: {
2509 MonoArrayType *array = t->data.array;
2512 encode_klass_ref (acfg, array->eklass, p, &p);
2513 encode_value (array->rank, p, &p);
2514 encode_value (array->numsizes, p, &p);
2515 for (i = 0; i < array->numsizes; ++i)
2516 encode_value (array->sizes [i], p, &p);
2517 encode_value (array->numlobounds, p, &p);
2518 for (i = 0; i < array->numlobounds; ++i)
2519 encode_value (array->lobounds [i], p, &p);
2523 case MONO_TYPE_MVAR:
2524 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2527 g_assert_not_reached ();
2534 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2540 /* Similar to the metadata encoding */
2541 if (sig->generic_param_count)
2545 if (sig->explicit_this)
2547 flags |= (sig->call_convention & 0x0F);
2551 if (sig->generic_param_count)
2552 encode_value (sig->generic_param_count, p, &p);
2553 encode_value (sig->param_count, p, &p);
2555 encode_type (acfg, sig->ret, p, &p);
2556 for (i = 0; i < sig->param_count; ++i) {
2557 if (sig->sentinelpos == i) {
2558 *p = MONO_TYPE_SENTINEL;
2561 encode_type (acfg, sig->params [i], p, &p);
2567 #define MAX_IMAGE_INDEX 250
2570 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2572 guint32 image_index = get_image_index (acfg, method->klass->image);
2573 guint32 token = method->token;
2574 MonoJumpInfoToken *ji;
2578 * The encoding for most methods is as follows:
2579 * - image index encoded as a leb128
2580 * - token index encoded as a leb128
2581 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2582 * types of method encodings.
2585 /* Mark methods which can't use aot trampolines because they need the further
2586 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2588 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2589 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2590 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2592 if (method->wrapper_type) {
2593 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2595 encode_value (method->wrapper_type, p, &p);
2597 switch (method->wrapper_type) {
2598 case MONO_WRAPPER_REMOTING_INVOKE:
2599 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2600 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2603 m = mono_marshal_method_from_wrapper (method);
2605 encode_method_ref (acfg, m, p, &p);
2608 case MONO_WRAPPER_PROXY_ISINST:
2609 case MONO_WRAPPER_LDFLD:
2610 case MONO_WRAPPER_LDFLDA:
2611 case MONO_WRAPPER_STFLD:
2612 case MONO_WRAPPER_ISINST: {
2613 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2614 encode_klass_ref (acfg, proxy_class, p, &p);
2617 case MONO_WRAPPER_LDFLD_REMOTE:
2618 case MONO_WRAPPER_STFLD_REMOTE:
2620 case MONO_WRAPPER_ALLOC: {
2621 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2623 /* The GC name is saved once in MonoAotFileInfo */
2624 g_assert (info->alloc_type != -1);
2625 encode_value (info->alloc_type, p, &p);
2628 case MONO_WRAPPER_WRITE_BARRIER:
2630 case MONO_WRAPPER_STELEMREF: {
2631 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2634 encode_value (info->subtype, p, &p);
2635 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2636 encode_value (info->d.virtual_stelemref.kind, p, &p);
2639 case MONO_WRAPPER_UNKNOWN: {
2640 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2643 encode_value (info->subtype, p, &p);
2644 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2645 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2646 encode_klass_ref (acfg, method->klass, p, &p);
2647 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2648 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2649 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2650 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2653 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2654 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2657 encode_value (info->subtype, p, &p);
2658 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2659 strcpy ((char*)p, method->name);
2660 p += strlen (method->name) + 1;
2661 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2662 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2664 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2665 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2669 case MONO_WRAPPER_SYNCHRONIZED: {
2672 m = mono_marshal_method_from_wrapper (method);
2674 g_assert (m != method);
2675 encode_method_ref (acfg, m, p, &p);
2678 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2679 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2682 encode_value (info->subtype, p, &p);
2684 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2685 encode_value (info->d.element_addr.rank, p, &p);
2686 encode_value (info->d.element_addr.elem_size, p, &p);
2687 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2688 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2690 g_assert_not_reached ();
2694 case MONO_WRAPPER_CASTCLASS: {
2695 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2698 encode_value (info->subtype, p, &p);
2701 case MONO_WRAPPER_RUNTIME_INVOKE: {
2702 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2705 encode_value (info->subtype, p, &p);
2706 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2707 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2708 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2709 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2712 case MONO_WRAPPER_DELEGATE_INVOKE:
2713 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2714 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2715 if (method->is_inflated) {
2716 /* These wrappers are identified by their class */
2717 encode_value (1, p, &p);
2718 encode_klass_ref (acfg, method->klass, p, &p);
2720 MonoMethodSignature *sig = mono_method_signature (method);
2721 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2723 encode_value (0, p, &p);
2724 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2725 encode_value (info ? info->subtype : 0, p, &p);
2726 encode_signature (acfg, sig, p, &p);
2730 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2731 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2734 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2735 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2739 g_assert_not_reached ();
2741 } else if (mono_method_signature (method)->is_inflated) {
2743 * This is a generic method, find the original token which referenced it and
2745 * Obtain the token from information recorded by the JIT.
2747 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2749 image_index = get_image_index (acfg, ji->image);
2750 g_assert (image_index < MAX_IMAGE_INDEX);
2753 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2754 encode_value (image_index, p, &p);
2755 encode_value (token, p, &p);
2757 MonoMethod *declaring;
2758 MonoGenericContext *context = mono_method_get_context (method);
2760 g_assert (method->is_inflated);
2761 declaring = ((MonoMethodInflated*)method)->declaring;
2764 * This might be a non-generic method of a generic instance, which
2765 * doesn't have a token since the reference is generated by the JIT
2766 * like Nullable:Box/Unbox, or by generic sharing.
2768 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2769 /* Encode the klass */
2770 encode_klass_ref (acfg, method->klass, p, &p);
2771 /* Encode the method */
2772 image_index = get_image_index (acfg, method->klass->image);
2773 g_assert (image_index < MAX_IMAGE_INDEX);
2774 g_assert (declaring->token);
2775 token = declaring->token;
2776 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2777 encode_value (image_index, p, &p);
2778 encode_value (token, p, &p);
2779 encode_generic_context (acfg, context, p, &p);
2781 } else if (token == 0) {
2782 /* This might be a method of a constructed type like int[,].Set */
2783 /* Obtain the token from information recorded by the JIT */
2784 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2786 image_index = get_image_index (acfg, ji->image);
2787 g_assert (image_index < MAX_IMAGE_INDEX);
2790 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2791 encode_value (image_index, p, &p);
2792 encode_value (token, p, &p);
2795 g_assert (method->klass->rank);
2797 /* Encode directly */
2798 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2799 encode_klass_ref (acfg, method->klass, p, &p);
2800 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2801 encode_value (0, p, &p);
2802 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2803 encode_value (1, p, &p);
2804 else if (!strcmp (method->name, "Get"))
2805 encode_value (2, p, &p);
2806 else if (!strcmp (method->name, "Address"))
2807 encode_value (3, p, &p);
2808 else if (!strcmp (method->name, "Set"))
2809 encode_value (4, p, &p);
2811 g_assert_not_reached ();
2814 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2816 if (image_index >= MONO_AOT_METHODREF_MIN) {
2817 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2818 encode_value (image_index, p, &p);
2819 encode_value (mono_metadata_token_index (token), p, &p);
2821 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2828 compare_patches (gconstpointer a, gconstpointer b)
2832 i = (*(MonoJumpInfo**)a)->ip.i;
2833 j = (*(MonoJumpInfo**)b)->ip.i;
2844 static G_GNUC_UNUSED char*
2845 patch_to_string (MonoJumpInfo *patch_info)
2849 str = g_string_new ("");
2851 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2853 switch (patch_info->type) {
2854 case MONO_PATCH_INFO_VTABLE:
2855 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2860 g_string_append_printf (str, ")");
2861 return g_string_free (str, FALSE);
2867 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2870 static inline gboolean
2871 is_plt_patch (MonoJumpInfo *patch_info)
2873 switch (patch_info->type) {
2874 case MONO_PATCH_INFO_METHOD:
2875 case MONO_PATCH_INFO_INTERNAL_METHOD:
2876 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2877 case MONO_PATCH_INFO_ICALL_ADDR:
2878 case MONO_PATCH_INFO_CLASS_INIT:
2879 case MONO_PATCH_INFO_RGCTX_FETCH:
2880 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2881 case MONO_PATCH_INFO_MONITOR_ENTER:
2882 case MONO_PATCH_INFO_MONITOR_EXIT:
2883 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2893 * Return the symbol identifying the plt entry PLT_OFFSET.
2896 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2900 * The Apple linker reorganizes object files, so it doesn't like branches to local
2901 * labels, since those have no relocations.
2903 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2905 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2912 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2914 static MonoPltEntry*
2915 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2919 if (!is_plt_patch (patch_info))
2922 if (!acfg->patch_to_plt_entry [patch_info->type])
2923 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
2924 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
2926 // FIXME: This breaks the calculation of final_got_size
2927 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2929 * Allocate a separate PLT slot for each such patch, since some plt
2930 * entries will refer to the method itself, and some will refer to the
2937 MonoJumpInfo *new_ji;
2939 g_assert (!acfg->final_got_size);
2941 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2943 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2944 res->plt_offset = acfg->plt_offset;
2946 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2947 if (acfg->aot_opts.write_symbols)
2948 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2950 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2952 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2954 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
2956 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2958 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2959 //mono_print_ji (patch_info); printf ("\n");
2960 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2962 acfg->plt_offset ++;
2971 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2972 * JI could be found if it exists, otherwise allocates a new one.
2975 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2979 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2981 return got_offset - 1;
2983 got_offset = acfg->got_offset;
2984 acfg->got_offset ++;
2986 if (acfg->final_got_size)
2987 g_assert (got_offset < acfg->final_got_size);
2989 acfg->stats.got_slots ++;
2990 acfg->stats.got_slot_types [ji->type] ++;
2992 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2993 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2994 g_ptr_array_add (acfg->got_patches, ji);
2999 /* Add a method to the list of methods which need to be emitted */
3001 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3004 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3005 g_ptr_array_add (acfg->methods, method);
3006 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3007 acfg->nmethods = acfg->methods->len + 1;
3010 if (method->wrapper_type || extra)
3011 g_ptr_array_add (acfg->extra_methods, method);
3015 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3017 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3025 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3029 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3033 index = acfg->method_index;
3034 add_method_with_index (acfg, method, index, extra);
3036 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3038 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3040 acfg->method_index ++;
3046 add_method (MonoAotCompile *acfg, MonoMethod *method)
3048 return add_method_full (acfg, method, FALSE, 0);
3052 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3054 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3055 method = mini_get_shared_method (method);
3057 if (acfg->aot_opts.log_generics)
3058 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3060 add_method_full (acfg, method, TRUE, depth);
3064 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3066 add_extra_method_with_depth (acfg, method, 0);
3070 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3072 MonoAotCompile *acfg = user_data;
3073 MonoJitICallInfo *callinfo = value;
3074 MonoMethod *wrapper;
3080 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3081 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3084 add_method (acfg, wrapper);
3088 get_runtime_invoke_sig (MonoMethodSignature *sig)
3090 MonoMethodBuilder *mb;
3093 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3094 m = mono_mb_create_method (mb, sig, 16);
3095 return mono_marshal_get_runtime_invoke (m, FALSE);
3099 can_marshal_struct (MonoClass *klass)
3101 MonoClassField *field;
3102 gboolean can_marshal = TRUE;
3103 gpointer iter = NULL;
3104 MonoMarshalType *info;
3107 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3110 info = mono_marshal_load_type_info (klass);
3112 /* Only allow a few field types to avoid asserts in the marshalling code */
3113 while ((field = mono_class_get_fields (klass, &iter))) {
3114 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3117 switch (field->type->type) {
3122 case MONO_TYPE_BOOLEAN:
3125 case MONO_TYPE_CHAR:
3133 case MONO_TYPE_STRING:
3135 case MONO_TYPE_VALUETYPE:
3136 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3137 can_marshal = FALSE;
3139 case MONO_TYPE_SZARRAY: {
3140 gboolean has_mspec = FALSE;
3143 for (i = 0; i < info->num_fields; ++i) {
3144 if (info->fields [i].field == field && info->fields [i].mspec)
3149 can_marshal = FALSE;
3153 can_marshal = FALSE;
3159 /* Its hard to compute whenever these can be marshalled or not */
3160 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3167 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3169 /* Create a vtype instantiation */
3170 MonoGenericContext shared_context;
3172 MonoGenericInst *inst;
3173 MonoGenericContainer *container;
3174 MonoClass **constraints;
3177 memset (ctx, 0, sizeof (MonoGenericContext));
3179 if (method->klass->generic_container) {
3180 shared_context = method->klass->generic_container->context;
3181 inst = shared_context.class_inst;
3183 args = g_new0 (MonoType*, inst->type_argc);
3184 for (i = 0; i < inst->type_argc; ++i) {
3185 args [i] = &mono_defaults.int_class->byval_arg;
3187 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3189 if (method->is_generic) {
3190 container = mono_method_get_generic_container (method);
3191 shared_context = container->context;
3192 inst = shared_context.method_inst;
3194 args = g_new0 (MonoType*, inst->type_argc);
3195 for (i = 0; i < container->type_argc; ++i) {
3196 MonoGenericParamInfo *info = &container->type_params [i].info;
3197 gboolean ref_only = FALSE;
3199 if (info && info->constraints) {
3200 constraints = info->constraints;
3202 while (*constraints) {
3203 MonoClass *cklass = *constraints;
3204 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3205 /* Inflaring the method with our vtype would not be valid */
3212 args [i] = &mono_defaults.object_class->byval_arg;
3214 args [i] = &mono_defaults.int_class->byval_arg;
3216 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3221 add_wrappers (MonoAotCompile *acfg)
3223 MonoMethod *method, *m;
3225 MonoMethodSignature *sig, *csig;
3229 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3230 * so there is only one wrapper of a given type, or inlining their contents into their
3233 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3235 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3236 gboolean skip = FALSE;
3238 method = mono_get_method (acfg->image, token, NULL);
3240 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3241 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3242 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3245 /* Skip methods which can not be handled by get_runtime_invoke () */
3246 sig = mono_method_signature (method);
3249 if ((sig->ret->type == MONO_TYPE_PTR) ||
3250 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3252 if (mono_class_is_open_constructed_type (sig->ret))
3255 for (j = 0; j < sig->param_count; j++) {
3256 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3258 if (mono_class_is_open_constructed_type (sig->params [j]))
3262 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3263 if (!mono_class_is_contextbound (method->klass)) {
3264 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3265 gboolean has_nullable = FALSE;
3267 for (j = 0; j < sig->param_count; j++) {
3268 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3269 has_nullable = TRUE;
3272 if (info && !has_nullable) {
3273 /* Supported by the dynamic runtime-invoke wrapper */
3281 //printf ("%s\n", mono_method_full_name (method, TRUE));
3282 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3286 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3287 MonoMethodDesc *desc;
3288 MonoMethod *orig_method;
3291 /* Runtime invoke wrappers */
3293 /* void runtime-invoke () [.cctor] */
3294 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3295 csig->ret = &mono_defaults.void_class->byval_arg;
3296 add_method (acfg, get_runtime_invoke_sig (csig));
3298 /* void runtime-invoke () [Finalize] */
3299 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3301 csig->ret = &mono_defaults.void_class->byval_arg;
3302 add_method (acfg, get_runtime_invoke_sig (csig));
3304 /* void runtime-invoke (string) [exception ctor] */
3305 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3307 csig->ret = &mono_defaults.void_class->byval_arg;
3308 csig->params [0] = &mono_defaults.string_class->byval_arg;
3309 add_method (acfg, get_runtime_invoke_sig (csig));
3311 /* void runtime-invoke (string, string) [exception ctor] */
3312 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3314 csig->ret = &mono_defaults.void_class->byval_arg;
3315 csig->params [0] = &mono_defaults.string_class->byval_arg;
3316 csig->params [1] = &mono_defaults.string_class->byval_arg;
3317 add_method (acfg, get_runtime_invoke_sig (csig));
3319 /* string runtime-invoke () [Exception.ToString ()] */
3320 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3322 csig->ret = &mono_defaults.string_class->byval_arg;
3323 add_method (acfg, get_runtime_invoke_sig (csig));
3325 /* void runtime-invoke (string, Exception) [exception ctor] */
3326 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3328 csig->ret = &mono_defaults.void_class->byval_arg;
3329 csig->params [0] = &mono_defaults.string_class->byval_arg;
3330 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3331 add_method (acfg, get_runtime_invoke_sig (csig));
3333 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3334 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3336 csig->ret = &(mono_class_from_name (
3337 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3338 csig->params [0] = &mono_defaults.string_class->byval_arg;
3339 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3340 add_method (acfg, get_runtime_invoke_sig (csig));
3342 /* runtime-invoke used by finalizers */
3343 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3345 /* This is used by mono_runtime_capture_context () */
3346 method = mono_get_context_capture_method ();
3348 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3350 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3351 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3355 add_method (acfg, mono_marshal_get_stelemref ());
3357 if (MONO_ARCH_HAVE_TLS_GET) {
3358 /* Managed Allocators */
3359 nallocators = mono_gc_get_managed_allocator_types ();
3360 for (i = 0; i < nallocators; ++i) {
3361 m = mono_gc_get_managed_allocator_by_type (i);
3363 add_method (acfg, m);
3366 /* Monitor Enter/Exit */
3367 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3368 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3369 /* This is a v4 method */
3371 method = mono_monitor_get_fast_path (orig_method);
3373 add_method (acfg, method);
3375 mono_method_desc_free (desc);
3377 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3378 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3379 g_assert (orig_method);
3380 mono_method_desc_free (desc);
3381 method = mono_monitor_get_fast_path (orig_method);
3383 add_method (acfg, method);
3386 /* Stelemref wrappers */
3388 MonoMethod **wrappers;
3391 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3392 for (i = 0; i < nwrappers; ++i)
3393 add_method (acfg, wrappers [i]);
3397 /* castclass_with_check wrapper */
3398 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3399 /* isinst_with_check wrapper */
3400 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3402 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3404 MonoMethodDesc *desc;
3407 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3408 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3409 mono_method_desc_free (desc);
3411 m = mono_monitor_get_fast_path (m);
3413 add_method (acfg, m);
3418 /* JIT icall wrappers */
3419 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3420 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3424 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3425 * we use the original method instead at runtime.
3426 * Since full-aot doesn't support remoting, this is not a problem.
3429 /* remoting-invoke wrappers */
3430 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3431 MonoMethodSignature *sig;
3433 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3434 method = mono_get_method (acfg->image, token, NULL);
3436 sig = mono_method_signature (method);
3438 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3439 m = mono_marshal_get_remoting_invoke_with_check (method);
3441 add_method (acfg, m);
3446 /* delegate-invoke wrappers */
3447 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3449 MonoCustomAttrInfo *cattr;
3451 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3452 klass = mono_class_get (acfg->image, token);
3455 mono_loader_clear_error ();
3459 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3462 if (!klass->generic_container) {
3463 method = mono_get_delegate_invoke (klass);
3465 m = mono_marshal_get_delegate_invoke (method, NULL);
3467 add_method (acfg, m);
3469 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3471 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3473 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3475 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3477 cattr = mono_custom_attrs_from_class (klass);
3482 for (j = 0; j < cattr->num_attrs; ++j)
3483 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3485 if (j < cattr->num_attrs)
3486 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3488 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3489 MonoGenericContext ctx;
3490 MonoMethod *inst, *gshared;
3493 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3496 method = mono_get_delegate_invoke (klass);
3497 create_gsharedvt_inst (acfg, method, &ctx);
3499 inst = mono_class_inflate_generic_method (method, &ctx);
3501 m = mono_marshal_get_delegate_invoke (inst, NULL);
3502 g_assert (m->is_inflated);
3504 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3505 add_extra_method (acfg, gshared);
3508 method = mono_get_delegate_begin_invoke (klass);
3509 create_gsharedvt_inst (acfg, method, &ctx);
3511 inst = mono_class_inflate_generic_method (method, &ctx);
3513 m = mono_marshal_get_delegate_begin_invoke (inst);
3514 g_assert (m->is_inflated);
3516 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3517 add_extra_method (acfg, gshared);
3520 method = mono_get_delegate_end_invoke (klass);
3521 create_gsharedvt_inst (acfg, method, &ctx);
3523 inst = mono_class_inflate_generic_method (method, &ctx);
3525 m = mono_marshal_get_delegate_end_invoke (inst);
3526 g_assert (m->is_inflated);
3528 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3529 add_extra_method (acfg, gshared);
3534 /* array access wrappers */
3535 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3538 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3539 klass = mono_class_get (acfg->image, token);
3542 mono_loader_clear_error ();
3546 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3547 MonoMethod *m, *wrapper;
3549 /* Add runtime-invoke wrappers too */
3551 m = mono_class_get_method_from_name (klass, "Get", -1);
3553 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3554 add_extra_method (acfg, wrapper);
3555 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3557 m = mono_class_get_method_from_name (klass, "Set", -1);
3559 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3560 add_extra_method (acfg, wrapper);
3561 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3565 /* Synchronized wrappers */
3566 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3567 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3568 method = mono_get_method (acfg->image, token, NULL);
3570 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3571 if (method->is_generic) {
3573 } else if (method->klass->generic_container) {
3574 MonoGenericContext ctx;
3575 MonoMethod *inst, *gshared, *m;
3578 * Create a generic wrapper for a generic instance, and AOT that.
3580 create_gsharedvt_inst (acfg, method, &ctx);
3581 inst = mono_class_inflate_generic_method (method, &ctx);
3582 m = mono_marshal_get_synchronized_wrapper (inst);
3583 g_assert (m->is_inflated);
3584 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3585 add_method (acfg, gshared);
3587 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3592 /* pinvoke wrappers */
3593 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3595 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3597 method = mono_get_method (acfg->image, token, NULL);
3599 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3600 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3601 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3605 /* native-to-managed wrappers */
3606 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3608 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3609 MonoCustomAttrInfo *cattr;
3612 method = mono_get_method (acfg->image, token, NULL);
3615 * Only generate native-to-managed wrappers for methods which have an
3616 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3617 * name to avoid defining a new assembly to contain it.
3619 cattr = mono_custom_attrs_from_method (method);
3622 for (j = 0; j < cattr->num_attrs; ++j)
3623 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3625 if (j < cattr->num_attrs) {
3626 MonoCustomAttrEntry *e = &cattr->attrs [j];
3627 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3628 const char *p = (const char*)e->data;
3630 int slen, num_named, named_type, data_type;
3634 char *export_name = NULL;
3635 MonoMethod *wrapper;
3637 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3638 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3639 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3640 mono_method_full_name (method, TRUE));
3644 g_assert (sig->param_count == 1);
3645 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3648 * Decode the cattr manually since we can't create objects
3649 * during aot compilation.
3655 /* From load_cattr_value () in reflection.c */
3656 slen = mono_metadata_decode_value (p, &p);
3657 n = g_memdup (p, slen + 1);
3659 t = mono_reflection_type_from_name (n, acfg->image);
3663 klass = mono_class_from_mono_type (t);
3664 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3668 num_named = read16 (p);
3671 g_assert (num_named < 2);
3672 if (num_named == 1) {
3675 MonoType *prop_type;
3677 /* parse ExportSymbol attribute */
3679 named_type = *named;
3684 name_len = mono_metadata_decode_blob_size (named, &named);
3685 name = g_malloc (name_len + 1);
3686 memcpy (name, named, name_len);
3687 name [name_len] = 0;
3690 g_assert (named_type == 0x54);
3691 g_assert (!strcmp (name, "ExportSymbol"));
3693 prop_type = &mono_defaults.string_class->byval_arg;
3695 /* load_cattr_value (), string case */
3696 g_assert (*named != (char)0xff);
3697 slen = mono_metadata_decode_value (named, &named);
3698 export_name = g_malloc (slen + 1);
3699 memcpy (export_name, named, slen);
3700 export_name [slen] = 0;
3704 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3705 add_method (acfg, wrapper);
3707 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3711 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3712 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3713 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3717 /* StructureToPtr/PtrToStructure wrappers */
3718 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3721 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3722 klass = mono_class_get (acfg->image, token);
3725 mono_loader_clear_error ();
3729 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3730 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3731 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3732 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3738 has_type_vars (MonoClass *klass)
3740 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3743 return has_type_vars (klass->element_class);
3744 if (klass->generic_class) {
3745 MonoGenericContext *context = &klass->generic_class->context;
3746 if (context->class_inst) {
3749 for (i = 0; i < context->class_inst->type_argc; ++i)
3750 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3754 if (klass->generic_container)
3760 is_vt_inst (MonoGenericInst *inst)
3764 for (i = 0; i < inst->type_argc; ++i) {
3765 MonoType *t = inst->type_argv [i];
3766 if (t->type == MONO_TYPE_VALUETYPE)
3773 method_has_type_vars (MonoMethod *method)
3775 if (has_type_vars (method->klass))
3778 if (method->is_inflated) {
3779 MonoGenericContext *context = mono_method_get_context (method);
3780 if (context->method_inst) {
3783 for (i = 0; i < context->method_inst->type_argc; ++i)
3784 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3791 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3794 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3796 /* This might lead to a huge code blowup so only do it if neccesary */
3797 if (!acfg->aot_opts.full_aot && !force)
3800 add_generic_class_with_depth (acfg, klass, 0, ref);
3804 check_type_depth (MonoType *t, int depth)
3812 case MONO_TYPE_GENERICINST: {
3813 MonoGenericClass *gklass = t->data.generic_class;
3814 MonoGenericInst *ginst = gklass->context.class_inst;
3817 for (i = 0; i < ginst->type_argc; ++i) {
3818 if (check_type_depth (ginst->type_argv [i], depth + 1))
3832 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
3835 * add_generic_class:
3837 * Add all methods of a generic class.
3840 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3843 MonoClassField *field;
3845 gboolean use_gsharedvt = FALSE;
3847 if (!acfg->ginst_hash)
3848 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3850 mono_class_init (klass);
3852 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3855 if (has_type_vars (klass))
3858 if (!klass->generic_class && !klass->rank)
3861 if (klass->exception_type)
3864 if (!acfg->ginst_hash)
3865 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3867 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3870 if (check_type_depth (&klass->byval_arg, 0))
3873 if (acfg->aot_opts.log_generics)
3874 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3876 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3879 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
3880 * Enable this only for some classes since gsharedvt might not support all methods.
3882 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")))
3883 use_gsharedvt = TRUE;
3886 while ((method = mono_class_get_methods (klass, &iter))) {
3887 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
3889 * This is partial sharing, and we can't handle it yet
3894 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
3896 add_types_from_method_header (acfg, method);
3900 if (method->is_generic)
3905 * FIXME: Instances which are referenced by these methods are not added,
3906 * for example Array.Resize<int> for List<int>.Add ().
3908 add_extra_method_with_depth (acfg, method, depth + 1);
3912 while ((field = mono_class_get_fields (klass, &iter))) {
3913 if (field->type->type == MONO_TYPE_GENERICINST)
3914 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3917 if (klass->delegate) {
3918 method = mono_get_delegate_invoke (klass);
3920 method = mono_marshal_get_delegate_invoke (method, NULL);
3922 if (acfg->aot_opts.log_generics)
3923 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3925 add_method (acfg, method);
3928 /* Add superclasses */
3930 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3933 * For ICollection<T>, add instances of the helper methods
3934 * in Array, since a T[] could be cast to ICollection<T>.
3936 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3937 (!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"))) {
3938 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3939 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3943 if (!strcmp (klass->name, "IEnumerator`1"))
3944 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3946 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3948 /* Add the T[]/InternalEnumerator class */
3949 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3953 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3954 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3958 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3959 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3963 while ((method = mono_class_get_methods (array_class, &iter))) {
3964 if (strstr (method->name, name_prefix)) {
3965 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3967 add_extra_method_with_depth (acfg, m, depth);
3971 g_free (name_prefix);
3974 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3975 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3976 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3977 MonoClass *icomparable, *gcomparer;
3978 MonoGenericContext ctx;
3979 MonoType *args [16];
3981 memset (&ctx, 0, sizeof (ctx));
3983 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3984 g_assert (icomparable);
3985 args [0] = &tclass->byval_arg;
3986 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3988 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3989 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3990 g_assert (gcomparer);
3991 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3995 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3996 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3997 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3998 MonoClass *iface, *gcomparer;
3999 MonoGenericContext ctx;
4000 MonoType *args [16];
4002 memset (&ctx, 0, sizeof (ctx));
4004 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4006 args [0] = &tclass->byval_arg;
4007 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4009 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4010 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4011 g_assert (gcomparer);
4012 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4018 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4021 MonoGenericContext ctx;
4022 MonoType *args [16];
4024 if (acfg->aot_opts.no_instances)
4027 memset (&ctx, 0, sizeof (ctx));
4029 for (i = 0; i < ninsts; ++i) {
4030 args [0] = insts [i];
4031 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4032 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4037 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4039 MonoMethodHeader *header;
4040 MonoMethodSignature *sig;
4043 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4045 sig = mono_method_signature (method);
4048 for (j = 0; j < sig->param_count; ++j)
4049 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4050 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4053 header = mono_method_get_header (method);
4056 for (j = 0; j < header->num_locals; ++j)
4057 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4058 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4060 mono_loader_clear_error ();
4065 * add_generic_instances:
4067 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4070 add_generic_instances (MonoAotCompile *acfg)
4075 MonoGenericContext *context;
4077 if (acfg->aot_opts.no_instances)
4080 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4081 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4082 method = mono_get_method (acfg->image, token, NULL);
4087 if (method->klass->image != acfg->image)
4090 context = mono_method_get_context (method);
4092 if (context && ((context->class_inst && context->class_inst->is_open)))
4096 * For open methods, create an instantiation which can be passed to the JIT.
4097 * FIXME: Handle class_inst as well.
4099 if (context && context->method_inst && context->method_inst->is_open) {
4100 MonoGenericContext shared_context;
4101 MonoGenericInst *inst;
4102 MonoType **type_argv;
4104 MonoMethod *declaring_method;
4105 gboolean supported = TRUE;
4107 /* Check that the context doesn't contain open constructed types */
4108 if (context->class_inst) {
4109 inst = context->class_inst;
4110 for (i = 0; i < inst->type_argc; ++i) {
4111 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)
4113 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4117 if (context->method_inst) {
4118 inst = context->method_inst;
4119 for (i = 0; i < inst->type_argc; ++i) {
4120 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)
4122 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4130 memset (&shared_context, 0, sizeof (MonoGenericContext));
4132 inst = context->class_inst;
4134 type_argv = g_new0 (MonoType*, inst->type_argc);
4135 for (i = 0; i < inst->type_argc; ++i) {
4136 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)
4137 type_argv [i] = &mono_defaults.object_class->byval_arg;
4139 type_argv [i] = inst->type_argv [i];
4142 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4146 inst = context->method_inst;
4148 type_argv = g_new0 (MonoType*, inst->type_argc);
4149 for (i = 0; i < inst->type_argc; ++i) {
4150 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)
4151 type_argv [i] = &mono_defaults.object_class->byval_arg;
4153 type_argv [i] = inst->type_argv [i];
4156 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4160 if (method->is_generic || method->klass->generic_container)
4161 declaring_method = method;
4163 declaring_method = mono_method_get_declaring_generic_method (method);
4165 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
4169 * If the method is fully sharable, it was already added in place of its
4170 * generic definition.
4172 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4176 * FIXME: Partially shared methods are not shared here, so we end up with
4177 * many identical methods.
4179 add_extra_method (acfg, method);
4182 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4185 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4187 klass = mono_class_get (acfg->image, token);
4188 if (!klass || klass->rank) {
4189 mono_loader_clear_error ();
4193 add_generic_class (acfg, klass, FALSE, "typespec");
4196 /* Add types of args/locals */
4197 for (i = 0; i < acfg->methods->len; ++i) {
4198 method = g_ptr_array_index (acfg->methods, i);
4199 add_types_from_method_header (acfg, method);
4202 if (acfg->image == mono_defaults.corlib) {
4204 MonoType *insts [256];
4207 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4208 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4209 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4210 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4211 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4212 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4213 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4214 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4215 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4216 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4217 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4218 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4220 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4221 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4223 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4224 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4226 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4228 /* Add instances of the array generic interfaces for primitive types */
4229 /* This will add instances of the InternalArray_ helper methods in Array too */
4230 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4232 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4233 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4235 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4236 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4238 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4241 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4242 * used for all instances of GetGenericValueImpl by the AOT runtime.
4245 MonoGenericContext ctx;
4246 MonoType *args [16];
4247 MonoMethod *get_method;
4248 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4250 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4253 memset (&ctx, 0, sizeof (ctx));
4254 args [0] = &mono_defaults.object_class->byval_arg;
4255 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4256 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4260 /* Same for CompareExchange<T>/Exchange<T> */
4262 MonoGenericContext ctx;
4263 MonoType *args [16];
4265 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4266 gpointer iter = NULL;
4268 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4269 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4270 memset (&ctx, 0, sizeof (ctx));
4271 args [0] = &mono_defaults.object_class->byval_arg;
4272 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4273 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4278 /* Same for Volatile.Read/Write<T> */
4280 MonoGenericContext ctx;
4281 MonoType *args [16];
4283 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4284 gpointer iter = NULL;
4286 if (volatile_klass) {
4287 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4288 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4289 memset (&ctx, 0, sizeof (ctx));
4290 args [0] = &mono_defaults.object_class->byval_arg;
4291 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4292 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4301 * is_direct_callable:
4303 * Return whenever the method identified by JI is directly callable without
4304 * going through the PLT.
4307 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4309 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4310 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4312 gboolean direct_callable = TRUE;
4314 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4315 direct_callable = FALSE;
4316 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4317 // FIXME: Maybe call the wrapper directly ?
4318 direct_callable = FALSE;
4320 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4321 /* Disable this so all calls go through load_method (), see the
4322 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4323 * mono_debugger_agent_init ().
4325 direct_callable = FALSE;
4328 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4329 /* sgen does some initialization when the allocator method is created */
4330 direct_callable = FALSE;
4332 if (direct_callable)
4335 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4336 if (acfg->aot_opts.direct_pinvoke)
4338 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4339 if (acfg->aot_opts.direct_icalls)
4347 #ifdef MONO_ARCH_AOT_SUPPORTED
4349 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4351 MonoImage *image = method->klass->image;
4352 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4353 MonoTableInfo *tables = image->tables;
4354 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4355 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4356 guint32 im_cols [MONO_IMPLMAP_SIZE];
4359 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4363 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4366 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4368 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4371 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4373 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4380 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4382 if (a->native_offset == b->native_offset)
4383 return a->il_offset - b->il_offset;
4385 return a->native_offset - b->native_offset;
4389 * compute_line_numbers:
4391 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4394 static MonoDebugSourceLocation**
4395 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4397 MonoDebugMethodInfo *minfo;
4398 MonoDebugLineNumberEntry *ln_array;
4399 MonoDebugSourceLocation *loc;
4400 int i, prev_line, prev_il_offset;
4401 int *native_to_il_offset = NULL;
4402 MonoDebugSourceLocation **res;
4405 minfo = mono_debug_lookup_method (method);
4408 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4409 if (debug_info->code_size != code_size)
4412 g_assert (code_size);
4414 /* Compute the native->IL offset mapping */
4416 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4417 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4419 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4421 native_to_il_offset = g_new0 (int, code_size + 1);
4423 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4425 MonoDebugLineNumberEntry *lne = &ln_array [i];
4428 for (j = 0; j < lne->native_offset; ++j)
4429 native_to_il_offset [j] = -1;
4432 if (i < debug_info->num_line_numbers - 1) {
4433 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4435 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4436 native_to_il_offset [j] = lne->il_offset;
4438 for (j = lne->native_offset; j < code_size; ++j)
4439 native_to_il_offset [j] = lne->il_offset;
4444 /* Compute the native->line number mapping */
4445 res = g_new0 (MonoDebugSourceLocation*, code_size);
4446 prev_il_offset = -1;
4449 for (i = 0; i < code_size; ++i) {
4450 int il_offset = native_to_il_offset [i];
4452 if (il_offset == -1 || il_offset == prev_il_offset)
4454 prev_il_offset = il_offset;
4455 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4456 if (!(loc && loc->source_file))
4458 if (loc->row == prev_line) {
4459 mono_debug_symfile_free_location (loc);
4462 prev_line = loc->row;
4463 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4465 /* This will cover the prolog too */
4475 get_file_index (MonoAotCompile *acfg, const char *source_file)
4479 // FIXME: Free these
4480 if (!acfg->dwarf_ln_filenames)
4481 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4482 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4484 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4485 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4486 emit_unset_mode (acfg);
4487 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4495 * emit_and_reloc_code:
4497 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4498 * is true, calls are made through the GOT too. This is used for emitting trampolines
4499 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4500 * since trampolines are needed to make PTL work.
4503 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4505 int i, pindex, start_index, method_index;
4507 MonoJumpInfo *patch_info;
4508 MonoMethodHeader *header;
4509 MonoDebugSourceLocation **locs = NULL;
4511 #ifdef MONO_ARCH_AOT_SUPPORTED
4512 gboolean direct_call, external_call;
4514 const char *direct_call_target = 0;
4515 const char *direct_pinvoke;
4519 header = mono_method_get_header (method);
4521 method_index = get_method_index (acfg, method);
4524 if (acfg->gas_line_numbers && method && debug_info) {
4525 locs = compute_line_numbers (method, code_len, debug_info);
4527 int findex = get_file_index (acfg, "<unknown>");
4528 emit_unset_mode (acfg);
4529 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4533 /* Collect and sort relocations */
4534 patches = g_ptr_array_new ();
4535 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4536 g_ptr_array_add (patches, patch_info);
4537 g_ptr_array_sort (patches, compare_patches);
4540 for (i = 0; i < code_len; i += INST_LEN) {
4542 for (pindex = start_index; pindex < patches->len; ++pindex) {
4543 patch_info = g_ptr_array_index (patches, pindex);
4544 if (patch_info->ip.i >= i)
4548 if (locs && locs [i]) {
4549 MonoDebugSourceLocation *loc = locs [i];
4552 findex = get_file_index (acfg, loc->source_file);
4553 emit_unset_mode (acfg);
4554 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4555 mono_debug_symfile_free_location (loc);
4559 #ifdef MONO_ARCH_AOT_SUPPORTED
4560 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4561 start_index = pindex;
4563 switch (patch_info->type) {
4564 case MONO_PATCH_INFO_NONE:
4566 case MONO_PATCH_INFO_GOT_OFFSET: {
4569 arch_emit_got_offset (acfg, code + i, &code_size);
4570 i += code_size - INST_LEN;
4572 patch_info->type = MONO_PATCH_INFO_NONE;
4575 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4576 int code_size, index;
4577 char *selector = (void*)patch_info->data.target;
4579 if (!acfg->objc_selector_to_index)
4580 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4581 if (!acfg->objc_selectors)
4582 acfg->objc_selectors = g_ptr_array_new ();
4583 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4587 index = acfg->objc_selector_index;
4588 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4589 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4590 acfg->objc_selector_index ++;
4593 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4594 i += code_size - INST_LEN;
4596 patch_info->type = MONO_PATCH_INFO_NONE;
4601 * If this patch is a call, try emitting a direct call instead of
4602 * through a PLT entry. This is possible if the called method is in
4603 * the same assembly and requires no initialization.
4605 direct_call = FALSE;
4606 external_call = FALSE;
4607 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4608 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4609 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4610 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4612 direct_call_target = callee_cfg->asm_symbol;
4613 patch_info->type = MONO_PATCH_INFO_NONE;
4614 acfg->stats.direct_calls ++;
4617 acfg->stats.all_calls ++;
4618 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4619 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4620 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4621 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4623 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4624 if (direct_pinvoke) {
4626 g_assert (strlen (direct_pinvoke) < 1000);
4627 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4630 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4631 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4632 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4633 /* Call to a C function implementing a jit icall */
4635 external_call = TRUE;
4636 g_assert (strlen (sym) < 1000);
4637 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4639 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4640 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4641 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4642 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4643 /* Call to a jit icall without a wrapper */
4645 external_call = TRUE;
4646 g_assert (strlen (sym) < 1000);
4647 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4652 patch_info->type = MONO_PATCH_INFO_NONE;
4653 acfg->stats.direct_calls ++;
4656 if (!got_only && !direct_call) {
4657 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4659 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4661 direct_call_target = plt_entry->symbol;
4663 /* Nullify the patch */
4664 patch_info->type = MONO_PATCH_INFO_NONE;
4665 plt_entry->jit_used = TRUE;
4672 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4673 i += call_size - INST_LEN;
4677 got_slot = get_got_offset (acfg, patch_info);
4679 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4680 i += code_size - INST_LEN;
4686 #endif /* MONO_ARCH_AOT_SUPPORTED */
4689 /* Find next patch */
4691 for (pindex = start_index; pindex < patches->len; ++pindex) {
4692 patch_info = g_ptr_array_index (patches, pindex);
4693 if (patch_info->ip.i >= i)
4697 /* Try to emit multiple bytes at once */
4698 if (pindex < patches->len && patch_info->ip.i > i) {
4701 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4702 if (locs && locs [limit])
4706 emit_code_bytes (acfg, code + i, limit - i);
4707 i = limit - INST_LEN;
4709 emit_code_bytes (acfg, code + i, INST_LEN);
4720 * Return a modified version of S which only includes characters permissible in symbols.
4723 sanitize_symbol (MonoAotCompile *acfg, char *s)
4725 gboolean process = FALSE;
4734 for (i = 0; i < len; ++i)
4735 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4740 gs = g_string_sized_new (len);
4741 for (i = 0; i < len; ++i) {
4743 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4744 g_string_append_c (gs, c);
4745 } else if (c > 0x7f) {
4746 /* multi-byte utf8 */
4747 g_string_append_printf (gs, "_0x%x", c);
4750 while (c >> 6 == 0x2) {
4751 g_string_append_printf (gs, "%x", c);
4755 g_string_append_printf (gs, "_");
4758 g_string_append_c (gs, '_');
4762 res = mono_mempool_strdup (acfg->mempool, gs->str);
4763 g_string_free (gs, TRUE);
4768 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4770 char *name1, *name2, *cached;
4771 int i, j, len, count;
4774 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4775 if (!prefix || !*prefix)
4779 name1 = mono_method_full_name (method, TRUE);
4780 len = strlen (name1);
4781 name2 = malloc (strlen (prefix) + len + 16);
4782 memcpy (name2, prefix, strlen (prefix));
4783 j = strlen (prefix);
4784 for (i = 0; i < len; ++i) {
4785 if (isalnum (name1 [i])) {
4786 name2 [j ++] = name1 [i];
4787 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4789 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4792 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4801 while (g_hash_table_lookup (cache, name2)) {
4802 sprintf (name2 + j, "_%d", count);
4806 cached = g_strdup (name2);
4807 g_hash_table_insert (cache, cached, cached);
4813 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4818 char *debug_sym = NULL;
4819 char *symbol = NULL;
4820 int func_alignment = AOT_FUNC_ALIGNMENT;
4821 MonoMethodHeader *header;
4824 method = cfg->orig_method;
4825 code = cfg->native_code;
4826 header = cfg->header;
4828 method_index = get_method_index (acfg, method);
4829 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4832 /* Make the labels local */
4833 emit_section_change (acfg, ".text", 0);
4834 emit_alignment (acfg, func_alignment);
4836 if (acfg->global_symbols && acfg->need_no_dead_strip)
4837 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4839 emit_label (acfg, cfg->asm_symbol);
4841 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4843 * Write a C style symbol for every method, this has two uses:
4844 * - it works on platforms where the dwarf debugging info is not
4846 * - it allows the setting of breakpoints of aot-ed methods.
4848 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4850 if (acfg->need_no_dead_strip)
4851 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4852 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4853 emit_label (acfg, debug_sym);
4856 export_name = g_hash_table_lookup (acfg->export_names, method);
4858 /* Emit a global symbol for the method */
4859 emit_global_inner (acfg, export_name, TRUE);
4860 emit_label (acfg, export_name);
4863 if (cfg->verbose_level > 0)
4864 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4866 acfg->stats.code_size += cfg->code_len;
4868 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4870 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 ()));
4874 if (acfg->aot_opts.write_symbols) {
4875 emit_symbol_size (acfg, debug_sym, ".");
4879 emit_label (acfg, symbol);
4886 * Encode PATCH_INFO into its disk representation.
4889 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4893 switch (patch_info->type) {
4894 case MONO_PATCH_INFO_NONE:
4896 case MONO_PATCH_INFO_IMAGE:
4897 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4899 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4900 case MONO_PATCH_INFO_JIT_TLS_ID:
4901 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4902 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4904 case MONO_PATCH_INFO_METHOD_REL:
4905 encode_value ((gint)patch_info->data.offset, p, &p);
4907 case MONO_PATCH_INFO_SWITCH: {
4908 gpointer *table = (gpointer *)patch_info->data.table->table;
4911 encode_value (patch_info->data.table->table_size, p, &p);
4912 for (k = 0; k < patch_info->data.table->table_size; k++)
4913 encode_value ((int)(gssize)table [k], p, &p);
4916 case MONO_PATCH_INFO_METHODCONST:
4917 case MONO_PATCH_INFO_METHOD:
4918 case MONO_PATCH_INFO_METHOD_JUMP:
4919 case MONO_PATCH_INFO_ICALL_ADDR:
4920 case MONO_PATCH_INFO_METHOD_RGCTX:
4921 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
4922 encode_method_ref (acfg, patch_info->data.method, p, &p);
4924 case MONO_PATCH_INFO_INTERNAL_METHOD:
4925 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4926 guint32 len = strlen (patch_info->data.name);
4928 encode_value (len, p, &p);
4930 memcpy (p, patch_info->data.name, len);
4935 case MONO_PATCH_INFO_LDSTR: {
4936 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4937 guint32 token = patch_info->data.token->token;
4938 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4939 encode_value (image_index, p, &p);
4940 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4943 case MONO_PATCH_INFO_RVA:
4944 case MONO_PATCH_INFO_DECLSEC:
4945 case MONO_PATCH_INFO_LDTOKEN:
4946 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4947 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4948 encode_value (patch_info->data.token->token, p, &p);
4949 encode_value (patch_info->data.token->has_context, p, &p);
4950 if (patch_info->data.token->has_context)
4951 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4953 case MONO_PATCH_INFO_EXC_NAME: {
4954 MonoClass *ex_class;
4957 mono_class_from_name (mono_defaults.exception_class->image,
4958 "System", patch_info->data.target);
4959 g_assert (ex_class);
4960 encode_klass_ref (acfg, ex_class, p, &p);
4963 case MONO_PATCH_INFO_R4:
4964 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4966 case MONO_PATCH_INFO_R8:
4967 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4968 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4970 case MONO_PATCH_INFO_VTABLE:
4971 case MONO_PATCH_INFO_CLASS:
4972 case MONO_PATCH_INFO_IID:
4973 case MONO_PATCH_INFO_ADJUSTED_IID:
4974 case MONO_PATCH_INFO_CLASS_INIT:
4975 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4977 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4978 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
4979 if (patch_info->data.del_tramp->method) {
4980 encode_value (1, p, &p);
4981 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
4983 encode_value (0, p, &p);
4986 case MONO_PATCH_INFO_FIELD:
4987 case MONO_PATCH_INFO_SFLDA:
4988 encode_field_info (acfg, patch_info->data.field, p, &p);
4990 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4992 case MONO_PATCH_INFO_RGCTX_FETCH: {
4993 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4998 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4999 * reference the same method, so encode the method only once.
5001 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5003 buf2 = g_malloc (1024);
5006 encode_method_ref (acfg, entry->method, p2, &p2);
5007 g_assert (p2 - buf2 < 1024);
5009 offset = add_to_blob (acfg, buf2, p2 - buf2);
5012 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5017 encode_value (offset, p, &p);
5018 g_assert ((int)entry->info_type < 256);
5019 g_assert (entry->data->type < 256);
5020 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5021 encode_patch (acfg, entry->data, p, &p);
5024 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5025 case MONO_PATCH_INFO_MONITOR_ENTER:
5026 case MONO_PATCH_INFO_MONITOR_EXIT:
5027 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5029 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5030 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5031 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5033 case MONO_PATCH_INFO_SIGNATURE:
5034 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5036 case MONO_PATCH_INFO_TLS_OFFSET:
5037 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5039 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5040 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5041 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5043 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5044 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5047 encode_method_ref (acfg, info->method, p, &p);
5048 encode_value (info->num_entries, p, &p);
5049 for (i = 0; i < info->num_entries; ++i) {
5050 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5052 encode_value (template->info_type, p, &p);
5053 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5054 case MONO_PATCH_INFO_CLASS:
5055 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5057 case MONO_PATCH_INFO_FIELD:
5058 encode_field_info (acfg, template->data, p, &p);
5061 g_assert_not_reached ();
5068 g_warning ("unable to handle jump info %d", patch_info->type);
5069 g_assert_not_reached ();
5076 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
5079 guint32 pindex, offset;
5080 MonoJumpInfo *patch_info;
5082 encode_value (n_patches, p, &p);
5084 for (pindex = 0; pindex < patches->len; ++pindex) {
5085 patch_info = g_ptr_array_index (patches, pindex);
5087 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5091 offset = get_got_offset (acfg, patch_info);
5092 encode_value (offset, p, &p);
5099 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5103 int pindex, buf_size, n_patches;
5105 MonoJumpInfo *patch_info;
5106 MonoMethodHeader *header;
5107 guint32 method_index;
5109 guint32 first_got_offset;
5111 method = cfg->orig_method;
5112 header = mono_method_get_header (method);
5114 method_index = get_method_index (acfg, method);
5116 /* Sort relocations */
5117 patches = g_ptr_array_new ();
5118 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5119 g_ptr_array_add (patches, patch_info);
5120 g_ptr_array_sort (patches, compare_patches);
5122 first_got_offset = acfg->cfgs [method_index]->got_offset;
5124 /**********************/
5125 /* Encode method info */
5126 /**********************/
5128 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5129 p = buf = g_malloc (buf_size);
5131 if (mono_class_get_cctor (method->klass))
5132 encode_klass_ref (acfg, method->klass, p, &p);
5134 /* Not needed when loading the method */
5135 encode_value (0, p, &p);
5138 if (cfg->opt & MONO_OPT_SHARED) {
5139 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5140 for (l = cfg->ldstr_list; l; l = l->next) {
5141 encode_value ((long)l->data, p, &p);
5145 /* Used only in shared mode */
5146 g_assert (!cfg->ldstr_list);
5149 for (pindex = 0; pindex < patches->len; ++pindex) {
5150 patch_info = g_ptr_array_index (patches, pindex);
5152 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5153 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5154 patch_info->type = MONO_PATCH_INFO_NONE;
5159 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5160 /* Stored in a GOT slot initialized at module load time */
5161 patch_info->type = MONO_PATCH_INFO_NONE;
5165 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
5166 /* Stored in a GOT slot initialized at module load time */
5167 patch_info->type = MONO_PATCH_INFO_NONE;
5171 if (is_plt_patch (patch_info)) {
5172 /* Calls are made through the PLT */
5173 patch_info->type = MONO_PATCH_INFO_NONE;
5181 g_assert (cfg->has_got_slots);
5183 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
5185 acfg->stats.info_size += p - buf;
5187 g_assert (p - buf < buf_size);
5189 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5194 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5196 guint32 cache_index;
5199 /* Reuse the unwind module to canonize and store unwind info entries */
5200 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5202 /* Use +/- 1 to distinguish 0s from missing entries */
5203 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5211 * It would be easier to use assembler symbols, but the caller needs an
5214 offset = acfg->unwind_info_offset;
5215 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5216 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5219 encode_value (encoded_len, p, &p);
5221 acfg->unwind_info_offset += encoded_len + (p - buf);
5227 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
5230 int i, k, buf_size, method_index;
5231 guint32 debug_info_size;
5233 MonoMethodHeader *header;
5234 guint8 *p, *buf, *debug_info;
5235 MonoJitInfo *jinfo = cfg->jit_info;
5237 gboolean use_unwind_ops = FALSE;
5238 MonoSeqPointInfo *seq_points;
5240 method = cfg->orig_method;
5241 code = cfg->native_code;
5242 header = cfg->header;
5244 method_index = get_method_index (acfg, method);
5246 if (!acfg->aot_opts.nodebug) {
5247 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5250 debug_info_size = 0;
5253 seq_points = cfg->seq_point_info;
5255 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 128) : 0) + cfg->gc_map_size;
5256 p = buf = g_malloc (buf_size);
5258 use_unwind_ops = cfg->unwind_ops != NULL;
5260 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);
5262 encode_value (flags, p, &p);
5264 if (use_unwind_ops) {
5265 guint32 encoded_len;
5269 * This is a duplicate of the data in the .debug_frame section, but that
5270 * section cannot be accessed using the dl interface.
5272 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5273 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
5276 encode_value (jinfo->used_regs, p, &p);
5279 /*Encode the number of holes before the number of clauses to make decoding easier*/
5280 if (jinfo->has_try_block_holes) {
5281 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5282 encode_value (table->num_holes, p, &p);
5285 /* Exception table */
5286 if (cfg->compile_llvm) {
5288 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5289 * since the information is only available to llc. Instead, we let llc save the data
5290 * into the LSDA, and read it from there at runtime.
5292 /* The assembly might be CIL stripped so emit the data ourselves */
5293 if (header->num_clauses)
5294 encode_value (header->num_clauses, p, &p);
5296 for (k = 0; k < header->num_clauses; ++k) {
5297 MonoExceptionClause *clause;
5299 clause = &header->clauses [k];
5301 encode_value (clause->flags, p, &p);
5302 if (clause->data.catch_class) {
5303 encode_value (1, p, &p);
5304 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5306 encode_value (0, p, &p);
5309 /* Emit a list of nesting clauses */
5310 for (i = 0; i < header->num_clauses; ++i) {
5312 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5314 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5316 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5317 encode_value (i, p, &p);
5319 encode_value (-1, p, &p);
5322 if (jinfo->num_clauses)
5323 encode_value (jinfo->num_clauses, p, &p);
5325 for (k = 0; k < jinfo->num_clauses; ++k) {
5326 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5328 encode_value (ei->flags, p, &p);
5329 encode_value (ei->exvar_offset, p, &p);
5331 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5332 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5334 if (ei->data.catch_class) {
5338 buf2 = g_malloc (4096);
5340 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5342 g_assert (len < 4096);
5343 encode_value (len, p, &p);
5344 memcpy (p, buf2, len);
5348 encode_value (0, p, &p);
5352 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5353 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5354 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5358 if (jinfo->has_try_block_holes) {
5359 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5360 for (i = 0; i < table->num_holes; ++i) {
5361 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5362 encode_value (hole->clause, p, &p);
5363 encode_value (hole->length, p, &p);
5364 encode_value (hole->offset, p, &p);
5368 if (jinfo->has_arch_eh_info) {
5369 MonoArchEHJitInfo *eh_info;
5371 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5372 encode_value (eh_info->stack_size, p, &p);
5375 if (jinfo->has_generic_jit_info) {
5376 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5377 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5383 encode_value (gi->nlocs, p, &p);
5385 for (i = 0; i < gi->nlocs; ++i) {
5386 MonoDwarfLocListEntry *entry = &gi->locations [i];
5388 encode_value (entry->is_reg ? 1 : 0, p, &p);
5389 encode_value (entry->reg, p, &p);
5391 encode_value (entry->offset, p, &p);
5393 g_assert (entry->from == 0);
5395 encode_value (entry->from, p, &p);
5396 encode_value (entry->to, p, &p);
5399 if (!cfg->compile_llvm) {
5400 encode_value (gi->has_this ? 1 : 0, p, &p);
5401 encode_value (gi->this_reg, p, &p);
5402 encode_value (gi->this_offset, p, &p);
5407 * Need to encode jinfo->method too, since it is not equal to 'method'
5408 * when using generic sharing.
5410 buf2 = g_malloc (4096);
5412 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5414 g_assert (len < 4096);
5415 encode_value (len, p, &p);
5416 memcpy (p, buf2, len);
5420 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5421 MonoMethodInflated *inflated;
5422 MonoGenericContext *context;
5423 MonoGenericInst *inst;
5425 g_assert (jinfo->d.method->is_inflated);
5426 inflated = (MonoMethodInflated*)jinfo->d.method;
5427 context = &inflated->context;
5429 encode_value (1, p, &p);
5430 if (context->class_inst) {
5431 inst = context->class_inst;
5433 encode_value (inst->type_argc, p, &p);
5434 for (i = 0; i < inst->type_argc; ++i)
5435 encode_value (gsctx->var_is_vt [i], p, &p);
5437 encode_value (0, p, &p);
5439 if (context->method_inst) {
5440 inst = context->method_inst;
5442 encode_value (inst->type_argc, p, &p);
5443 for (i = 0; i < inst->type_argc; ++i)
5444 encode_value (gsctx->mvar_is_vt [i], p, &p);
5446 encode_value (0, p, &p);
5449 encode_value (0, p, &p);
5454 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5456 encode_value (seq_points->len, p, &p);
5457 last_il_offset = last_native_offset = 0;
5458 for (i = 0; i < seq_points->len; ++i) {
5459 SeqPoint *sp = &seq_points->seq_points [i];
5460 il_offset = sp->il_offset;
5461 native_offset = sp->native_offset;
5462 encode_value (il_offset - last_il_offset, p, &p);
5463 encode_value (native_offset - last_native_offset, p, &p);
5464 last_il_offset = il_offset;
5465 last_native_offset = native_offset;
5467 encode_value (sp->flags, p, &p);
5468 encode_value (sp->next_len, p, &p);
5469 for (j = 0; j < sp->next_len; ++j)
5470 encode_value (sp->next [j], p, &p);
5474 g_assert (debug_info_size < buf_size);
5476 encode_value (debug_info_size, p, &p);
5477 if (debug_info_size) {
5478 memcpy (p, debug_info, debug_info_size);
5479 p += debug_info_size;
5480 g_free (debug_info);
5485 encode_value (cfg->gc_map_size, p, &p);
5486 /* The GC map requires 4 bytes of alignment */
5487 while ((gsize)p % 4)
5489 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5490 p += cfg->gc_map_size;
5493 acfg->stats.ex_info_size += p - buf;
5495 g_assert (p - buf < buf_size);
5498 /* The GC Map requires 4 byte alignment */
5499 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5504 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5506 MonoClass *klass = mono_class_get (acfg->image, token);
5508 int i, buf_size, res;
5509 gboolean no_special_static, cant_encode;
5510 gpointer iter = NULL;
5513 mono_loader_clear_error ();
5517 p = buf = g_malloc (buf_size);
5519 /* Mark as unusable */
5520 encode_value (-1, p, &p);
5522 res = add_to_blob (acfg, buf, p - buf);
5528 buf_size = 10240 + (klass->vtable_size * 16);
5529 p = buf = g_malloc (buf_size);
5533 mono_class_init (klass);
5535 mono_class_get_nested_types (klass, &iter);
5536 g_assert (klass->nested_classes_inited);
5538 mono_class_setup_vtable (klass);
5541 * Emit all the information which is required for creating vtables so
5542 * the runtime does not need to create the MonoMethod structures which
5543 * take up a lot of space.
5546 no_special_static = !mono_class_has_special_static_fields (klass);
5548 /* Check whenever we have enough info to encode the vtable */
5549 cant_encode = FALSE;
5550 for (i = 0; i < klass->vtable_size; ++i) {
5551 MonoMethod *cm = klass->vtable [i];
5553 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5557 mono_class_has_finalizer (klass);
5559 if (klass->generic_container || cant_encode) {
5560 encode_value (-1, p, &p);
5562 encode_value (klass->vtable_size, p, &p);
5563 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);
5564 if (klass->has_cctor)
5565 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5566 if (klass->has_finalize)
5567 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5569 encode_value (klass->instance_size, p, &p);
5570 encode_value (mono_class_data_size (klass), p, &p);
5571 encode_value (klass->packing_size, p, &p);
5572 encode_value (klass->min_align, p, &p);
5574 for (i = 0; i < klass->vtable_size; ++i) {
5575 MonoMethod *cm = klass->vtable [i];
5578 encode_method_ref (acfg, cm, p, &p);
5580 encode_value (0, p, &p);
5584 acfg->stats.class_info_size += p - buf;
5586 g_assert (p - buf < buf_size);
5587 res = add_to_blob (acfg, buf, p - buf);
5594 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5596 char *debug_sym = NULL;
5600 case MONO_PATCH_INFO_METHOD:
5601 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5603 case MONO_PATCH_INFO_INTERNAL_METHOD:
5604 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5606 case MONO_PATCH_INFO_CLASS_INIT:
5607 s = mono_type_get_name (&ji->data.klass->byval_arg);
5608 debug_sym = g_strdup_printf ("plt__class_init_%s", s);
5611 case MONO_PATCH_INFO_RGCTX_FETCH:
5612 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5614 case MONO_PATCH_INFO_ICALL_ADDR: {
5615 char *s = get_debug_sym (ji->data.method, "", cache);
5617 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5621 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5622 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5624 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5625 debug_sym = g_strdup_printf ("plt__generic_class_init");
5631 return sanitize_symbol (acfg, debug_sym);
5635 * Calls made from AOTed code are routed through a table of jumps similar to the
5636 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5637 * control to the AOT runtime through a trampoline.
5640 emit_plt (MonoAotCompile *acfg)
5646 sprintf (symbol, "plt");
5648 emit_section_change (acfg, ".text", 0);
5649 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5650 emit_label (acfg, symbol);
5651 emit_label (acfg, acfg->plt_symbol);
5653 for (i = 0; i < acfg->plt_offset; ++i) {
5654 char *debug_sym = NULL;
5655 MonoPltEntry *plt_entry = NULL;
5660 * The first plt entry is unused.
5664 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5669 * If the target is directly callable, alias the plt symbol to point to
5671 * FIXME: Use this to simplify emit_and_reloc_code ().
5672 * FIXME: Avoid the got slot.
5673 * FIXME: Add support to the binary writer.
5675 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5676 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5679 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5680 /* LLVM calls the PLT entries using bl, so emit a stub */
5681 emit_set_thumb_mode (acfg);
5682 fprintf (acfg->fp, "\n.thumb_func\n");
5683 emit_label (acfg, plt_entry->llvm_symbol);
5684 fprintf (acfg->fp, "bx pc\n");
5685 fprintf (acfg->fp, "nop\n");
5686 emit_set_arm_mode (acfg);
5687 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5689 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5696 debug_sym = plt_entry->debug_sym;
5698 if (acfg->thumb_mixed && !plt_entry->jit_used)
5699 /* Emit only a thumb version */
5702 if (acfg->llvm && !acfg->thumb_mixed)
5703 emit_label (acfg, plt_entry->llvm_symbol);
5706 if (acfg->need_no_dead_strip) {
5707 emit_unset_mode (acfg);
5708 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5710 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5711 emit_label (acfg, debug_sym);
5714 emit_label (acfg, plt_entry->symbol);
5716 arch_emit_plt_entry (acfg, i);
5719 emit_symbol_size (acfg, debug_sym, ".");
5722 if (acfg->thumb_mixed) {
5723 /* Make sure the ARM symbols don't alias the thumb ones */
5724 emit_zero_bytes (acfg, 16);
5727 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5730 for (i = 0; i < acfg->plt_offset; ++i) {
5731 char *debug_sym = NULL;
5732 MonoPltEntry *plt_entry = NULL;
5738 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5741 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5744 /* Skip plt entries not actually called by LLVM code */
5745 if (!plt_entry->llvm_used)
5748 if (acfg->aot_opts.write_symbols) {
5749 if (plt_entry->debug_sym)
5750 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5754 #if defined(TARGET_MACH)
5755 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5756 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5758 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5759 emit_label (acfg, debug_sym);
5761 fprintf (acfg->fp, "\n.thumb_func\n");
5763 emit_label (acfg, plt_entry->llvm_symbol);
5765 arch_emit_llvm_plt_entry (acfg, i);
5768 emit_symbol_size (acfg, debug_sym, ".");
5774 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5776 sprintf (symbol, "plt_end");
5777 emit_label (acfg, symbol);
5781 * emit_trampoline_full:
5783 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5784 * create_jit_info_for_trampoline ().
5786 static G_GNUC_UNUSED void
5787 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5789 char start_symbol [256];
5790 char end_symbol [256];
5792 guint32 buf_size, info_offset;
5793 MonoJumpInfo *patch_info;
5806 code_size = info->code_size;
5808 unwind_ops = info->unwind_ops;
5810 #ifdef __native_client_codegen__
5811 mono_nacl_fix_patches (code, ji);
5816 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5818 emit_section_change (acfg, ".text", 0);
5819 emit_global (acfg, start_symbol, TRUE);
5820 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5821 emit_label (acfg, start_symbol);
5823 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5824 emit_label (acfg, symbol);
5827 * The code should access everything through the GOT, so we pass
5830 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
5832 emit_symbol_size (acfg, start_symbol, ".");
5835 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5836 emit_label (acfg, end_symbol);
5841 /* Sort relocations */
5842 patches = g_ptr_array_new ();
5843 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5844 if (patch_info->type != MONO_PATCH_INFO_NONE)
5845 g_ptr_array_add (patches, patch_info);
5846 g_ptr_array_sort (patches, compare_patches);
5848 buf_size = patches->len * 128 + 128;
5849 buf = g_malloc (buf_size);
5852 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5853 g_assert (p - buf < buf_size);
5855 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5857 info_offset = add_to_blob (acfg, buf, p - buf);
5859 emit_section_change (acfg, RODATA_SECT, 0);
5860 emit_global (acfg, symbol, FALSE);
5861 emit_label (acfg, symbol);
5863 emit_int32 (acfg, info_offset);
5867 guint32 encoded_len;
5871 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5873 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5874 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5877 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5878 emit_int32 (acfg, uw_offset);
5881 /* Emit debug info */
5885 sprintf (symbol, "%s", name);
5886 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5889 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5893 static G_GNUC_UNUSED void
5894 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5896 emit_trampoline_full (acfg, got_offset, info, FALSE);
5900 emit_trampolines (MonoAotCompile *acfg)
5903 char end_symbol [256];
5904 int i, tramp_got_offset;
5905 MonoAotTrampoline ntype;
5906 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5910 if (!acfg->aot_opts.full_aot)
5913 g_assert (acfg->image->assembly);
5915 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5916 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5917 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5918 MonoTrampInfo *info;
5921 * Emit the generic trampolines.
5923 * We could save some code by treating the generic trampolines as a wrapper
5924 * method, but that approach has its own complexities, so we choose the simpler
5927 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5928 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5929 #ifdef DISABLE_REMOTING
5930 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
5933 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
5934 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
5937 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5938 emit_trampoline (acfg, acfg->got_offset, info);
5941 mono_arch_get_nullified_class_init_trampoline (&info);
5942 emit_trampoline (acfg, acfg->got_offset, info);
5943 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5944 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5945 emit_trampoline (acfg, acfg->got_offset, info);
5946 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5947 emit_trampoline (acfg, acfg->got_offset, info);
5950 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5951 emit_trampoline (acfg, acfg->got_offset, info);
5953 /* Emit the exception related code pieces */
5954 mono_arch_get_restore_context (&info, TRUE);
5955 emit_trampoline (acfg, acfg->got_offset, info);
5956 mono_arch_get_call_filter (&info, TRUE);
5957 emit_trampoline (acfg, acfg->got_offset, info);
5958 mono_arch_get_throw_exception (&info, TRUE);
5959 emit_trampoline (acfg, acfg->got_offset, info);
5960 mono_arch_get_rethrow_exception (&info, TRUE);
5961 emit_trampoline (acfg, acfg->got_offset, info);
5962 mono_arch_get_throw_corlib_exception (&info, TRUE);
5963 emit_trampoline (acfg, acfg->got_offset, info);
5965 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5966 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5968 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5970 /* Create a separate out trampoline for more information in stack traces */
5971 info->name = g_strdup ("gsharedvt_out_trampoline");
5972 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5976 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5978 GSList *l = mono_arch_get_trampolines (TRUE);
5981 MonoTrampInfo *info = l->data;
5983 emit_trampoline (acfg, acfg->got_offset, info);
5989 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5992 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5993 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5994 emit_trampoline (acfg, acfg->got_offset, info);
5996 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5997 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5998 emit_trampoline (acfg, acfg->got_offset, info);
6001 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6002 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6003 emit_trampoline (acfg, acfg->got_offset, info);
6009 /* delegate_invoke_impl trampolines */
6010 l = mono_arch_get_delegate_invoke_impls ();
6012 MonoTrampInfo *info = l->data;
6014 emit_trampoline (acfg, acfg->got_offset, info);
6019 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6021 /* Emit trampolines which are numerous */
6024 * These include the following:
6025 * - specific trampolines
6026 * - static rgctx invoke trampolines
6028 * These trampolines have the same code, they are parameterized by GOT
6030 * They are defined in this file, in the arch_... routines instead of
6031 * in tramp-<ARCH>.c, since it is easier to do it this way.
6035 * When running in aot-only mode, we can't create specific trampolines at
6036 * runtime, so we create a few, and save them in the AOT file.
6037 * Normal trampolines embed their argument as a literal inside the
6038 * trampoline code, we can't do that here, so instead we embed an offset
6039 * which needs to be added to the trampoline address to get the address of
6040 * the GOT slot which contains the argument value.
6041 * The generated trampolines jump to the generic trampolines using another
6042 * GOT slot, which will be setup by the AOT loader to point to the
6043 * generic trampoline code of the given type.
6047 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6051 emit_section_change (acfg, ".text", 0);
6053 tramp_got_offset = acfg->got_offset;
6055 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6057 case MONO_AOT_TRAMP_SPECIFIC:
6058 sprintf (symbol, "specific_trampolines");
6060 case MONO_AOT_TRAMP_STATIC_RGCTX:
6061 sprintf (symbol, "static_rgctx_trampolines");
6063 case MONO_AOT_TRAMP_IMT_THUNK:
6064 sprintf (symbol, "imt_thunks");
6066 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6067 sprintf (symbol, "gsharedvt_arg_trampolines");
6070 g_assert_not_reached ();
6073 sprintf (end_symbol, "%s_e", symbol);
6075 if (acfg->aot_opts.write_symbols)
6076 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6078 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6079 emit_label (acfg, symbol);
6081 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6083 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6087 case MONO_AOT_TRAMP_SPECIFIC:
6088 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6089 tramp_got_offset += 2;
6091 case MONO_AOT_TRAMP_STATIC_RGCTX:
6092 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6093 tramp_got_offset += 2;
6095 case MONO_AOT_TRAMP_IMT_THUNK:
6096 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6097 tramp_got_offset += 1;
6099 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6100 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6101 tramp_got_offset += 2;
6104 g_assert_not_reached ();
6106 #ifdef __native_client_codegen__
6107 /* align to avoid 32-byte boundary crossings */
6108 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6111 if (!acfg->trampoline_size [ntype]) {
6112 g_assert (tramp_size);
6113 acfg->trampoline_size [ntype] = tramp_size;
6117 emit_label (acfg, end_symbol);
6118 emit_int32 (acfg, 0);
6121 arch_emit_specific_trampoline_pages (acfg);
6123 /* Reserve some entries at the end of the GOT for our use */
6124 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6127 acfg->got_offset += acfg->num_trampoline_got_entries;
6131 str_begins_with (const char *str1, const char *str2)
6133 int len = strlen (str2);
6134 return strncmp (str1, str2, len) == 0;
6138 mono_aot_readonly_field_override (MonoClassField *field)
6141 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6142 char *p = rdv->name;
6144 len = strlen (field->parent->name_space);
6145 if (strncmp (p, field->parent->name_space, len))
6150 len = strlen (field->parent->name);
6151 if (strncmp (p, field->parent->name, len))
6156 if (strcmp (p, field->name))
6158 switch (rdv->type) {
6160 return &rdv->value.i1;
6162 return &rdv->value.i2;
6164 return &rdv->value.i4;
6173 add_readonly_value (MonoAotOptions *opts, const char *val)
6178 /* the format of val is:
6179 * namespace.typename.fieldname=type/value
6180 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6182 fval = strrchr (val, '/');
6184 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6187 tval = strrchr (val, '=');
6189 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6192 rdv = g_new0 (ReadOnlyValue, 1);
6193 rdv->name = g_malloc0 (tval - val + 1);
6194 memcpy (rdv->name, val, tval - val);
6197 if (strncmp (tval, "i1", 2) == 0) {
6198 rdv->value.i1 = atoi (fval);
6199 rdv->type = MONO_TYPE_I1;
6200 } else if (strncmp (tval, "i2", 2) == 0) {
6201 rdv->value.i2 = atoi (fval);
6202 rdv->type = MONO_TYPE_I2;
6203 } else if (strncmp (tval, "i4", 2) == 0) {
6204 rdv->value.i4 = atoi (fval);
6205 rdv->type = MONO_TYPE_I4;
6207 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6210 rdv->next = readonly_values;
6211 readonly_values = rdv;
6215 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6217 gchar **args, **ptr;
6219 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6220 for (ptr = args; ptr && *ptr; ptr ++) {
6221 const char *arg = *ptr;
6223 if (str_begins_with (arg, "outfile=")) {
6224 opts->outfile = g_strdup (arg + strlen ("outfile="));
6225 } else if (str_begins_with (arg, "save-temps")) {
6226 opts->save_temps = TRUE;
6227 } else if (str_begins_with (arg, "keep-temps")) {
6228 opts->save_temps = TRUE;
6229 } else if (str_begins_with (arg, "write-symbols")) {
6230 opts->write_symbols = TRUE;
6231 } else if (str_begins_with (arg, "no-write-symbols")) {
6232 opts->write_symbols = FALSE;
6233 } else if (str_begins_with (arg, "metadata-only")) {
6234 opts->metadata_only = TRUE;
6235 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6236 opts->bind_to_runtime_version = TRUE;
6237 } else if (str_begins_with (arg, "full")) {
6238 opts->full_aot = TRUE;
6239 } else if (str_begins_with (arg, "threads=")) {
6240 opts->nthreads = atoi (arg + strlen ("threads="));
6241 } else if (str_begins_with (arg, "static")) {
6242 opts->static_link = TRUE;
6243 opts->no_dlsym = TRUE;
6244 } else if (str_begins_with (arg, "asmonly")) {
6245 opts->asm_only = TRUE;
6246 } else if (str_begins_with (arg, "asmwriter")) {
6247 opts->asm_writer = TRUE;
6248 } else if (str_begins_with (arg, "nodebug")) {
6249 opts->nodebug = TRUE;
6250 } else if (str_begins_with (arg, "dwarfdebug")) {
6251 opts->dwarf_debug = TRUE;
6252 } else if (str_begins_with (arg, "nopagetrampolines")) {
6253 opts->use_trampolines_page = FALSE;
6254 } else if (str_begins_with (arg, "ntrampolines=")) {
6255 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6256 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6257 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6258 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6259 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6260 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6261 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6262 } else if (str_begins_with (arg, "autoreg")) {
6263 opts->autoreg = TRUE;
6264 } else if (str_begins_with (arg, "tool-prefix=")) {
6265 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6266 } else if (str_begins_with (arg, "soft-debug")) {
6267 opts->soft_debug = TRUE;
6268 } else if (str_begins_with (arg, "direct-pinvoke")) {
6269 opts->direct_pinvoke = TRUE;
6270 } else if (str_begins_with (arg, "direct-icalls")) {
6271 opts->direct_icalls = TRUE;
6272 #if defined(TARGET_ARM)
6273 } else if (str_begins_with (arg, "iphone-abi")) {
6274 // older full-aot users did depend on this.
6276 } else if (str_begins_with (arg, "no-direct-calls")) {
6277 opts->no_direct_calls = TRUE;
6278 } else if (str_begins_with (arg, "print-skipped")) {
6279 opts->print_skipped_methods = TRUE;
6280 } else if (str_begins_with (arg, "stats")) {
6282 } else if (str_begins_with (arg, "no-instances")) {
6283 opts->no_instances = TRUE;
6284 } else if (str_begins_with (arg, "log-generics")) {
6285 opts->log_generics = TRUE;
6286 } else if (str_begins_with (arg, "mtriple=")) {
6287 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6288 } else if (str_begins_with (arg, "llvm-path=")) {
6289 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6290 } else if (str_begins_with (arg, "readonly-value=")) {
6291 add_readonly_value (opts, arg + strlen ("readonly-value="));
6292 } else if (str_begins_with (arg, "info")) {
6293 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6295 } else if (str_begins_with (arg, "gc-maps")) {
6296 mini_gc_enable_gc_maps_for_aot ();
6297 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6298 printf ("Supported options for --aot:\n");
6299 printf (" outfile=\n");
6300 printf (" save-temps\n");
6301 printf (" keep-temps\n");
6302 printf (" write-symbols\n");
6303 printf (" metadata-only\n");
6304 printf (" bind-to-runtime-version\n");
6306 printf (" threads=\n");
6307 printf (" static\n");
6308 printf (" asmonly\n");
6309 printf (" asmwriter\n");
6310 printf (" nodebug\n");
6311 printf (" dwarfdebug\n");
6312 printf (" ntrampolines=\n");
6313 printf (" nrgctx-trampolines=\n");
6314 printf (" nimt-trampolines=\n");
6315 printf (" ngsharedvt-trampolines=\n");
6316 printf (" autoreg\n");
6317 printf (" tool-prefix=\n");
6318 printf (" readonly-value=\n");
6319 printf (" soft-debug\n");
6320 printf (" gc-maps\n");
6321 printf (" print-skipped\n");
6322 printf (" no-instances\n");
6323 printf (" stats\n");
6325 printf (" help/?\n");
6328 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6333 if (opts->use_trampolines_page) {
6334 opts->ntrampolines = 0;
6335 opts->nrgctx_trampolines = 0;
6336 opts->nimt_trampolines = 0;
6337 opts->ngsharedvt_arg_trampolines = 0;
6343 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6345 MonoMethod *method = (MonoMethod*)key;
6346 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6347 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
6348 MonoAotCompile *acfg = user_data;
6350 new_ji->image = ji->image;
6351 new_ji->token = ji->token;
6352 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6356 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6358 if (klass->type_token)
6360 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6363 return can_encode_class (acfg, klass->element_class);
6368 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6370 if (method->wrapper_type) {
6371 switch (method->wrapper_type) {
6372 case MONO_WRAPPER_NONE:
6373 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6374 case MONO_WRAPPER_XDOMAIN_INVOKE:
6375 case MONO_WRAPPER_STFLD:
6376 case MONO_WRAPPER_LDFLD:
6377 case MONO_WRAPPER_LDFLDA:
6378 case MONO_WRAPPER_LDFLD_REMOTE:
6379 case MONO_WRAPPER_STFLD_REMOTE:
6380 case MONO_WRAPPER_STELEMREF:
6381 case MONO_WRAPPER_ISINST:
6382 case MONO_WRAPPER_PROXY_ISINST:
6383 case MONO_WRAPPER_ALLOC:
6384 case MONO_WRAPPER_REMOTING_INVOKE:
6385 case MONO_WRAPPER_UNKNOWN:
6386 case MONO_WRAPPER_WRITE_BARRIER:
6387 case MONO_WRAPPER_DELEGATE_INVOKE:
6388 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6389 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6390 case MONO_WRAPPER_SYNCHRONIZED:
6392 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6393 case MONO_WRAPPER_CASTCLASS: {
6394 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6403 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6407 if (!method->token) {
6408 /* The method is part of a constructed type like Int[,].Set (). */
6409 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6410 if (method->klass->rank)
6420 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6422 switch (patch_info->type) {
6423 case MONO_PATCH_INFO_METHOD:
6424 case MONO_PATCH_INFO_METHODCONST:
6425 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6426 MonoMethod *method = patch_info->data.method;
6428 return can_encode_method (acfg, method);
6430 case MONO_PATCH_INFO_VTABLE:
6431 case MONO_PATCH_INFO_CLASS_INIT:
6432 case MONO_PATCH_INFO_CLASS:
6433 case MONO_PATCH_INFO_IID:
6434 case MONO_PATCH_INFO_ADJUSTED_IID:
6435 if (!can_encode_class (acfg, patch_info->data.klass)) {
6436 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6440 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6441 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6442 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6447 case MONO_PATCH_INFO_RGCTX_FETCH: {
6448 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6450 if (!can_encode_method (acfg, entry->method))
6452 if (!can_encode_patch (acfg, entry->data))
6466 * AOT compile a given method.
6467 * This function might be called by multiple threads, so it must be thread-safe.
6470 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6473 MonoJumpInfo *patch_info;
6476 MonoMethod *wrapped;
6478 if (acfg->aot_opts.metadata_only)
6481 mono_acfg_lock (acfg);
6482 index = get_method_index (acfg, method);
6483 mono_acfg_unlock (acfg);
6485 /* fixme: maybe we can also precompile wrapper methods */
6486 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6487 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6488 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6489 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6493 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6496 wrapped = mono_marshal_method_from_wrapper (method);
6497 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6498 // FIXME: The wrapper should be generic too, but it is not
6501 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6504 InterlockedIncrement (&acfg->stats.mcount);
6507 if (method->is_generic || method->klass->generic_container) {
6508 InterlockedIncrement (&acfg->stats.genericcount);
6513 //acfg->aot_opts.print_skipped_methods = TRUE;
6516 * Since these methods are the only ones which are compiled with
6517 * AOT support, and they are not used by runtime startup/shutdown code,
6518 * the runtime will not see AOT methods during AOT compilation,so it
6519 * does not need to support them by creating a fake GOT etc.
6521 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), acfg->aot_opts.full_aot ? (JIT_FLAG_AOT|JIT_FLAG_FULL_AOT) : (JIT_FLAG_AOT), 0);
6522 mono_loader_clear_error ();
6524 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6525 if (acfg->aot_opts.print_skipped_methods)
6526 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6527 InterlockedIncrement (&acfg->stats.genericcount);
6530 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6531 if (acfg->aot_opts.print_skipped_methods)
6532 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6533 /* Let the exception happen at runtime */
6537 if (cfg->disable_aot) {
6538 if (acfg->aot_opts.print_skipped_methods)
6539 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6540 InterlockedIncrement (&acfg->stats.ocount);
6541 mono_destroy_compile (cfg);
6544 cfg->method_index = index;
6546 /* Nullify patches which need no aot processing */
6547 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6548 switch (patch_info->type) {
6549 case MONO_PATCH_INFO_LABEL:
6550 case MONO_PATCH_INFO_BB:
6551 patch_info->type = MONO_PATCH_INFO_NONE;
6558 /* Collect method->token associations from the cfg */
6559 mono_acfg_lock (acfg);
6560 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6561 mono_acfg_unlock (acfg);
6564 * Check for absolute addresses.
6567 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6568 switch (patch_info->type) {
6569 case MONO_PATCH_INFO_ABS:
6570 /* unable to handle this */
6579 if (acfg->aot_opts.print_skipped_methods)
6580 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6581 InterlockedIncrement (&acfg->stats.abscount);
6582 mono_destroy_compile (cfg);
6586 /* Lock for the rest of the code */
6587 mono_acfg_lock (acfg);
6590 * Check for methods/klasses we can't encode.
6593 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6594 if (!can_encode_patch (acfg, patch_info))
6599 if (acfg->aot_opts.print_skipped_methods)
6600 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6601 acfg->stats.ocount++;
6602 mono_destroy_compile (cfg);
6603 mono_acfg_unlock (acfg);
6607 /* Adds generic instances referenced by this method */
6609 * The depth is used to avoid infinite loops when generic virtual recursion is
6612 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6613 if (!acfg->aot_opts.no_instances && depth < 32) {
6614 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6615 switch (patch_info->type) {
6616 case MONO_PATCH_INFO_METHOD: {
6617 MonoMethod *m = patch_info->data.method;
6618 if (m->is_inflated) {
6619 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6620 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6621 !method_has_type_vars (m)) {
6622 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6623 if (acfg->aot_opts.full_aot)
6624 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6626 add_extra_method_with_depth (acfg, m, depth + 1);
6627 add_types_from_method_header (acfg, m);
6630 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6632 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6633 add_extra_method_with_depth (acfg, m, depth + 1);
6636 case MONO_PATCH_INFO_VTABLE: {
6637 MonoClass *klass = patch_info->data.klass;
6639 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6640 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6643 case MONO_PATCH_INFO_SFLDA: {
6644 MonoClass *klass = patch_info->data.field->parent;
6646 /* The .cctor needs to run at runtime. */
6647 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6648 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6657 /* Determine whenever the method has GOT slots */
6658 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6659 switch (patch_info->type) {
6660 case MONO_PATCH_INFO_GOT_OFFSET:
6661 case MONO_PATCH_INFO_NONE:
6662 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6664 case MONO_PATCH_INFO_IMAGE:
6665 /* The assembly is stored in GOT slot 0 */
6666 if (patch_info->data.image != acfg->image)
6667 cfg->has_got_slots = TRUE;
6670 if (!is_plt_patch (patch_info))
6671 cfg->has_got_slots = TRUE;
6676 if (!cfg->has_got_slots)
6677 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6680 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6682 /* Make a copy of the patch info which is in the mempool */
6684 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6686 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6687 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6690 patches = new_patch_info;
6692 patches_end->next = new_patch_info;
6693 patches_end = new_patch_info;
6695 cfg->patch_info = patches;
6697 /* Make a copy of the unwind info */
6699 GSList *l, *unwind_ops;
6703 for (l = cfg->unwind_ops; l; l = l->next) {
6704 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6705 memcpy (op, l->data, sizeof (MonoUnwindOp));
6706 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6708 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6710 /* Make a copy of the argument/local info */
6712 MonoInst **args, **locals;
6713 MonoMethodSignature *sig;
6714 MonoMethodHeader *header;
6717 sig = mono_method_signature (method);
6718 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6719 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6720 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6721 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6725 header = mono_method_get_header (method);
6726 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6727 for (i = 0; i < header->num_locals; ++i) {
6728 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6729 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6731 cfg->locals = locals;
6734 /* Free some fields used by cfg to conserve memory */
6735 mono_mempool_destroy (cfg->mempool);
6736 cfg->mempool = NULL;
6737 g_free (cfg->varinfo);
6738 cfg->varinfo = NULL;
6742 mono_regstate_free (cfg->rs);
6746 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6748 while (index >= acfg->cfgs_size) {
6749 MonoCompile **new_cfgs;
6752 new_size = acfg->cfgs_size * 2;
6753 new_cfgs = g_new0 (MonoCompile*, new_size);
6754 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6755 g_free (acfg->cfgs);
6756 acfg->cfgs = new_cfgs;
6757 acfg->cfgs_size = new_size;
6759 acfg->cfgs [index] = cfg;
6761 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6764 if (cfg->orig_method->wrapper_type)
6765 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6768 mono_acfg_unlock (acfg);
6770 InterlockedIncrement (&acfg->stats.ccount);
6774 compile_thread_main (gpointer *user_data)
6776 MonoDomain *domain = user_data [0];
6777 MonoAotCompile *acfg = user_data [1];
6778 GPtrArray *methods = user_data [2];
6781 mono_thread_attach (domain);
6783 for (i = 0; i < methods->len; ++i)
6784 compile_method (acfg, g_ptr_array_index (methods, i));
6788 load_profile_files (MonoAotCompile *acfg)
6792 int file_index, res, method_index, i;
6795 GList *unordered, *l;
6800 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6802 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6807 infile = fopen (tmp, "r");
6810 printf ("Using profile data file '%s'\n", tmp);
6815 res = fscanf (infile, "%32s\n", ver);
6816 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6817 printf ("Profile file has wrong version or invalid.\n");
6824 MonoMethodDesc *desc;
6827 if (fgets (name, 1023, infile) == NULL)
6830 /* Kill the newline */
6831 if (strlen (name) > 0)
6832 name [strlen (name) - 1] = '\0';
6834 desc = mono_method_desc_new (name, TRUE);
6836 method = mono_method_desc_search_in_image (desc, acfg->image);
6838 if (method && mono_method_get_token (method)) {
6839 token = mono_method_get_token (method);
6840 method_index = mono_metadata_token_index (token) - 1;
6843 for (i = 0; i < acfg->method_order->len; ++i) {
6844 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6850 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6852 //printf ("No method found matching '%s'.\n", name);
6858 /* Add missing methods */
6860 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6862 for (i = 0; i < acfg->method_order->len; ++i) {
6863 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6869 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6871 unordered = g_list_reverse (unordered);
6872 for (l = unordered; l; l = l->next)
6873 g_ptr_array_add (acfg->method_order, l->data);
6876 /* Used by the LLVM backend */
6878 mono_aot_get_got_offset (MonoJumpInfo *ji)
6880 return get_got_offset (llvm_acfg, ji);
6884 mono_aot_get_method_name (MonoCompile *cfg)
6886 if (llvm_acfg->aot_opts.static_link)
6887 /* Include the assembly name too to avoid duplicate symbol errors */
6888 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6890 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6894 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6896 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6897 MonoPltEntry *plt_entry;
6900 ji->data.target = data;
6902 if (!can_encode_patch (llvm_acfg, ji))
6905 plt_entry = get_plt_entry (llvm_acfg, ji);
6906 plt_entry->llvm_used = TRUE;
6908 #if defined(TARGET_MACH)
6909 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6911 return g_strdup_printf (plt_entry->llvm_symbol);
6916 mono_aot_get_method_index (MonoMethod *method)
6918 g_assert (llvm_acfg);
6919 return get_method_index (llvm_acfg, method);
6923 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6927 mono_acfg_lock (llvm_acfg);
6928 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6929 mono_acfg_unlock (llvm_acfg);
6939 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6943 emit_llvm_file (MonoAotCompile *acfg)
6945 char *command, *opts, *tempbc;
6947 MonoJumpInfo *patch_info;
6950 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6954 /* Compute the final size of the got */
6955 for (i = 0; i < acfg->nmethods; ++i) {
6956 if (acfg->cfgs [i]) {
6957 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6958 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6959 if (!is_plt_patch (patch_info))
6960 get_got_offset (acfg, patch_info);
6962 get_plt_entry (acfg, patch_info);
6968 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6970 if (acfg->aot_opts.full_aot) {
6974 * Need to add the got entries used by the trampolines.
6975 * This is only a conservative approximation.
6977 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6978 /* For the generic + rgctx trampolines */
6979 acfg->final_got_size += 400;
6980 /* For the specific trampolines */
6981 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6982 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6987 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
6988 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6992 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6993 * a lot of time, and doesn't seem to save much space.
6994 * The following optimizations cannot be enabled:
6996 * - 'jump-threading' changes our blockaddress references to int constants.
6997 * - 'basiccg' fails because it contains:
6998 * if (CS && !isa<IntrinsicInst>(II)) {
6999 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7000 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7001 * The opt list below was produced by taking the output of:
7002 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7003 * then removing tailcallelim + the global opts.
7004 * strip-dead-prototypes deletes unused intrinsics definitions.
7006 opts = g_strdup ("-instcombine -simplifycfg");
7007 //opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -domtree -verify");
7008 /* The dse pass is disabled because of #13734 and #17616 */
7010 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7011 * // If we have no DataLayout information around, then the size of the store
7012 * // is inferrable from the pointee type. If they are the same type, then
7013 * // we know that the store is safe.
7014 * if (AA.getDataLayout() == 0 &&
7015 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7016 * return OverwriteComplete;
7017 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7019 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -sroa -domtree -early-cse -lazy-value-info -correlated-propagation -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -indvars -loop-idiom -loop-deletion -loop-unroll -memdep -gvn -memdep -memcpyopt -sccp -instcombine -lazy-value-info -correlated-propagation -domtree -memdep -adce -simplifycfg -instcombine -strip-dead-prototypes -domtree -verify");
7021 command = g_strdup_printf ("%sopt -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7022 printf ("Executing opt: %s\n", command);
7023 if (system (command) != 0) {
7029 if (!acfg->llc_args)
7030 acfg->llc_args = g_string_new ("");
7032 /* Verbose asm slows down llc greatly */
7033 g_string_append (acfg->llc_args, " -asm-verbose=false");
7035 if (acfg->aot_opts.mtriple)
7036 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7038 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7039 /* ios requires PIC code now */
7040 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7042 if (llvm_acfg->aot_opts.static_link)
7043 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7045 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7047 unlink (acfg->tmpfname);
7049 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpbasename);
7051 printf ("Executing llc: %s\n", command);
7053 if (system (command) != 0) {
7060 emit_code (MonoAotCompile *acfg)
7062 int oindex, i, prev_index;
7065 #if defined(TARGET_POWERPC64)
7066 sprintf (symbol, ".Lgot_addr");
7067 emit_section_change (acfg, ".text", 0);
7068 emit_alignment (acfg, 8);
7069 emit_label (acfg, symbol);
7070 emit_pointer (acfg, acfg->got_symbol);
7074 * This global symbol is used to compute the address of each method using the
7075 * code_offsets array. It is also used to compute the memory ranges occupied by
7076 * AOT code, so it must be equal to the address of the first emitted method.
7078 emit_section_change (acfg, ".text", 0);
7079 emit_alignment (acfg, 8);
7081 for (i = 0; i < acfg->nmethods; ++i) {
7082 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7083 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7088 if (!acfg->methods_symbol) {
7089 sprintf (symbol, "methods");
7090 emit_label (acfg, symbol);
7091 acfg->methods_symbol = g_strdup (symbol);
7095 * Emit some padding so the local symbol for the first method doesn't have the
7096 * same address as 'methods'.
7098 #if defined(__default_codegen__)
7099 emit_zero_bytes (acfg, 16);
7100 #elif defined(__native_client_codegen__)
7102 const int kPaddingSize = 16;
7103 guint8 pad_buffer[kPaddingSize];
7104 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7105 emit_bytes (acfg, pad_buffer, kPaddingSize);
7109 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7113 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7115 cfg = acfg->cfgs [i];
7120 method = cfg->orig_method;
7122 /* Emit unbox trampoline */
7123 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7124 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7126 emit_section_change (acfg, ".text", 0);
7127 #ifdef __native_client_codegen__
7128 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7131 if (acfg->thumb_mixed && cfg->compile_llvm) {
7132 emit_set_thumb_mode (acfg);
7133 fprintf (acfg->fp, "\n.thumb_func\n");
7136 emit_label (acfg, symbol);
7138 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7140 if (acfg->thumb_mixed && cfg->compile_llvm) {
7141 emit_set_arm_mode (acfg);
7145 if (cfg->compile_llvm)
7146 acfg->stats.llvm_count ++;
7148 emit_method_code (acfg, cfg);
7151 sprintf (symbol, "methods_end");
7152 emit_section_change (acfg, ".text", 0);
7153 emit_alignment (acfg, 8);
7154 emit_label (acfg, symbol);
7155 /* To distinguish it from the next symbol */
7156 emit_int32 (acfg, 0);
7159 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7160 * from optimizing them away, since it doesn't see that code_offsets references them.
7161 * JITted methods don't need this since they are referenced using assembler local
7163 * FIXME: This is why write-symbols doesn't work on OSX ?
7165 if (acfg->llvm && acfg->need_no_dead_strip) {
7166 fprintf (acfg->fp, "\n");
7167 for (i = 0; i < acfg->nmethods; ++i) {
7168 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7169 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7173 if (acfg->direct_method_addresses) {
7174 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
7177 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7178 * This is PIE code, and the linker can update it if needed.
7180 sprintf (symbol, "method_addresses");
7181 emit_section_change (acfg, ".text", 1);
7182 emit_alignment (acfg, 8);
7183 emit_label (acfg, symbol);
7184 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7185 emit_unset_mode (acfg);
7186 if (acfg->need_no_dead_strip)
7187 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7189 for (i = 0; i < acfg->nmethods; ++i) {
7192 #ifdef MONO_ARCH_AOT_SUPPORTED
7194 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7196 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7200 sprintf (symbol, "method_addresses_end");
7201 emit_label (acfg, symbol);
7204 sprintf (symbol, "code_offsets");
7205 emit_section_change (acfg, RODATA_SECT, 1);
7206 emit_alignment (acfg, 8);
7207 emit_label (acfg, symbol);
7208 emit_int32 (acfg, 0);
7210 sprintf (symbol, "code_offsets");
7211 emit_section_change (acfg, RODATA_SECT, 1);
7212 emit_alignment (acfg, 8);
7213 emit_label (acfg, symbol);
7215 acfg->stats.offsets_size += acfg->nmethods * 4;
7217 for (i = 0; i < acfg->nmethods; ++i) {
7218 if (acfg->cfgs [i]) {
7219 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, acfg->methods_symbol, 0);
7221 emit_int32 (acfg, 0xffffffff);
7227 /* Emit a sorted table mapping methods to their unbox trampolines */
7228 sprintf (symbol, "unbox_trampolines");
7229 if (acfg->direct_method_addresses)
7230 emit_section_change (acfg, ".text", 0);
7232 emit_section_change (acfg, RODATA_SECT, 0);
7233 emit_alignment (acfg, 8);
7234 emit_label (acfg, symbol);
7237 for (i = 0; i < acfg->nmethods; ++i) {
7242 cfg = acfg->cfgs [i];
7246 method = cfg->orig_method;
7248 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7249 index = get_method_index (acfg, method);
7250 sprintf (symbol, "ut_%d", index);
7252 emit_int32 (acfg, index);
7253 if (acfg->direct_method_addresses) {
7254 emit_unset_mode (acfg);
7255 if (acfg->thumb_mixed && cfg->compile_llvm)
7256 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
7258 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
7260 emit_symbol_diff (acfg, symbol, acfg->methods_symbol, 0);
7262 /* Make sure the table is sorted by index */
7263 g_assert (index > prev_index);
7267 sprintf (symbol, "unbox_trampolines_end");
7268 emit_label (acfg, symbol);
7269 emit_int32 (acfg, 0);
7273 emit_info (MonoAotCompile *acfg)
7279 offsets = g_new0 (gint32, acfg->nmethods);
7281 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7282 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7284 if (acfg->cfgs [i]) {
7285 emit_method_info (acfg, acfg->cfgs [i]);
7286 offsets [i] = acfg->cfgs [i]->method_info_offset;
7292 sprintf (symbol, "method_info_offsets");
7293 emit_section_change (acfg, RODATA_SECT, 1);
7294 emit_alignment (acfg, 8);
7295 emit_label (acfg, symbol);
7297 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7302 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7304 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7305 #define mix(a,b,c) { \
7306 a -= c; a ^= rot(c, 4); c += b; \
7307 b -= a; b ^= rot(a, 6); a += c; \
7308 c -= b; c ^= rot(b, 8); b += a; \
7309 a -= c; a ^= rot(c,16); c += b; \
7310 b -= a; b ^= rot(a,19); a += c; \
7311 c -= b; c ^= rot(b, 4); b += a; \
7313 #define final(a,b,c) { \
7314 c ^= b; c -= rot(b,14); \
7315 a ^= c; a -= rot(c,11); \
7316 b ^= a; b -= rot(a,25); \
7317 c ^= b; c -= rot(b,16); \
7318 a ^= c; a -= rot(c,4); \
7319 b ^= a; b -= rot(a,14); \
7320 c ^= b; c -= rot(b,24); \
7324 mono_aot_type_hash (MonoType *t1)
7326 guint hash = t1->type;
7328 hash |= t1->byref << 6; /* do not collide with t1->type values */
7330 case MONO_TYPE_VALUETYPE:
7331 case MONO_TYPE_CLASS:
7332 case MONO_TYPE_SZARRAY:
7333 /* check if the distribution is good enough */
7334 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7336 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7337 case MONO_TYPE_ARRAY:
7338 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7339 case MONO_TYPE_GENERICINST:
7340 return ((hash << 5) - hash) ^ 0;
7347 * mono_aot_method_hash:
7349 * Return a hash code for methods which only depends on metadata.
7352 mono_aot_method_hash (MonoMethod *method)
7354 MonoMethodSignature *sig;
7358 guint32 *hashes_start, *hashes;
7360 MonoGenericInst *ginst = NULL;
7362 /* Similar to the hash in mono_method_get_imt_slot () */
7364 sig = mono_method_signature (method);
7366 if (method->is_inflated)
7367 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7369 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
7370 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7371 hashes = hashes_start;
7373 /* Some wrappers are assigned to random classes */
7374 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7375 klass = method->klass;
7377 klass = mono_defaults.object_class;
7379 if (!method->wrapper_type) {
7380 char *full_name = mono_type_full_name (&klass->byval_arg);
7382 hashes [0] = mono_metadata_str_hash (full_name);
7386 hashes [0] = mono_metadata_str_hash (klass->name);
7387 hashes [1] = mono_metadata_str_hash (klass->name_space);
7389 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7390 /* The method name includes a stringified pointer */
7393 hashes [2] = mono_metadata_str_hash (method->name);
7394 hashes [3] = method->wrapper_type;
7395 hashes [4] = mono_aot_type_hash (sig->ret);
7397 for (i = 0; i < sig->param_count; i++) {
7398 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7401 for (i = 0; i < ginst->type_argc; ++i)
7402 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7404 g_assert (hindex == hashes_count);
7406 /* Setup internal state */
7407 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7409 /* Handle most of the hashes */
7410 while (hashes_count > 3) {
7419 /* Handle the last 3 hashes (all the case statements fall through) */
7420 switch (hashes_count) {
7421 case 3 : c += hashes [2];
7422 case 2 : b += hashes [1];
7423 case 1 : a += hashes [0];
7425 case 0: /* nothing left to add */
7429 free (hashes_start);
7438 * mono_aot_get_array_helper_from_wrapper;
7440 * Get the helper method in Array called by an array wrapper method.
7443 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7447 MonoGenericContext ctx;
7448 MonoType *args [16];
7449 char *mname, *iname, *s, *s2, *helper_name = NULL;
7451 prefix = "System.Collections.Generic";
7452 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7453 s2 = strstr (s, "`1.");
7459 //printf ("X: %s %s\n", iname, mname);
7461 if (!strcmp (iname, "IList"))
7462 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7464 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7465 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7467 g_free (helper_name);
7470 if (m->is_generic) {
7471 memset (&ctx, 0, sizeof (ctx));
7472 args [0] = &method->klass->element_class->byval_arg;
7473 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7474 m = mono_class_inflate_generic_method (m, &ctx);
7480 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7482 typedef struct HashEntry {
7483 guint32 key, value, index;
7484 struct HashEntry *next;
7488 * emit_extra_methods:
7490 * Emit methods which are not in the METHOD table, like wrappers.
7493 emit_extra_methods (MonoAotCompile *acfg)
7495 int i, table_size, buf_size;
7498 guint32 *info_offsets;
7501 HashEntry *entry, *new_entry;
7502 int nmethods, max_chain_length;
7505 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7507 /* Emit method info */
7509 for (i = 0; i < acfg->extra_methods->len; ++i) {
7510 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7511 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7517 p = buf = g_malloc (buf_size);
7521 method = cfg->method_to_register;
7523 encode_method_ref (acfg, method, p, &p);
7525 g_assert ((p - buf) < buf_size);
7527 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7532 * Construct a chained hash table for mapping indexes in extra_method_info to
7535 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7536 table = g_ptr_array_sized_new (table_size);
7537 for (i = 0; i < table_size; ++i)
7538 g_ptr_array_add (table, NULL);
7539 chain_lengths = g_new0 (int, table_size);
7540 max_chain_length = 0;
7541 for (i = 0; i < acfg->extra_methods->len; ++i) {
7542 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7543 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7549 key = info_offsets [i];
7550 value = get_method_index (acfg, method);
7552 hash = mono_aot_method_hash (method) % table_size;
7553 //printf ("X: %s %d\n", mono_method_full_name (method, 1), hash);
7555 chain_lengths [hash] ++;
7556 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7558 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7559 new_entry->key = key;
7560 new_entry->value = value;
7562 entry = g_ptr_array_index (table, hash);
7563 if (entry == NULL) {
7564 new_entry->index = hash;
7565 g_ptr_array_index (table, hash) = new_entry;
7568 entry = entry->next;
7570 entry->next = new_entry;
7571 new_entry->index = table->len;
7572 g_ptr_array_add (table, new_entry);
7576 //printf ("MAX: %d\n", max_chain_length);
7578 /* Emit the table */
7579 sprintf (symbol, "extra_method_table");
7580 emit_section_change (acfg, RODATA_SECT, 0);
7581 emit_alignment (acfg, 8);
7582 emit_label (acfg, symbol);
7584 emit_int32 (acfg, table_size);
7585 for (i = 0; i < table->len; ++i) {
7586 HashEntry *entry = g_ptr_array_index (table, i);
7588 if (entry == NULL) {
7589 emit_int32 (acfg, 0);
7590 emit_int32 (acfg, 0);
7591 emit_int32 (acfg, 0);
7593 //g_assert (entry->key > 0);
7594 emit_int32 (acfg, entry->key);
7595 emit_int32 (acfg, entry->value);
7597 emit_int32 (acfg, entry->next->index);
7599 emit_int32 (acfg, 0);
7604 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7605 * This is used by mono_aot_find_jit_info ().
7607 sprintf (symbol, "extra_method_info_offsets");
7608 emit_section_change (acfg, RODATA_SECT, 0);
7609 emit_alignment (acfg, 8);
7610 emit_label (acfg, symbol);
7612 emit_int32 (acfg, acfg->extra_methods->len);
7613 for (i = 0; i < acfg->extra_methods->len; ++i) {
7614 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7616 emit_int32 (acfg, get_method_index (acfg, method));
7617 emit_int32 (acfg, info_offsets [i]);
7622 emit_exception_info (MonoAotCompile *acfg)
7628 offsets = g_new0 (gint32, acfg->nmethods);
7629 for (i = 0; i < acfg->nmethods; ++i) {
7630 if (acfg->cfgs [i]) {
7631 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7632 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7638 sprintf (symbol, "ex_info_offsets");
7639 emit_section_change (acfg, RODATA_SECT, 1);
7640 emit_alignment (acfg, 8);
7641 emit_label (acfg, symbol);
7643 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7648 emit_unwind_info (MonoAotCompile *acfg)
7654 * The unwind info contains a lot of duplicates so we emit each unique
7655 * entry once, and only store the offset from the start of the table in the
7659 sprintf (symbol, "unwind_info");
7660 emit_section_change (acfg, RODATA_SECT, 1);
7661 emit_alignment (acfg, 8);
7662 emit_label (acfg, symbol);
7664 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7665 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7666 guint8 *unwind_info;
7667 guint32 unwind_info_len;
7671 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7674 encode_value (unwind_info_len, p, &p);
7675 emit_bytes (acfg, buf, p - buf);
7676 emit_bytes (acfg, unwind_info, unwind_info_len);
7678 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7683 emit_class_info (MonoAotCompile *acfg)
7689 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7690 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7691 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7693 sprintf (symbol, "class_info_offsets");
7694 emit_section_change (acfg, RODATA_SECT, 1);
7695 emit_alignment (acfg, 8);
7696 emit_label (acfg, symbol);
7698 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7702 typedef struct ClassNameTableEntry {
7703 guint32 token, index;
7704 struct ClassNameTableEntry *next;
7705 } ClassNameTableEntry;
7708 emit_class_name_table (MonoAotCompile *acfg)
7711 guint32 token, hash;
7716 ClassNameTableEntry *entry, *new_entry;
7719 * Construct a chained hash table for mapping class names to typedef tokens.
7721 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7722 table = g_ptr_array_sized_new (table_size);
7723 for (i = 0; i < table_size; ++i)
7724 g_ptr_array_add (table, NULL);
7725 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7726 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7727 klass = mono_class_get (acfg->image, token);
7729 mono_loader_clear_error ();
7732 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7733 hash = mono_metadata_str_hash (full_name) % table_size;
7736 /* FIXME: Allocate from the mempool */
7737 new_entry = g_new0 (ClassNameTableEntry, 1);
7738 new_entry->token = token;
7740 entry = g_ptr_array_index (table, hash);
7741 if (entry == NULL) {
7742 new_entry->index = hash;
7743 g_ptr_array_index (table, hash) = new_entry;
7746 entry = entry->next;
7748 entry->next = new_entry;
7749 new_entry->index = table->len;
7750 g_ptr_array_add (table, new_entry);
7754 /* Emit the table */
7755 sprintf (symbol, "class_name_table");
7756 emit_section_change (acfg, RODATA_SECT, 0);
7757 emit_alignment (acfg, 8);
7758 emit_label (acfg, symbol);
7760 /* FIXME: Optimize memory usage */
7761 g_assert (table_size < 65000);
7762 emit_int16 (acfg, table_size);
7763 g_assert (table->len < 65000);
7764 for (i = 0; i < table->len; ++i) {
7765 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7767 if (entry == NULL) {
7768 emit_int16 (acfg, 0);
7769 emit_int16 (acfg, 0);
7771 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7773 emit_int16 (acfg, entry->next->index);
7775 emit_int16 (acfg, 0);
7781 emit_image_table (MonoAotCompile *acfg)
7787 * The image table is small but referenced in a lot of places.
7788 * So we emit it at once, and reference its elements by an index.
7791 sprintf (symbol, "image_table");
7792 emit_section_change (acfg, RODATA_SECT, 1);
7793 emit_alignment (acfg, 8);
7794 emit_label (acfg, symbol);
7796 emit_int32 (acfg, acfg->image_table->len);
7797 for (i = 0; i < acfg->image_table->len; i++) {
7798 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7799 MonoAssemblyName *aname = &image->assembly->aname;
7801 /* FIXME: Support multi-module assemblies */
7802 g_assert (image->assembly->image == image);
7804 emit_string (acfg, image->assembly_name);
7805 emit_string (acfg, image->guid);
7806 emit_string (acfg, aname->culture ? aname->culture : "");
7807 emit_string (acfg, (const char*)aname->public_key_token);
7809 emit_alignment (acfg, 8);
7810 emit_int32 (acfg, aname->flags);
7811 emit_int32 (acfg, aname->major);
7812 emit_int32 (acfg, aname->minor);
7813 emit_int32 (acfg, aname->build);
7814 emit_int32 (acfg, aname->revision);
7819 emit_got_info (MonoAotCompile *acfg)
7822 int i, first_plt_got_patch, buf_size;
7824 guint32 *got_info_offsets;
7826 /* Add the patches needed by the PLT to the GOT */
7827 acfg->plt_got_offset_base = acfg->got_offset;
7828 first_plt_got_patch = acfg->got_patches->len;
7829 for (i = 1; i < acfg->plt_offset; ++i) {
7830 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7832 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7834 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7837 acfg->got_offset += acfg->plt_offset;
7841 * - optimize offsets table.
7842 * - reduce number of exported symbols.
7843 * - emit info for a klass only once.
7844 * - determine when a method uses a GOT slot which is guaranteed to be already
7846 * - clean up and document the code.
7847 * - use String.Empty in class libs.
7850 /* Encode info required to decode shared GOT entries */
7851 buf_size = acfg->got_patches->len * 128;
7852 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7853 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7854 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7856 if (acfg->plt_offset)
7857 acfg->plt_got_info_offsets [0] = 0;
7858 for (i = 0; i < acfg->got_patches->len; ++i) {
7859 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7864 encode_value (ji->type, p, &p);
7866 encode_patch (acfg, ji, p, &p);
7867 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7868 g_assert (p - buf <= buf_size);
7869 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7871 if (i >= first_plt_got_patch)
7872 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7873 acfg->stats.got_info_size += p - buf;
7876 /* Emit got_info_offsets table */
7877 sprintf (symbol, "got_info_offsets");
7878 emit_section_change (acfg, RODATA_SECT, 1);
7879 emit_alignment (acfg, 8);
7880 emit_label (acfg, symbol);
7882 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7883 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7887 emit_got (MonoAotCompile *acfg)
7892 /* Don't make GOT global so accesses to it don't need relocations */
7893 sprintf (symbol, "%s", acfg->got_symbol);
7894 emit_section_change (acfg, ".bss", 0);
7895 emit_alignment (acfg, 8);
7896 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7897 emit_label (acfg, symbol);
7898 if (acfg->got_offset > 0)
7899 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7901 sprintf (symbol, "got_end");
7902 emit_label (acfg, symbol);
7906 typedef struct GlobalsTableEntry {
7907 guint32 value, index;
7908 struct GlobalsTableEntry *next;
7909 } GlobalsTableEntry;
7912 emit_globals (MonoAotCompile *acfg)
7918 GlobalsTableEntry *entry, *new_entry;
7920 if (!acfg->aot_opts.static_link)
7924 * When static linking, we emit a table containing our globals.
7928 * Construct a chained hash table for mapping global names to their index in
7929 * the globals table.
7931 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7932 table = g_ptr_array_sized_new (table_size);
7933 for (i = 0; i < table_size; ++i)
7934 g_ptr_array_add (table, NULL);
7935 for (i = 0; i < acfg->globals->len; ++i) {
7936 char *name = g_ptr_array_index (acfg->globals, i);
7938 hash = mono_metadata_str_hash (name) % table_size;
7940 /* FIXME: Allocate from the mempool */
7941 new_entry = g_new0 (GlobalsTableEntry, 1);
7942 new_entry->value = i;
7944 entry = g_ptr_array_index (table, hash);
7945 if (entry == NULL) {
7946 new_entry->index = hash;
7947 g_ptr_array_index (table, hash) = new_entry;
7950 entry = entry->next;
7952 entry->next = new_entry;
7953 new_entry->index = table->len;
7954 g_ptr_array_add (table, new_entry);
7958 /* Emit the table */
7959 sprintf (symbol, ".Lglobals_hash");
7960 emit_section_change (acfg, RODATA_SECT, 0);
7961 emit_alignment (acfg, 8);
7962 emit_label (acfg, symbol);
7964 /* FIXME: Optimize memory usage */
7965 g_assert (table_size < 65000);
7966 emit_int16 (acfg, table_size);
7967 for (i = 0; i < table->len; ++i) {
7968 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7970 if (entry == NULL) {
7971 emit_int16 (acfg, 0);
7972 emit_int16 (acfg, 0);
7974 emit_int16 (acfg, entry->value + 1);
7976 emit_int16 (acfg, entry->next->index);
7978 emit_int16 (acfg, 0);
7982 /* Emit the names */
7983 for (i = 0; i < acfg->globals->len; ++i) {
7984 char *name = g_ptr_array_index (acfg->globals, i);
7986 sprintf (symbol, "name_%d", i);
7987 emit_section_change (acfg, RODATA_SECT, 1);
7989 emit_alignment (acfg, 4);
7991 emit_label (acfg, symbol);
7992 emit_string (acfg, name);
7995 /* Emit the globals table */
7996 sprintf (symbol, "globals");
7997 emit_section_change (acfg, ".data", 0);
7998 /* This is not a global, since it is accessed by the init function */
7999 emit_alignment (acfg, 8);
8000 emit_label (acfg, symbol);
8002 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8003 emit_pointer (acfg, symbol);
8005 for (i = 0; i < acfg->globals->len; ++i) {
8006 char *name = g_ptr_array_index (acfg->globals, i);
8008 sprintf (symbol, "name_%d", i);
8009 emit_pointer (acfg, symbol);
8011 sprintf (symbol, "%s", name);
8012 emit_pointer (acfg, symbol);
8014 /* Null terminate the table */
8015 emit_int32 (acfg, 0);
8016 emit_int32 (acfg, 0);
8020 emit_autoreg (MonoAotCompile *acfg)
8025 * Emit a function into the .ctor section which will be called by the ELF
8026 * loader to register this module with the runtime.
8028 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8031 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8033 arch_emit_autoreg (acfg, symbol);
8039 emit_mem_end (MonoAotCompile *acfg)
8043 sprintf (symbol, "mem_end");
8044 emit_section_change (acfg, ".text", 1);
8045 emit_alignment (acfg, 8);
8046 emit_label (acfg, symbol);
8050 * Emit a structure containing all the information not stored elsewhere.
8053 emit_file_info (MonoAotCompile *acfg)
8058 const char *gc_name;
8061 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8063 if (acfg->aot_opts.bind_to_runtime_version) {
8064 build_info = mono_get_runtime_build_info ();
8065 emit_string_symbol (acfg, "runtime_version", build_info);
8066 g_free (build_info);
8068 emit_string_symbol (acfg, "runtime_version", "");
8071 /* Emit a string holding the assembly name */
8072 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8075 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8078 gc_name = mono_gc_get_gc_name ();
8079 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8081 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8082 emit_section_change (acfg, ".data", 0);
8083 emit_alignment (acfg, 8);
8084 emit_label (acfg, symbol);
8085 if (!acfg->aot_opts.static_link)
8086 emit_global (acfg, symbol, FALSE);
8088 /* The data emitted here must match MonoAotFileInfo. */
8090 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8091 emit_int32 (acfg, 0);
8094 * We emit pointers to our data structures instead of emitting global symbols which
8095 * point to them, to reduce the number of globals, and because using globals leads to
8096 * various problems (i.e. arm/thumb).
8098 emit_pointer (acfg, acfg->got_symbol);
8099 emit_pointer (acfg, acfg->methods_symbol);
8102 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8104 emit_pointer (acfg, "mono_eh_frame");
8106 emit_pointer (acfg, NULL);
8108 emit_pointer (acfg, "blob");
8109 emit_pointer (acfg, "class_name_table");
8110 emit_pointer (acfg, "class_info_offsets");
8111 emit_pointer (acfg, "method_info_offsets");
8112 emit_pointer (acfg, "ex_info_offsets");
8113 emit_pointer (acfg, "code_offsets");
8114 if (acfg->direct_method_addresses)
8115 emit_pointer (acfg, "method_addresses");
8117 emit_pointer (acfg, NULL);
8118 emit_pointer (acfg, "extra_method_info_offsets");
8119 emit_pointer (acfg, "extra_method_table");
8120 emit_pointer (acfg, "got_info_offsets");
8121 emit_pointer (acfg, "methods_end");
8122 emit_pointer (acfg, "unwind_info");
8123 emit_pointer (acfg, "mem_end");
8124 emit_pointer (acfg, "image_table");
8125 emit_pointer (acfg, "plt");
8126 emit_pointer (acfg, "plt_end");
8127 emit_pointer (acfg, "assembly_guid");
8128 emit_pointer (acfg, "runtime_version");
8129 if (acfg->num_trampoline_got_entries) {
8130 emit_pointer (acfg, "specific_trampolines");
8131 emit_pointer (acfg, "static_rgctx_trampolines");
8132 emit_pointer (acfg, "imt_thunks");
8133 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8135 emit_pointer (acfg, NULL);
8136 emit_pointer (acfg, NULL);
8137 emit_pointer (acfg, NULL);
8138 emit_pointer (acfg, NULL);
8140 if (acfg->thumb_mixed) {
8141 emit_pointer (acfg, "thumb_end");
8143 emit_pointer (acfg, NULL);
8145 if (acfg->aot_opts.static_link) {
8146 emit_pointer (acfg, "globals");
8148 emit_pointer (acfg, NULL);
8150 emit_pointer (acfg, "assembly_name");
8151 emit_pointer (acfg, "unbox_trampolines");
8152 emit_pointer (acfg, "unbox_trampolines_end");
8154 emit_int32 (acfg, acfg->plt_got_offset_base);
8155 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8156 emit_int32 (acfg, acfg->plt_offset);
8157 emit_int32 (acfg, acfg->nmethods);
8158 emit_int32 (acfg, acfg->flags);
8159 emit_int32 (acfg, acfg->opts);
8160 emit_int32 (acfg, acfg->simd_opts);
8161 emit_int32 (acfg, gc_name_offset);
8163 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8164 emit_int32 (acfg, acfg->num_trampolines [i]);
8165 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8166 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8167 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8168 emit_int32 (acfg, acfg->trampoline_size [i]);
8169 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8171 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8176 memset (&t, 0, sizeof (MonoType));
8177 t.type = MONO_TYPE_R8;
8178 mono_type_size (&t, &align);
8179 emit_int32 (acfg, align);
8181 memset (&t, 0, sizeof (MonoType));
8182 t.type = MONO_TYPE_I8;
8183 mono_type_size (&t, &align);
8185 emit_int32 (acfg, align);
8188 emit_int32 (acfg, __alignof__ (double));
8189 emit_int32 (acfg, __alignof__ (gint64));
8191 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8192 emit_int32 (acfg, acfg->tramp_page_size);
8193 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8194 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8196 if (acfg->aot_opts.static_link) {
8200 * Emit a global symbol which can be passed by an embedding app to
8201 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8204 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8206 /* Get rid of characters which cannot occur in symbols */
8208 for (p = symbol; *p; ++p) {
8209 if (!(isalnum (*p) || *p == '_'))
8212 acfg->static_linking_symbol = g_strdup (symbol);
8213 emit_global_inner (acfg, symbol, FALSE);
8214 emit_alignment (acfg, sizeof (gpointer));
8215 emit_label (acfg, symbol);
8216 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8221 emit_blob (MonoAotCompile *acfg)
8225 sprintf (symbol, "blob");
8226 emit_section_change (acfg, RODATA_SECT, 1);
8227 emit_alignment (acfg, 8);
8228 emit_label (acfg, symbol);
8230 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8234 emit_objc_selectors (MonoAotCompile *acfg)
8238 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8243 * cat > foo.m << EOF
8246 * return @selector(print:);
8251 img_writer_emit_unset_mode (acfg->w);
8252 g_assert (acfg->fp);
8253 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8254 fprintf (acfg->fp, ".align 2\n");
8255 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8256 fprintf (acfg->fp, "L_OBJC_SELECTOR_REFERENCES_%d:\n", i);
8257 fprintf (acfg->fp, ".long L_OBJC_METH_VAR_NAME_%d\n", i);
8259 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8260 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8261 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8262 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8265 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8266 fprintf (acfg->fp, ".align 2\n");
8267 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8268 fprintf (acfg->fp, ".long 0\n");
8269 fprintf (acfg->fp, ".long 16\n");
8273 emit_dwarf_info (MonoAotCompile *acfg)
8275 #ifdef EMIT_DWARF_INFO
8279 /* DIEs for methods */
8280 for (i = 0; i < acfg->nmethods; ++i) {
8281 MonoCompile *cfg = acfg->cfgs [i];
8286 // FIXME: LLVM doesn't define .Lme_...
8287 if (cfg->compile_llvm)
8290 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8292 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 ()));
8298 collect_methods (MonoAotCompile *acfg)
8301 MonoImage *image = acfg->image;
8303 /* Collect methods */
8304 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8306 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8308 method = mono_get_method (acfg->image, token, NULL);
8311 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
8312 printf ("Run with MONO_LOG_LEVEL=debug for more information.\n");
8316 /* Load all methods eagerly to skip the slower lazy loading code */
8317 mono_class_setup_methods (method->klass);
8319 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8320 /* Compile the wrapper instead */
8321 /* We do this here instead of add_wrappers () because it is easy to do it here */
8322 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8326 /* FIXME: Some mscorlib methods don't have debug info */
8328 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8329 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8330 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8331 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8332 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8333 if (!mono_debug_lookup_method (method)) {
8334 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8341 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8342 add_method_with_index (acfg, method, i, FALSE);
8343 acfg->method_index ++;
8346 /* gsharedvt methods */
8347 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8349 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8351 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8354 method = mono_get_method (acfg->image, token, NULL);
8358 if (strcmp (method->name, "gshared2"))
8362 if (!strstr (method->klass->image->name, "mini"))
8365 if (method->is_generic || method->klass->generic_container) {
8366 MonoMethod *gshared;
8368 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8369 add_extra_method (acfg, gshared);
8373 add_generic_instances (acfg);
8375 if (acfg->aot_opts.full_aot)
8376 add_wrappers (acfg);
8380 compile_methods (MonoAotCompile *acfg)
8384 if (acfg->aot_opts.nthreads > 0) {
8389 gpointer *user_data;
8390 MonoMethod **methods;
8392 methods_len = acfg->methods->len;
8394 len = acfg->methods->len / acfg->aot_opts.nthreads;
8397 * Partition the list of methods into fragments, and hand it to threads to
8400 threads = g_ptr_array_new ();
8401 /* Make a copy since acfg->methods is modified by compile_method () */
8402 methods = g_new0 (MonoMethod*, methods_len);
8403 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8404 for (i = 0; i < methods_len; ++i)
8405 methods [i] = g_ptr_array_index (acfg->methods, i);
8407 while (i < methods_len) {
8408 frag = g_ptr_array_new ();
8409 for (j = 0; j < len; ++j) {
8410 if (i < methods_len) {
8411 g_ptr_array_add (frag, methods [i]);
8416 user_data = g_new0 (gpointer, 3);
8417 user_data [0] = mono_domain_get ();
8418 user_data [1] = acfg;
8419 user_data [2] = frag;
8421 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8422 g_ptr_array_add (threads, handle);
8426 for (i = 0; i < threads->len; ++i) {
8427 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8433 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8434 for (i = methods_len; i < acfg->methods->len; ++i) {
8435 /* This can new methods to acfg->methods */
8436 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8441 compile_asm (MonoAotCompile *acfg)
8443 char *command, *objfile;
8444 char *outfile_name, *tmp_outfile_name;
8445 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8447 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8448 #define AS_OPTIONS "--64"
8449 #elif defined(TARGET_POWERPC64)
8450 #define AS_OPTIONS "-a64 -mppc64"
8451 #define LD_OPTIONS "-m elf64ppc"
8452 #elif defined(sparc) && SIZEOF_VOID_P == 8
8453 #define AS_OPTIONS "-xarch=v9"
8454 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8455 #define AS_OPTIONS "-arch i386"
8457 #define AS_OPTIONS ""
8460 #ifdef __native_client_codegen__
8461 #if defined(TARGET_AMD64)
8462 #define AS_NAME "nacl64-as"
8464 #define AS_NAME "nacl-as"
8466 #elif defined(TARGET_OSX)
8467 #define AS_NAME "clang -c -x assembler"
8469 #define AS_NAME "as"
8473 #define LD_OPTIONS ""
8477 #define LD_NAME "ld -shared -G"
8478 #elif defined(__ppc__) && defined(TARGET_MACH)
8479 #define LD_NAME "gcc -dynamiclib"
8480 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8481 #define LD_NAME "clang --shared"
8482 #elif defined(HOST_WIN32)
8483 #define LD_NAME "gcc -shared --dll"
8484 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8485 #define LD_NAME "clang -m32 -dynamiclib"
8488 if (acfg->aot_opts.asm_only) {
8489 printf ("Output file: '%s'.\n", acfg->tmpfname);
8490 if (acfg->aot_opts.static_link)
8491 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8495 if (acfg->aot_opts.static_link) {
8496 if (acfg->aot_opts.outfile)
8497 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8499 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8501 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8503 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);
8504 printf ("Executing the native assembler: %s\n", command);
8505 if (system (command) != 0) {
8513 if (acfg->aot_opts.static_link) {
8514 printf ("Output file: '%s'.\n", objfile);
8515 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8520 if (acfg->aot_opts.outfile)
8521 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8523 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8525 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8528 command = g_strdup_printf ("%s -o %s %s.o", LD_NAME, tmp_outfile_name, acfg->tmpfname);
8530 command = g_strdup_printf ("%sld %s -shared -o %s %s.o", tool_prefix, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
8532 printf ("Executing the native linker: %s\n", command);
8533 if (system (command) != 0) {
8534 g_free (tmp_outfile_name);
8535 g_free (outfile_name);
8543 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8544 printf ("Stripping the binary: %s\n", com);
8548 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8550 * gas generates 'mapping symbols' each time code and data is mixed, which
8551 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8553 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8554 printf ("Stripping the binary: %s\n", command);
8555 if (system (command) != 0) {
8556 g_free (tmp_outfile_name);
8557 g_free (outfile_name);
8564 rename (tmp_outfile_name, outfile_name);
8566 #if defined(TARGET_MACH)
8567 command = g_strdup_printf ("dsymutil %s", outfile_name);
8568 printf ("Executing dsymutil: %s\n", command);
8569 if (system (command) != 0) {
8574 if (!acfg->aot_opts.save_temps)
8577 g_free (tmp_outfile_name);
8578 g_free (outfile_name);
8581 if (acfg->aot_opts.save_temps)
8582 printf ("Retained input file.\n");
8584 unlink (acfg->tmpfname);
8589 static MonoAotCompile*
8590 acfg_create (MonoAssembly *ass, guint32 opts)
8592 MonoImage *image = ass->image;
8593 MonoAotCompile *acfg;
8596 acfg = g_new0 (MonoAotCompile, 1);
8597 acfg->methods = g_ptr_array_new ();
8598 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8599 acfg->method_depth = g_hash_table_new (NULL, NULL);
8600 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8601 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8602 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8603 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8604 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8605 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8606 acfg->got_patches = g_ptr_array_new ();
8607 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8608 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8609 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8610 acfg->image_hash = g_hash_table_new (NULL, NULL);
8611 acfg->image_table = g_ptr_array_new ();
8612 acfg->globals = g_ptr_array_new ();
8613 acfg->image = image;
8615 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8616 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8617 acfg->mempool = mono_mempool_new ();
8618 acfg->extra_methods = g_ptr_array_new ();
8619 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8620 acfg->unwind_ops = g_ptr_array_new ();
8621 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8622 acfg->method_order = g_ptr_array_new ();
8623 acfg->export_names = g_hash_table_new (NULL, NULL);
8624 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8625 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8626 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8627 InitializeCriticalSection (&acfg->mutex);
8633 acfg_free (MonoAotCompile *acfg)
8637 img_writer_destroy (acfg->w);
8638 for (i = 0; i < acfg->nmethods; ++i)
8640 g_free (acfg->cfgs [i]);
8641 g_free (acfg->cfgs);
8642 g_free (acfg->static_linking_symbol);
8643 g_free (acfg->got_symbol);
8644 g_free (acfg->plt_symbol);
8645 g_ptr_array_free (acfg->methods, TRUE);
8646 g_ptr_array_free (acfg->got_patches, TRUE);
8647 g_ptr_array_free (acfg->image_table, TRUE);
8648 g_ptr_array_free (acfg->globals, TRUE);
8649 g_ptr_array_free (acfg->unwind_ops, TRUE);
8650 g_hash_table_destroy (acfg->method_indexes);
8651 g_hash_table_destroy (acfg->method_depth);
8652 g_hash_table_destroy (acfg->plt_offset_to_entry);
8653 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
8654 if (acfg->patch_to_plt_entry [i])
8655 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
8657 g_free (acfg->patch_to_plt_entry);
8658 g_hash_table_destroy (acfg->patch_to_got_offset);
8659 g_hash_table_destroy (acfg->method_to_cfg);
8660 g_hash_table_destroy (acfg->token_info_hash);
8661 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8662 g_hash_table_destroy (acfg->image_hash);
8663 g_hash_table_destroy (acfg->unwind_info_offsets);
8664 g_hash_table_destroy (acfg->method_label_hash);
8665 g_hash_table_destroy (acfg->export_names);
8666 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8667 g_hash_table_destroy (acfg->klass_blob_hash);
8668 g_hash_table_destroy (acfg->method_blob_hash);
8669 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8670 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8671 g_free (acfg->patch_to_got_offset_by_type);
8672 mono_mempool_destroy (acfg->mempool);
8677 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8679 MonoImage *image = ass->image;
8681 MonoAotCompile *acfg;
8682 char *outfile_name, *tmp_outfile_name, *p;
8683 char llvm_stats_msg [256];
8687 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
8688 if (opts & MONO_OPT_GSHAREDVT) {
8689 fprintf (stderr, "-O=gsharedvt not supported on this platform.\n");
8694 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8696 acfg = acfg_create (ass, opts);
8698 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8699 acfg->aot_opts.write_symbols = TRUE;
8700 acfg->aot_opts.ntrampolines = 1024;
8701 acfg->aot_opts.nrgctx_trampolines = 1024;
8702 acfg->aot_opts.nimt_trampolines = 128;
8703 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8704 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8705 acfg->aot_opts.llvm_path = g_strdup ("");
8707 acfg->aot_opts.use_trampolines_page = TRUE;
8710 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8712 if (acfg->aot_opts.static_link)
8713 acfg->aot_opts.autoreg = TRUE;
8715 //acfg->aot_opts.print_skipped_methods = TRUE;
8717 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8718 if (acfg->aot_opts.full_aot) {
8719 printf ("--aot=full is not supported on this platform.\n");
8724 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8725 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8729 if (acfg->aot_opts.static_link)
8730 acfg->aot_opts.asm_writer = TRUE;
8732 if (acfg->aot_opts.soft_debug) {
8733 MonoDebugOptions *opt = mini_get_debug_options ();
8735 opt->mdb_optimizations = TRUE;
8736 opt->gen_seq_points = TRUE;
8738 if (!mono_debug_enabled ()) {
8739 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8742 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8745 if (mono_use_llvm) {
8747 acfg->aot_opts.asm_writer = TRUE;
8748 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8750 if (acfg->aot_opts.soft_debug) {
8751 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8756 if (acfg->aot_opts.full_aot)
8757 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8759 load_profile_files (acfg);
8761 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8762 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8763 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8765 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8766 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8767 if (acfg->opts & MONO_OPT_GSHAREDVT)
8768 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8771 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8775 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8776 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8777 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8779 /* Get rid of characters which cannot occur in symbols */
8780 for (p = acfg->got_symbol_base; *p; ++p) {
8781 if (!(isalnum (*p) || *p == '_'))
8784 for (p = acfg->plt_symbol; *p; ++p) {
8785 if (!(isalnum (*p) || *p == '_'))
8788 for (p = acfg->assembly_name_sym; *p; ++p) {
8789 if (!(isalnum (*p) || *p == '_'))
8793 acfg->method_index = 1;
8797 if (acfg->aot_opts.full_aot)
8798 mono_set_partial_sharing_supported (TRUE);
8801 collect_methods (acfg);
8803 acfg->cfgs_size = acfg->methods->len + 32;
8804 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8806 /* PLT offset 0 is reserved for the PLT trampoline */
8807 acfg->plt_offset = 1;
8812 mono_llvm_create_aot_module (acfg->got_symbol_base);
8816 /* GOT offset 0 is reserved for the address of the current assembly */
8820 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8821 ji->type = MONO_PATCH_INFO_IMAGE;
8822 ji->data.image = acfg->image;
8824 get_got_offset (acfg, ji);
8826 /* Slot 1 is reserved for the mscorlib got addr */
8827 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8828 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8829 get_got_offset (acfg, ji);
8831 /* This is very common */
8832 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8833 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8834 get_got_offset (acfg, ji);
8836 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8837 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8838 get_got_offset (acfg, ji);
8843 compile_methods (acfg);
8847 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8853 if (acfg->aot_opts.asm_only) {
8854 if (acfg->aot_opts.outfile) {
8855 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8856 acfg->tmpbasename = g_strdup (acfg->tmpfname);
8858 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
8859 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8862 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
8863 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
8866 emit_llvm_file (acfg);
8870 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8871 if (acfg->aot_opts.outfile)
8872 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8874 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8877 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8878 * it might be in another file system so the rename () won't work.
8880 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8882 acfg->fp = fopen (tmp_outfile_name, "w");
8884 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8888 acfg->w = img_writer_create (acfg->fp, TRUE);
8889 acfg->use_bin_writer = TRUE;
8892 /* Append to the .s file created by llvm */
8893 /* FIXME: Use multiple files instead */
8894 acfg->fp = fopen (acfg->tmpfname, "a+");
8896 if (acfg->aot_opts.asm_only) {
8897 if (acfg->aot_opts.outfile)
8898 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8900 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8901 acfg->fp = fopen (acfg->tmpfname, "w+");
8903 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8904 acfg->fp = fdopen (i, "w+");
8907 if (acfg->fp == 0) {
8908 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8911 acfg->w = img_writer_create (acfg->fp, FALSE);
8913 tmp_outfile_name = NULL;
8914 outfile_name = NULL;
8917 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8919 /* Compute symbols for methods */
8920 for (i = 0; i < acfg->nmethods; ++i) {
8921 if (acfg->cfgs [i]) {
8922 MonoCompile *cfg = acfg->cfgs [i];
8923 int method_index = get_method_index (acfg, cfg->orig_method);
8925 if (COMPILE_LLVM (cfg))
8926 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8927 else if (acfg->global_symbols)
8928 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8930 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8934 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
8936 * CLANG supports GAS .file/.loc directives, so emit line number information this way
8937 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
8940 //acfg->gas_line_numbers = TRUE;
8943 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8944 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
8945 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8948 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
8951 img_writer_emit_start (acfg->w);
8954 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
8956 if (acfg->thumb_mixed) {
8959 * This global symbol marks the end of THUMB code, and the beginning of ARM
8960 * code generated by our JIT.
8962 sprintf (symbol, "thumb_end");
8963 emit_section_change (acfg, ".text", 0);
8964 emit_alignment (acfg, 8);
8965 emit_label (acfg, symbol);
8966 emit_zero_bytes (acfg, 16);
8968 fprintf (acfg->fp, ".arm\n");
8975 emit_extra_methods (acfg);
8977 emit_trampolines (acfg);
8979 emit_class_name_table (acfg);
8981 emit_got_info (acfg);
8983 emit_exception_info (acfg);
8985 emit_unwind_info (acfg);
8987 emit_class_info (acfg);
8991 emit_image_table (acfg);
8995 emit_file_info (acfg);
8999 emit_objc_selectors (acfg);
9001 emit_globals (acfg);
9003 emit_autoreg (acfg);
9006 emit_dwarf_info (acfg);
9007 mono_dwarf_writer_close (acfg->dwarf);
9010 emit_mem_end (acfg);
9012 if (acfg->need_pt_gnu_stack) {
9013 /* This is required so the .so doesn't have an executable stack */
9014 /* The bin writer already emits this */
9015 if (!acfg->use_bin_writer)
9016 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9021 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9024 g_assert (acfg->got_offset <= acfg->final_got_size);
9027 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9029 strcpy (llvm_stats_msg, "");
9030 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);
9031 printf ("Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9032 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9034 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9035 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9036 if (acfg->stats.genericcount)
9037 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9038 if (acfg->stats.abscount)
9039 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9040 if (acfg->stats.lmfcount)
9041 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9042 if (acfg->stats.ocount)
9043 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9046 res = img_writer_emit_writeout (acfg->w);
9051 if (acfg->use_bin_writer) {
9052 int err = rename (tmp_outfile_name, outfile_name);
9055 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9059 res = compile_asm (acfg);
9066 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9068 if (acfg->aot_opts.stats) {
9071 printf ("GOT slot distribution:\n");
9072 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9073 if (acfg->stats.got_slot_types [i])
9074 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9077 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);
9089 mono_aot_readonly_field_override (MonoClassField *field)
9095 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)