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)
14 #include <sys/types.h>
34 #include <mono/metadata/abi-details.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/tokentype.h>
39 #include <mono/metadata/appdomain.h>
40 #include <mono/metadata/debug-helpers.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/metadata-internals.h>
43 #include <mono/metadata/marshal.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/monitor.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/mono-endian.h>
48 #include <mono/metadata/threads-types.h>
49 #include <mono/utils/mono-logger-internal.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-time.h>
52 #include <mono/utils/mono-mmap.h>
53 #include <mono/utils/json.h>
56 #include "seq-points.h"
57 #include "image-writer.h"
58 #include "dwarfwriter.h"
61 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
63 #if defined(__linux__) || defined(__native_client_codegen__)
64 #define RODATA_SECT ".rodata"
65 #elif defined(TARGET_MACH)
66 #define RODATA_SECT ".section __TEXT, __const"
68 #define RODATA_SECT ".text"
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
75 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
76 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
77 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
79 /* predefined values for static readonly fields without needed to run the .cctor */
80 typedef struct _ReadOnlyValue ReadOnlyValue;
81 struct _ReadOnlyValue {
84 int type; /* to be used later for typechecking to prevent user errors */
93 static ReadOnlyValue *readonly_values;
95 typedef struct MonoAotOptions {
99 gboolean write_symbols;
100 gboolean metadata_only;
101 gboolean bind_to_runtime_version;
104 gboolean static_link;
108 gboolean dwarf_debug;
110 gboolean log_generics;
111 gboolean log_instances;
112 gboolean gen_seq_points_file;
113 gboolean direct_pinvoke;
114 gboolean direct_icalls;
115 gboolean no_direct_calls;
116 gboolean use_trampolines_page;
117 gboolean no_instances;
122 int nrgctx_trampolines;
123 int nimt_trampolines;
124 int ngsharedvt_arg_trampolines;
125 int nrgctx_fetch_trampolines;
126 gboolean print_skipped_methods;
133 char *instances_logfile_path;
138 typedef struct MonoAotStats {
139 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
140 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
141 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
142 int got_slots, offsets_size;
143 int got_slot_types [MONO_PATCH_INFO_NONE];
144 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
145 int jit_time, gen_time, link_time;
148 typedef struct GotInfo {
149 GHashTable *patch_to_got_offset;
150 GHashTable **patch_to_got_offset_by_type;
151 GPtrArray *got_patches;
154 typedef struct MonoAotCompile {
157 GHashTable *method_indexes;
158 GHashTable *method_depth;
161 GHashTable **patch_to_plt_entry;
162 GHashTable *plt_offset_to_entry;
163 //GHashTable *patch_to_got_offset;
164 //GHashTable **patch_to_got_offset_by_type;
165 //GPtrArray *got_patches;
166 GotInfo got_info, llvm_got_info;
167 GHashTable *image_hash;
168 GHashTable *method_to_cfg;
169 GHashTable *token_info_hash;
170 GHashTable *method_to_pinvoke_import;
171 GPtrArray *extra_methods;
172 GPtrArray *image_table;
174 GPtrArray *method_order;
175 GHashTable *export_names;
176 /* Maps MonoClass* -> blob offset */
177 GHashTable *klass_blob_hash;
178 /* Maps MonoMethod* -> blob offset */
179 GHashTable *method_blob_hash;
180 guint32 *plt_got_info_offsets;
181 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base;
182 /* Number of GOT entries reserved for trampolines */
183 guint32 num_trampoline_got_entries;
184 guint32 tramp_page_size;
186 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
187 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
188 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
189 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
191 MonoAotOptions aot_opts;
195 MonoMemPool *mempool;
198 char *static_linking_symbol;
200 gboolean use_bin_writer;
201 gboolean gas_line_numbers;
202 /* Whenever to emit an object file directly from llc */
203 gboolean llvm_owriter;
205 MonoDwarfWriter *dwarf;
212 GHashTable *unwind_info_offsets;
213 GPtrArray *unwind_ops;
214 guint32 unwind_info_offset;
215 char *got_symbol_base;
216 char *llvm_got_symbol_base;
218 char *llvm_got_symbol;
220 char *methods_symbol;
221 char *llvm_eh_frame_symbol;
222 GHashTable *method_label_hash;
223 const char *temp_prefix;
224 const char *user_symbol_prefix;
225 const char *llvm_label_prefix;
226 const char *inst_directive;
228 guint32 label_generator;
230 MonoAotFileFlags flags;
231 MonoDynamicStream blob;
232 MonoClass **typespec_classes;
235 char *assembly_name_sym;
236 GHashTable *plt_entry_debug_sym_cache;
237 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
238 GHashTable *ginst_hash;
239 GHashTable *dwarf_ln_filenames;
240 gboolean global_symbols;
241 int objc_selector_index, objc_selector_index_2;
242 GPtrArray *objc_selectors;
243 GHashTable *objc_selector_to_index;
245 FILE *instances_logfile;
250 char *symbol, *llvm_symbol, *debug_sym;
252 gboolean jit_used, llvm_used;
255 #define mono_acfg_lock(acfg) mono_mutex_lock (&((acfg)->mutex))
256 #define mono_acfg_unlock(acfg) mono_mutex_unlock (&((acfg)->mutex))
258 /* This points to the current acfg in LLVM mode */
259 static MonoAotCompile *llvm_acfg;
261 #ifdef HAVE_ARRAY_ELEM_INIT
262 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
263 #define MSGSTRFIELD1(line) str##line
264 static const struct msgstr_t {
265 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
266 #include "patch-info.h"
269 #define PATCH_INFO(a,b) b,
270 #include "patch-info.h"
273 static const gint16 opidx [] = {
274 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
275 #include "patch-info.h"
279 static G_GNUC_UNUSED const char*
280 get_patch_name (int info)
282 return (const char*)&opstr + opidx [info];
286 #define PATCH_INFO(a,b) b,
287 static const char* const
288 patch_types [MONO_PATCH_INFO_NUM + 1] = {
289 #include "patch-info.h"
293 static G_GNUC_UNUSED const char*
294 get_patch_name (int info)
296 return patch_types [info];
302 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
305 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
311 output = acfg->logfile;
315 va_start (args, format);
316 vfprintf (output, format, args);
321 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
327 output = acfg->logfile;
331 va_start (args, format);
332 vfprintf (output, format, args);
337 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
342 if (mono_error_ok (error))
346 output = acfg->logfile;
350 va_start (args, format);
351 vfprintf (output, format, args);
353 mono_error_cleanup (error);
355 g_error ("FullAOT cannot continue if there are loader errors");
358 /* Wrappers around the image writer functions */
361 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
363 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
367 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
369 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
373 emit_label (MonoAotCompile *acfg, const char *name)
375 img_writer_emit_label (acfg->w, name);
379 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
381 img_writer_emit_bytes (acfg->w, buf, size);
385 emit_string (MonoAotCompile *acfg, const char *value)
387 img_writer_emit_string (acfg->w, value);
391 emit_line (MonoAotCompile *acfg)
393 img_writer_emit_line (acfg->w);
397 emit_alignment (MonoAotCompile *acfg, int size)
399 img_writer_emit_alignment (acfg->w, size);
403 emit_alignment_code (MonoAotCompile *acfg, int size)
405 if (acfg->align_pad_value)
406 img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
408 img_writer_emit_alignment (acfg->w, size);
412 emit_padding (MonoAotCompile *acfg, int size)
417 if (acfg->align_pad_value) {
418 for (i = 0; i < 16; ++i)
419 buf [i] = acfg->align_pad_value;
421 memset (buf, 0, sizeof (buf));
424 for (i = 0; i < size; i += 16) {
426 emit_bytes (acfg, buf, size - i);
428 emit_bytes (acfg, buf, 16);
433 emit_pointer (MonoAotCompile *acfg, const char *target)
435 img_writer_emit_pointer (acfg->w, target);
439 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
441 if (prefix [0] != '\0') {
442 char *s = g_strdup_printf ("%s%s", prefix, target);
443 img_writer_emit_pointer (acfg->w, s);
446 img_writer_emit_pointer (acfg->w, target);
451 emit_int16 (MonoAotCompile *acfg, int value)
453 img_writer_emit_int16 (acfg->w, value);
457 emit_int32 (MonoAotCompile *acfg, int value)
459 img_writer_emit_int32 (acfg->w, value);
463 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
465 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
469 emit_zero_bytes (MonoAotCompile *acfg, int num)
471 img_writer_emit_zero_bytes (acfg->w, num);
475 emit_byte (MonoAotCompile *acfg, guint8 val)
477 img_writer_emit_byte (acfg->w, val);
480 #ifdef __native_client_codegen__
482 emit_nacl_call_alignment (MonoAotCompile *acfg)
484 img_writer_emit_nacl_call_alignment (acfg->w);
488 static G_GNUC_UNUSED void
489 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
491 img_writer_emit_global (acfg->w, name, func);
495 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
497 if (acfg->aot_opts.no_dlsym) {
498 g_ptr_array_add (acfg->globals, g_strdup (name));
499 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
501 img_writer_emit_global (acfg->w, name, func);
506 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
508 img_writer_emit_symbol_size (acfg->w, name, end_label);
512 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
514 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
516 /* On apple, all symbols need to be aligned to avoid warnings from ld */
517 emit_alignment (acfg, 4);
519 img_writer_emit_label (acfg->w, name);
520 img_writer_emit_string (acfg->w, value);
523 static G_GNUC_UNUSED void
524 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
527 guint8 b = value & 0x7f;
529 if (value != 0) /* more bytes to come */
535 static G_GNUC_UNUSED void
536 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
539 gboolean negative = (value < 0);
546 /* the following is unnecessary if the
547 * implementation of >>= uses an arithmetic rather
548 * than logical shift for a signed left operand
552 value |= - ((gint64)1 <<(size - 7));
553 /* sign bit of byte is second high order bit (0x40) */
554 if ((value == 0 && !(byte & 0x40)) ||
555 (value == -1 && (byte & 0x40)))
559 emit_byte (acfg, byte);
563 static G_GNUC_UNUSED void
564 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
569 guint8 b = value & 0x7f;
571 if (value != 0) /* more bytes to come */
579 static G_GNUC_UNUSED void
580 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
583 gboolean negative = (value < 0);
591 /* the following is unnecessary if the
592 * implementation of >>= uses an arithmetic rather
593 * than logical shift for a signed left operand
597 value |= - (1 <<(size - 7));
598 /* sign bit of byte is second high order bit (0x40) */
599 if ((value == 0 && !(byte & 0x40)) ||
600 (value == -1 && (byte & 0x40)))
611 emit_unset_mode (MonoAotCompile *acfg)
613 img_writer_emit_unset_mode (acfg->w);
616 static G_GNUC_UNUSED void
617 emit_set_thumb_mode (MonoAotCompile *acfg)
619 emit_unset_mode (acfg);
620 fprintf (acfg->fp, ".code 16\n");
623 static G_GNUC_UNUSED void
624 emit_set_arm_mode (MonoAotCompile *acfg)
626 emit_unset_mode (acfg);
627 fprintf (acfg->fp, ".code 32\n");
631 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
636 g_assert (size % 4 == 0);
637 emit_unset_mode (acfg);
638 for (i = 0; i < size; i += 4)
639 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
641 emit_bytes (acfg, buf, size);
645 /* ARCHITECTURE SPECIFIC CODE */
647 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
648 #define EMIT_DWARF_INFO 1
651 #if defined(TARGET_ARM)
652 #define AOT_FUNC_ALIGNMENT 4
654 #define AOT_FUNC_ALIGNMENT 16
656 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
657 #undef AOT_FUNC_ALIGNMENT
658 #define AOT_FUNC_ALIGNMENT 32
661 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
662 #define PPC_LD_OP "ld"
663 #define PPC_LDX_OP "ldx"
665 #define PPC_LD_OP "lwz"
666 #define PPC_LDX_OP "lwzx"
670 #define AOT_TARGET_STR "AMD64"
675 #define AOT_TARGET_STR "ARM (MACH)"
677 #define AOT_TARGET_STR "ARM (!MACH)"
683 #define AOT_TARGET_STR "ARM64 (MACH)"
685 #define AOT_TARGET_STR "ARM64 (!MACH)"
689 #ifdef TARGET_POWERPC64
690 #ifdef __mono_ilp32__
691 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
693 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
696 #ifdef TARGET_POWERPC
697 #ifdef __mono_ilp32__
698 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
700 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
707 #define AOT_TARGET_STR "X86 (WIN32)"
708 #elif defined(__native_client_codegen__)
709 #define AOT_TARGET_STR "X86 (native client codegen)"
711 #define AOT_TARGET_STR "X86 (!native client codegen)"
715 #ifndef AOT_TARGET_STR
716 #define AOT_TARGET_STR ""
720 arch_init (MonoAotCompile *acfg)
722 acfg->llc_args = g_string_new ("");
723 acfg->as_args = g_string_new ("");
726 * The prefix LLVM likes to put in front of symbol names on darwin.
727 * The mach-os specs require this for globals, but LLVM puts them in front of all
728 * symbols. We need to handle this, since we need to refer to LLVM generated
731 acfg->llvm_label_prefix = "";
732 acfg->user_symbol_prefix = "";
734 #if defined(TARGET_X86)
735 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
738 #if defined(TARGET_AMD64)
739 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
741 acfg->align_pad_value = 0x90;
745 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
746 g_string_append (acfg->llc_args, "-mattr=+v6");
749 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
750 g_string_append (acfg->as_args, " -mfpu=vfp3");
752 g_string_append (acfg->llc_args, " -soft-float");
755 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
756 acfg->thumb_mixed = TRUE;
758 if (acfg->aot_opts.mtriple)
759 mono_arch_set_target (acfg->aot_opts.mtriple);
763 acfg->inst_directive = ".inst";
764 if (acfg->aot_opts.mtriple)
765 mono_arch_set_target (acfg->aot_opts.mtriple);
769 acfg->user_symbol_prefix = "_";
770 acfg->llvm_label_prefix = "_";
771 acfg->inst_directive = ".word";
772 acfg->need_no_dead_strip = TRUE;
773 acfg->aot_opts.gnu_asm = TRUE;
776 #if defined(__linux__) && !defined(TARGET_ARM)
777 acfg->need_pt_gnu_stack = TRUE;
781 acfg->global_symbols = TRUE;
787 #include "../../../mono-extensions/mono/mini/aot-compiler-arm64.c"
791 #ifdef MONO_ARCH_AOT_SUPPORTED
793 * arch_emit_direct_call:
795 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
799 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
801 #if defined(TARGET_X86) || defined(TARGET_AMD64)
802 /* Need to make sure this is exactly 5 bytes long */
803 if (!acfg->use_bin_writer) {
804 emit_unset_mode (acfg);
805 fprintf (acfg->fp, "call %s\n", target);
807 emit_byte (acfg, '\xe8');
808 emit_symbol_diff (acfg, target, ".", -4);
811 #elif defined(TARGET_ARM)
812 if (acfg->use_bin_writer) {
819 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
820 emit_bytes (acfg, buf, 4);
822 emit_unset_mode (acfg);
824 fprintf (acfg->fp, "blx %s\n", target);
826 fprintf (acfg->fp, "bl %s\n", target);
829 #elif defined(TARGET_ARM64)
830 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
831 #elif defined(TARGET_POWERPC)
832 if (acfg->use_bin_writer) {
833 g_assert_not_reached ();
835 emit_unset_mode (acfg);
836 fprintf (acfg->fp, "bl %s\n", target);
840 g_assert_not_reached ();
847 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
849 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
850 * in in the 2. slot of every GOT, and require every method to place the GOT
851 * address in r30, even when it doesn't access the GOT otherwise. This way,
852 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
857 * PPC64 uses function descriptors which greatly complicate all code, since
858 * these are used very inconsistently in the runtime. Some functions like
859 * mono_compile_method () return ftn descriptors, while others like the
860 * trampoline creation functions do not.
861 * We assume that all GOT slots contain function descriptors, and create
862 * descriptors in aot-runtime.c when needed.
863 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
864 * from function descriptors, we could do the same, but it would require
865 * rewriting all the ppc/aot code to handle function descriptors properly.
866 * So instead, we use the same approach as on PPC32.
867 * This is a horrible mess, but fixing it would probably lead to an even bigger
873 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
876 #ifdef MONO_ARCH_AOT_SUPPORTED
878 * arch_emit_got_offset:
880 * The memory pointed to by CODE should hold native code for computing the GOT
881 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
882 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
885 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
887 #if defined(TARGET_POWERPC64)
888 g_assert (!acfg->use_bin_writer);
889 emit_unset_mode (acfg);
891 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
892 * unsupported relocations. So we store the got address into the .Lgot_addr
893 * symbol which is in the text segment, compute its address, and load it.
895 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
896 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
897 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
898 fprintf (acfg->fp, "add 30, 30, 0\n");
899 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
900 acfg->label_generator ++;
902 #elif defined(TARGET_POWERPC)
903 g_assert (!acfg->use_bin_writer);
904 emit_unset_mode (acfg);
905 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
906 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
907 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
908 acfg->label_generator ++;
911 guint32 offset = mono_arch_get_patch_offset (code);
912 emit_bytes (acfg, code, offset);
913 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
915 *code_size = offset + 4;
920 * arch_emit_got_access:
922 * The memory pointed to by CODE should hold native code for loading a GOT
923 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
924 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
927 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
930 /* mov reg, got+offset(%rip) */
932 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
936 /* Decode reg, see amd64_mov_reg_membase () */
937 rex_r = code [0] & AMD64_REX_R;
938 g_assert (code [0] == 0x49 + rex_r);
939 g_assert (code [1] == 0x8b);
940 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
942 emit_unset_mode (acfg);
943 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
946 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
947 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
948 *code_size = mono_arch_get_patch_offset (code) + 4;
950 #elif defined(TARGET_X86)
951 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
952 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
953 *code_size = mono_arch_get_patch_offset (code) + 4;
954 #elif defined(TARGET_ARM)
955 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
956 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
957 *code_size = mono_arch_get_patch_offset (code) + 4;
958 #elif defined(TARGET_ARM64)
959 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
960 arm64_emit_got_access (acfg, code, got_slot, code_size);
961 #elif defined(TARGET_POWERPC)
966 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
968 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
969 g_assert (code - buf == 8);
970 emit_bytes (acfg, buf, code - buf);
971 *code_size = code - buf;
974 g_assert_not_reached ();
980 #ifdef MONO_ARCH_AOT_SUPPORTED
982 * arch_emit_objc_selector_ref:
984 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
987 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
989 #if defined(TARGET_ARM)
992 int lindex = acfg->objc_selector_index_2 ++;
995 emit_bytes (acfg, code, 8);
997 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
998 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1000 emit_label (acfg, symbol1);
1001 img_writer_emit_unset_mode (acfg->w);
1002 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1005 #elif defined(TARGET_ARM64)
1006 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1008 g_assert_not_reached ();
1014 * arch_emit_plt_entry:
1016 * Emit code for the PLT entry.
1017 * The plt entry should look like this:
1018 * <indirect jump to GOT_SYMBOL + OFFSET>
1019 * <INFO_OFFSET embedded into the instruction stream>
1022 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1024 #if defined(TARGET_X86)
1025 #if defined(__default_codegen__)
1026 /* jmp *<offset>(%ebx) */
1027 emit_byte (acfg, 0xff);
1028 emit_byte (acfg, 0xa3);
1029 emit_int32 (acfg, offset);
1030 /* Used by mono_aot_get_plt_info_offset */
1031 emit_int32 (acfg, info_offset);
1032 #elif defined(__native_client_codegen__)
1033 const guint8 kSizeOfNaClJmp = 11;
1034 guint8 bytes[kSizeOfNaClJmp];
1035 guint8 *pbytes = &bytes[0];
1037 x86_jump_membase32 (pbytes, X86_EBX, offset);
1038 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
1039 /* four bytes of data, used by mono_arch_patch_plt_entry */
1040 /* For Native Client, make this work with data embedded in push. */
1041 emit_byte (acfg, 0x68); /* hide data in a push */
1042 emit_int32 (acfg, info_offset);
1043 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1044 #endif /*__native_client_codegen__*/
1045 #elif defined(TARGET_AMD64)
1046 #if defined(__default_codegen__)
1047 if (acfg->use_bin_writer) {
1048 emit_byte (acfg, '\xff');
1049 emit_byte (acfg, '\x25');
1050 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1052 emit_unset_mode (acfg);
1053 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1055 /* Used by mono_aot_get_plt_info_offset */
1056 emit_int32 (acfg, info_offset);
1057 acfg->stats.plt_size += 10;
1058 #elif defined(__native_client_codegen__)
1060 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1061 guint8 *code = buf_aligned;
1063 /* mov <OFFSET>(%rip), %r11d */
1064 emit_byte (acfg, '\x45');
1065 emit_byte (acfg, '\x8b');
1066 emit_byte (acfg, '\x1d');
1067 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1069 amd64_jump_reg (code, AMD64_R11);
1070 /* This should be constant for the plt patch */
1071 g_assert ((size_t)(code-buf_aligned) == 10);
1072 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1074 /* Hide data in a push imm32 so it passes validation */
1075 emit_byte (acfg, 0x68); /* push */
1076 emit_int32 (acfg, info_offset);
1077 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
1078 #endif /*__native_client_codegen__*/
1079 #elif defined(TARGET_ARM)
1084 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1085 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1086 emit_bytes (acfg, buf, code - buf);
1087 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1088 /* Used by mono_aot_get_plt_info_offset */
1089 emit_int32 (acfg, info_offset);
1090 #elif defined(TARGET_ARM64)
1091 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1092 #elif defined(TARGET_POWERPC)
1093 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1094 g_assert (!acfg->use_bin_writer);
1095 emit_unset_mode (acfg);
1096 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1097 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1098 fprintf (acfg->fp, "add 11, 11, 30\n");
1099 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1100 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1101 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1102 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1104 fprintf (acfg->fp, "mtctr 11\n");
1105 fprintf (acfg->fp, "bctr\n");
1106 emit_int32 (acfg, info_offset);
1108 g_assert_not_reached ();
1113 * arch_emit_llvm_plt_entry:
1115 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1116 * This is only needed on arm to handle thumb interop.
1119 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1121 #if defined(TARGET_ARM)
1122 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1123 /* The caller already transitioned to thumb */
1124 /* The code below should be 12 bytes long */
1125 /* clang has trouble encoding these instructions, so emit the binary */
1127 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1128 /* thumb can't encode ld pc, [pc, ip] */
1129 fprintf (acfg->fp, "add ip, pc, ip\n");
1130 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1131 fprintf (acfg->fp, "bx ip\n");
1133 emit_set_thumb_mode (acfg);
1134 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1135 fprintf (acfg->fp, ".2byte 0x44fc\n");
1136 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1137 fprintf (acfg->fp, ".2byte 0x4760\n");
1138 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1139 emit_int32 (acfg, info_offset);
1140 emit_unset_mode (acfg);
1141 emit_set_arm_mode (acfg);
1143 g_assert_not_reached ();
1148 * arch_emit_specific_trampoline_pages:
1150 * Emits a page full of trampolines: each trampoline uses its own address to
1151 * lookup both the generic trampoline code and the data argument.
1152 * This page can be remapped in process multiple times so we can get an
1153 * unlimited number of trampolines.
1154 * Specifically this implementation uses the following trick: two memory pages
1155 * are allocated, with the first containing the data and the second containing the trampolines.
1156 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1157 * implementation does all the lifting.
1158 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1159 * on the arm 32 bit system.
1162 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1164 #if defined(TARGET_ARM)
1167 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1169 #define COMMON_TRAMP_SIZE 16
1170 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
1171 int imm8, rot_amount;
1174 if (!acfg->aot_opts.use_trampolines_page)
1177 acfg->tramp_page_size = mono_pagesize ();
1179 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1180 emit_alignment (acfg, mono_pagesize ());
1181 emit_global (acfg, symbol, TRUE);
1182 emit_label (acfg, symbol);
1184 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1186 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1187 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1188 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1189 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1191 g_assert (code - buf == COMMON_TRAMP_SIZE);
1194 emit_bytes (acfg, buf, code - buf);
1196 for (i = 0; i < count; ++i) {
1198 ARM_PUSH (code, 0x5fff);
1200 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1201 g_assert (code - buf == 8);
1202 emit_bytes (acfg, buf, code - buf);
1205 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1206 * the instruction pointer address, so the generic trampoline at the start of the page
1207 * subtracts 4096 to get to the data page and loads the values
1208 * We again fit the generic trampiline in 16 bytes.
1210 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1211 emit_global (acfg, symbol, TRUE);
1212 emit_label (acfg, symbol);
1214 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1215 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1216 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1217 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1219 g_assert (code - buf == COMMON_TRAMP_SIZE);
1222 emit_bytes (acfg, buf, code - buf);
1224 for (i = 0; i < count; ++i) {
1226 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1228 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1229 g_assert (code - buf == 8);
1230 emit_bytes (acfg, buf, code - buf);
1234 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1236 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1237 emit_global (acfg, symbol, TRUE);
1238 emit_label (acfg, symbol);
1240 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1241 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1242 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1243 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1244 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1245 g_assert (code - buf == COMMON_TRAMP_SIZE);
1247 emit_bytes (acfg, buf, code - buf);
1249 for (i = 0; i < count; ++i) {
1251 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1253 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1254 g_assert (code - buf == 8);
1255 emit_bytes (acfg, buf, code - buf);
1258 /* now the imt trampolines: each specific trampolines puts in the ip register
1259 * the instruction pointer address, so the generic trampoline at the start of the page
1260 * subtracts 4096 to get to the data page and loads the values
1261 * We again fit the generic trampiline in 16 bytes.
1263 #define IMT_TRAMP_SIZE 72
1264 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1265 emit_global (acfg, symbol, TRUE);
1266 emit_label (acfg, symbol);
1268 /* Need at least two free registers, plus a slot for storing the pc */
1269 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1271 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1272 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1273 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1275 /* The IMT method is in v5, r0 has the imt array address */
1278 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1279 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1280 imt_found_check = code;
1281 ARM_B_COND (code, ARMCOND_EQ, 0);
1283 /* End-of-loop check */
1284 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1285 loop_end_check = code;
1286 ARM_B_COND (code, ARMCOND_EQ, 0);
1289 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1290 loop_branch_back = code;
1292 arm_patch (loop_branch_back, loop_start);
1295 arm_patch (imt_found_check, code);
1296 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1297 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1298 /* Save it to the third stack slot */
1299 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1300 /* Restore the registers and branch */
1301 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1304 arm_patch (loop_end_check, code);
1305 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1306 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1307 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1311 g_assert (code - buf == IMT_TRAMP_SIZE);
1312 emit_bytes (acfg, buf, code - buf);
1314 for (i = 0; i < count; ++i) {
1316 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1318 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1319 g_assert (code - buf == 8);
1320 emit_bytes (acfg, buf, code - buf);
1323 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1324 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1325 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1326 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1327 #elif defined(TARGET_ARM64)
1328 arm64_emit_specific_trampoline_pages (acfg);
1333 * arch_emit_specific_trampoline:
1335 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1336 * two GOT slots which contain the generic trampoline address and the trampoline
1337 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1340 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1343 * The trampolines created here are variations of the specific
1344 * trampolines created in mono_arch_create_specific_trampoline (). The
1346 * - the generic trampoline address is taken from a got slot.
1347 * - the offset of the got slot where the trampoline argument is stored
1348 * is embedded in the instruction stream, and the generic trampoline
1349 * can load the argument by loading the offset, adding it to the
1350 * address of the trampoline to get the address of the got slot, and
1351 * loading the argument from there.
1352 * - all the trampolines should be of the same length.
1354 #if defined(TARGET_AMD64)
1355 #if defined(__default_codegen__)
1356 /* This should be exactly 8 bytes long */
1358 /* call *<offset>(%rip) */
1360 emit_unset_mode (acfg);
1361 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1362 emit_zero_bytes (acfg, 2);
1364 emit_byte (acfg, '\x41');
1365 emit_byte (acfg, '\xff');
1366 emit_byte (acfg, '\x15');
1367 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1368 emit_zero_bytes (acfg, 1);
1370 #elif defined(__native_client_codegen__)
1372 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1373 guint8 *code = buf_aligned;
1378 /* Emit this call in 'code' so we can find out how long it is. */
1379 amd64_call_reg (code, AMD64_R11);
1380 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1381 call_len = code - call_start;
1383 /* The tramp_size is twice the NaCl alignment because it starts with */
1384 /* a call which needs to be aligned to the end of the boundary. */
1385 *tramp_size = kNaClAlignment*2;
1387 /* Emit nops to align call site below which is 7 bytes plus */
1388 /* the length of the call sequence emitted above. */
1389 /* Note: this requires the specific trampoline starts on a */
1390 /* kNaclAlignedment aligned address, which it does because */
1391 /* it's its own function that is aligned. */
1392 guint8 nop_buf[256];
1393 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1394 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1395 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1397 /* The trampoline is stored at the offset'th pointer, the -4 is */
1398 /* present because RIP relative addressing starts at the end of */
1399 /* the current instruction, while the label "." is relative to */
1400 /* the beginning of the current asm location, which in this case */
1401 /* is not the mov instruction, but the offset itself, due to the */
1402 /* way the bytes and ints are emitted here. */
1403 got_offset = (offset * sizeof(gpointer)) - 4;
1405 /* mov <OFFSET>(%rip), %r11d */
1406 emit_byte (acfg, '\x45');
1407 emit_byte (acfg, '\x8b');
1408 emit_byte (acfg, '\x1d');
1409 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1412 emit_bytes (acfg, call_start, call_len);
1414 /* The arg is stored at the offset+1 pointer, relative to beginning */
1415 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1416 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1418 /* We can't emit this data directly, hide in a "push imm32" */
1419 emit_byte (acfg, '\x68'); /* push */
1420 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1421 emit_alignment (acfg, kNaClAlignment);
1422 #endif /*__native_client_codegen__*/
1423 #elif defined(TARGET_ARM)
1427 /* This should be exactly 20 bytes long */
1430 ARM_PUSH (code, 0x5fff);
1431 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1432 /* Load the value from the GOT */
1433 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1435 ARM_BLX_REG (code, ARMREG_R1);
1437 g_assert (code - buf == 16);
1440 emit_bytes (acfg, buf, code - buf);
1442 * Only one offset is needed, since the second one would be equal to the
1445 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1446 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1447 #elif defined(TARGET_ARM64)
1448 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1449 #elif defined(TARGET_POWERPC)
1456 g_assert (!acfg->use_bin_writer);
1459 * PPC has no ip relative addressing, so we need to compute the address
1460 * of the mscorlib got. That is slow and complex, so instead, we store it
1461 * in the second got slot of every aot image. The caller already computed
1462 * the address of its got and placed it into r30.
1464 emit_unset_mode (acfg);
1465 /* Load mscorlib got address */
1466 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1467 /* Load generic trampoline address */
1468 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1469 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1470 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1471 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1472 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1474 fprintf (acfg->fp, "mtctr 11\n");
1475 /* Load trampoline argument */
1476 /* On ppc, we pass it normally to the generic trampoline */
1477 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1478 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1479 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1480 /* Branch to generic trampoline */
1481 fprintf (acfg->fp, "bctr\n");
1483 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1484 *tramp_size = 10 * 4;
1486 *tramp_size = 9 * 4;
1488 #elif defined(TARGET_X86)
1492 /* Similar to the PPC code above */
1494 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1496 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1497 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1498 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1499 #ifdef MONO_ARCH_MONITOR_LOCK_TAKEN_REG
1500 g_assert (MONO_ARCH_MONITOR_LOCK_TAKEN_REG != X86_ECX);
1505 /* Load mscorlib got address */
1506 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1507 /* Push trampoline argument */
1508 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1509 /* Load generic trampoline address */
1510 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1511 /* Branch to generic trampoline */
1512 x86_jump_reg (code, X86_ECX);
1514 #ifdef __native_client_codegen__
1516 /* emit nops to next 32 byte alignment */
1517 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1518 while (code < (buf + a)) x86_nop(code);
1521 emit_bytes (acfg, buf, code - buf);
1523 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1524 g_assert (code - buf == *tramp_size);
1526 g_assert_not_reached ();
1531 * arch_emit_unbox_trampoline:
1533 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1534 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1537 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1539 #if defined(TARGET_AMD64)
1544 this_reg = mono_arch_get_this_arg_reg (NULL);
1546 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1548 emit_bytes (acfg, buf, code - buf);
1551 emit_unset_mode (acfg);
1552 fprintf (acfg->fp, "jmp %s\n", call_target);
1554 emit_byte (acfg, '\xe9');
1555 emit_symbol_diff (acfg, call_target, ".", -4);
1557 #elif defined(TARGET_X86)
1564 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1566 emit_bytes (acfg, buf, code - buf);
1569 emit_byte (acfg, '\xe9');
1570 emit_symbol_diff (acfg, call_target, ".", -4);
1571 #elif defined(TARGET_ARM)
1575 if (acfg->thumb_mixed && cfg->compile_llvm) {
1576 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1577 fprintf (acfg->fp, "b %s\n", call_target);
1578 fprintf (acfg->fp, ".arm\n");
1579 fprintf (acfg->fp, ".align 2\n");
1585 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1587 emit_bytes (acfg, buf, code - buf);
1588 /* jump to method */
1589 if (acfg->use_bin_writer) {
1596 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1597 emit_bytes (acfg, buf, 4);
1599 if (acfg->thumb_mixed && cfg->compile_llvm)
1600 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1602 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1604 #elif defined(TARGET_ARM64)
1605 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
1606 #elif defined(TARGET_POWERPC)
1609 g_assert (!acfg->use_bin_writer);
1611 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1612 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1614 g_assert_not_reached ();
1619 * arch_emit_static_rgctx_trampoline:
1621 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1622 * two GOT slots which contain the rgctx argument, and the method to jump to.
1623 * TRAMP_SIZE is set to the size of the emitted trampoline.
1624 * These kinds of trampolines cannot be enumerated statically, since there could
1625 * be one trampoline per method instantiation, so we emit the same code for all
1626 * trampolines, and parameterize them using two GOT slots.
1629 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1631 #if defined(TARGET_AMD64)
1632 #if defined(__default_codegen__)
1633 /* This should be exactly 13 bytes long */
1637 emit_unset_mode (acfg);
1638 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1639 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
1641 /* mov <OFFSET>(%rip), %r10 */
1642 emit_byte (acfg, '\x4d');
1643 emit_byte (acfg, '\x8b');
1644 emit_byte (acfg, '\x15');
1645 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1647 /* jmp *<offset>(%rip) */
1648 emit_byte (acfg, '\xff');
1649 emit_byte (acfg, '\x25');
1650 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1652 #elif defined(__native_client_codegen__)
1654 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1655 guint8 *code = buf_aligned;
1657 /* mov <OFFSET>(%rip), %r10d */
1658 emit_byte (acfg, '\x45');
1659 emit_byte (acfg, '\x8b');
1660 emit_byte (acfg, '\x15');
1661 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1663 /* mov <OFFSET>(%rip), %r11d */
1664 emit_byte (acfg, '\x45');
1665 emit_byte (acfg, '\x8b');
1666 emit_byte (acfg, '\x1d');
1667 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1670 amd64_jump_reg (code, AMD64_R11);
1671 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1673 emit_alignment (acfg, kNaClAlignment);
1674 *tramp_size = kNaClAlignment;
1675 #endif /*__native_client_codegen__*/
1677 #elif defined(TARGET_ARM)
1681 /* This should be exactly 24 bytes long */
1684 /* Load rgctx value */
1685 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1686 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1687 /* Load branch addr + branch */
1688 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1689 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1691 g_assert (code - buf == 16);
1694 emit_bytes (acfg, buf, code - buf);
1695 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1696 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1697 #elif defined(TARGET_ARM64)
1698 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
1699 #elif defined(TARGET_POWERPC)
1706 g_assert (!acfg->use_bin_writer);
1709 * PPC has no ip relative addressing, so we need to compute the address
1710 * of the mscorlib got. That is slow and complex, so instead, we store it
1711 * in the second got slot of every aot image. The caller already computed
1712 * the address of its got and placed it into r30.
1714 emit_unset_mode (acfg);
1715 /* Load mscorlib got address */
1716 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1718 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1719 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1720 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1721 /* Load target address */
1722 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1723 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1724 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1725 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1726 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1727 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1729 fprintf (acfg->fp, "mtctr 11\n");
1730 /* Branch to the target address */
1731 fprintf (acfg->fp, "bctr\n");
1733 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1734 *tramp_size = 11 * 4;
1736 *tramp_size = 9 * 4;
1739 #elif defined(TARGET_X86)
1743 /* Similar to the PPC code above */
1745 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1748 /* Load mscorlib got address */
1749 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1751 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1752 /* Branch to the target address */
1753 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1755 #ifdef __native_client_codegen__
1757 /* emit nops to next 32 byte alignment */
1758 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1759 while (code < (buf + a)) x86_nop(code);
1763 emit_bytes (acfg, buf, code - buf);
1765 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1766 g_assert (code - buf == *tramp_size);
1768 g_assert_not_reached ();
1773 * arch_emit_imt_thunk:
1775 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1776 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1777 * key is the IMT key, and ptr holds the address of a memory location holding
1778 * the address to branch to if the IMT arg matches the key. The array is
1779 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1781 * TRAMP_SIZE is set to the size of the emitted trampoline.
1784 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1786 #if defined(TARGET_AMD64)
1788 #if defined(__native_client_codegen__)
1791 guint8 *labels [16];
1793 guint8 *mov_buf_ptr = mov_buf;
1795 const int kSizeOfMove = 7;
1796 #if defined(__default_codegen__)
1797 code = buf = g_malloc (256);
1798 #elif defined(__native_client_codegen__)
1799 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1800 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1801 /* The RIP relative move below is emitted first */
1806 /* FIXME: Optimize this, i.e. use binary search etc. */
1807 /* Maybe move the body into a separate function (slower, but much smaller) */
1809 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1812 emit_unset_mode (acfg);
1813 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
1817 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1819 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1822 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1824 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1827 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1828 amd64_jump_code (code, labels [0]);
1831 mono_amd64_patch (labels [2], code);
1832 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1833 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1836 mono_amd64_patch (labels [1], code);
1837 /* Load fail tramp */
1838 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1839 /* Check if there is a fail tramp */
1840 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1842 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1843 /* Jump to fail tramp */
1844 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1847 mono_amd64_patch (labels [3], code);
1848 x86_breakpoint (code);
1851 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1852 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1853 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1854 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1855 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1856 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1858 emit_bytes (acfg, buf, code - buf);
1860 *tramp_size = code - buf + kSizeOfMove;
1861 #if defined(__native_client_codegen__)
1862 /* The tramp will be padded to the next kNaClAlignment bundle. */
1863 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1866 #if defined(__default_codegen__)
1868 #elif defined(__native_client_codegen__)
1872 #elif defined(TARGET_X86)
1874 #ifdef __native_client_codegen__
1877 guint8 *labels [16];
1879 #if defined(__default_codegen__)
1880 code = buf = g_malloc (256);
1881 #elif defined(__native_client_codegen__)
1882 buf_alloc = g_malloc (256 + kNaClAlignment);
1883 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1886 /* Allocate a temporary stack slot */
1887 x86_push_reg (code, X86_EAX);
1889 x86_push_reg (code, X86_EAX);
1891 /* Load mscorlib got address */
1892 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1894 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1897 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1899 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1902 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1904 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1907 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1908 x86_jump_code (code, labels [0]);
1911 mono_x86_patch (labels [2], code);
1912 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1913 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1914 /* Save the target address to the temporary stack location */
1915 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1917 x86_pop_reg (code, X86_EAX);
1918 /* Jump to the target address */
1922 mono_x86_patch (labels [1], code);
1923 /* Load fail tramp */
1924 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1925 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1927 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1928 /* Jump to fail tramp */
1929 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1930 x86_pop_reg (code, X86_EAX);
1934 mono_x86_patch (labels [3], code);
1935 x86_breakpoint (code);
1937 #ifdef __native_client_codegen__
1939 /* emit nops to next 32 byte alignment */
1940 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1941 while (code < (buf + a)) x86_nop(code);
1944 emit_bytes (acfg, buf, code - buf);
1946 *tramp_size = code - buf;
1948 #if defined(__default_codegen__)
1950 #elif defined(__native_client_codegen__)
1954 #elif defined(TARGET_ARM)
1956 guint8 *code, *code2, *labels [16];
1960 /* The IMT method is in v5 */
1962 /* Need at least two free registers, plus a slot for storing the pc */
1963 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1965 /* Load the parameter from the GOT */
1966 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1967 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1970 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1971 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1973 ARM_B_COND (code, ARMCOND_EQ, 0);
1975 /* End-of-loop check */
1976 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1978 ARM_B_COND (code, ARMCOND_EQ, 0);
1981 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1984 arm_patch (labels [4], labels [1]);
1987 arm_patch (labels [2], code);
1988 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1989 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1990 /* Save it to the third stack slot */
1991 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1992 /* Restore the registers and branch */
1993 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1996 arm_patch (labels [3], code);
1997 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1998 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1999 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2003 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2005 emit_bytes (acfg, buf, code - buf);
2006 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2008 *tramp_size = code - buf + 4;
2009 #elif defined(TARGET_ARM64)
2010 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2011 #elif defined(TARGET_POWERPC)
2013 guint8 *code, *labels [16];
2017 /* Load the mscorlib got address */
2018 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2019 /* Load the parameter from the GOT */
2020 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2021 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2023 /* Load and check key */
2025 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2026 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2028 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2030 /* End-of-loop check */
2031 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2033 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2036 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2039 mono_ppc_patch (labels [4], labels [1]);
2042 mono_ppc_patch (labels [2], code);
2043 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2044 /* r12 now contains the value of the vtable slot */
2045 /* this is not a function descriptor on ppc64 */
2046 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2047 ppc_mtctr (code, ppc_r12);
2048 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2051 mono_ppc_patch (labels [3], code);
2055 *tramp_size = code - buf;
2057 emit_bytes (acfg, buf, code - buf);
2059 g_assert_not_reached ();
2064 * arch_emit_gsharedvt_arg_trampoline:
2066 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2067 * two GOT slots which contain the argument, and the code to jump to.
2068 * TRAMP_SIZE is set to the size of the emitted trampoline.
2069 * These kinds of trampolines cannot be enumerated statically, since there could
2070 * be one trampoline per method instantiation, so we emit the same code for all
2071 * trampolines, and parameterize them using two GOT slots.
2074 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2076 #if defined(TARGET_X86)
2080 /* Similar to the PPC code above */
2082 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2085 /* Load mscorlib got address */
2086 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2088 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2089 /* Branch to the target address */
2090 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2092 #ifdef __native_client_codegen__
2094 /* emit nops to next 32 byte alignment */
2095 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
2096 while (code < (buf + a)) x86_nop(code);
2100 emit_bytes (acfg, buf, code - buf);
2102 *tramp_size = NACL_SIZE (15, kNaClAlignment);
2103 g_assert (code - buf == *tramp_size);
2104 #elif defined(TARGET_ARM)
2108 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2109 /* Similar to arch_emit_specific_trampoline () */
2112 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2113 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2114 /* Load the arg value from the GOT */
2115 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2116 /* Load the addr from the GOT */
2117 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2119 ARM_BX (code, ARMREG_R1);
2121 g_assert (code - buf == 20);
2124 emit_bytes (acfg, buf, code - buf);
2125 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2126 #elif defined(TARGET_ARM64)
2127 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2129 g_assert_not_reached ();
2134 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
2136 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
2137 /* Based on code generated by gcc */
2138 emit_unset_mode (acfg);
2141 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2142 ".section .ctors,\"aw\",@progbits\n"
2146 ".section .opd,\"aw\"\n"
2149 ".long .%s,.TOC.@tocbase32\n"
2152 ".type .%s,@function\n"
2154 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
2156 ".section .ctors,\"aw\",@progbits\n"
2160 ".section .opd,\"aw\"\n"
2163 ".long .%1$s,.TOC.@tocbase32\n"
2164 ".size %1$s,.-%1$s\n"
2166 ".type .%1$s,@function\n"
2168 ".%1$s:\n", symbol);
2179 "lis 3, .Lglobals@h\n"
2180 "ori 3, 3, .Lglobals@l\n"
2181 "bl .mono_aot_register_module\n"
2189 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
2191 ".size .%s,.-.%s\n", symbol, symbol);
2194 ".size .%1$s,.-.%1$s\n", symbol);
2200 /* END OF ARCH SPECIFIC CODE */
2203 mono_get_field_token (MonoClassField *field)
2205 MonoClass *klass = field->parent;
2208 for (i = 0; i < klass->field.count; ++i) {
2209 if (field == &klass->fields [i])
2210 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2213 g_assert_not_reached ();
2218 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2222 //printf ("ENCODE: %d 0x%x.\n", value, value);
2225 * Same encoding as the one used in the metadata, extended to handle values
2226 * greater than 0x1fffffff.
2228 if ((value >= 0) && (value <= 127))
2230 else if ((value >= 0) && (value <= 16383)) {
2231 p [0] = 0x80 | (value >> 8);
2232 p [1] = value & 0xff;
2234 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2235 p [0] = (value >> 24) | 0xc0;
2236 p [1] = (value >> 16) & 0xff;
2237 p [2] = (value >> 8) & 0xff;
2238 p [3] = value & 0xff;
2243 p [1] = (value >> 24) & 0xff;
2244 p [2] = (value >> 16) & 0xff;
2245 p [3] = (value >> 8) & 0xff;
2246 p [4] = value & 0xff;
2254 stream_init (MonoDynamicStream *sh)
2257 sh->alloc_size = 4096;
2258 sh->data = g_malloc (4096);
2260 /* So offsets are > 0 */
2266 make_room_in_stream (MonoDynamicStream *stream, int size)
2268 if (size <= stream->alloc_size)
2271 while (stream->alloc_size <= size) {
2272 if (stream->alloc_size < 4096)
2273 stream->alloc_size = 4096;
2275 stream->alloc_size *= 2;
2278 stream->data = g_realloc (stream->data, stream->alloc_size);
2282 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2286 make_room_in_stream (stream, stream->index + len);
2287 memcpy (stream->data + stream->index, data, len);
2288 idx = stream->index;
2289 stream->index += len;
2296 * Add data to the binary blob inside the aot image. Returns the offset inside the
2297 * blob where the data was stored.
2300 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2302 if (acfg->blob.alloc_size == 0)
2303 stream_init (&acfg->blob);
2305 return add_stream_data (&acfg->blob, (char*)data, data_len);
2309 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2314 if (acfg->blob.alloc_size == 0)
2315 stream_init (&acfg->blob);
2317 count = acfg->blob.index % align;
2319 /* we assume the stream data will be aligned */
2321 add_stream_data (&acfg->blob, buf, 4 - count);
2323 return add_stream_data (&acfg->blob, (char*)data, data_len);
2327 * emit_offset_table:
2329 * Emit a table of increasing offsets in a compact form using differential encoding.
2330 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2331 * group size, the more compact the table becomes, but the slower it becomes to compute
2332 * a given entry. Returns the size of the table.
2335 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2337 gint32 current_offset;
2338 int i, buf_size, ngroups, index_entry_size;
2340 guint32 *index_offsets;
2342 ngroups = (noffsets + (group_size - 1)) / group_size;
2344 index_offsets = g_new0 (guint32, ngroups);
2346 buf_size = noffsets * 4;
2347 p = buf = g_malloc0 (buf_size);
2350 for (i = 0; i < noffsets; ++i) {
2351 //printf ("D: %d -> %d\n", i, offsets [i]);
2352 if ((i % group_size) == 0) {
2353 index_offsets [i / group_size] = p - buf;
2354 /* Emit the full value for these entries */
2355 encode_value (offsets [i], p, &p);
2357 /* The offsets are allowed to be non-increasing */
2358 //g_assert (offsets [i] >= current_offset);
2359 encode_value (offsets [i] - current_offset, p, &p);
2361 current_offset = offsets [i];
2364 if (ngroups && index_offsets [ngroups - 1] < 65000)
2365 index_entry_size = 2;
2367 index_entry_size = 4;
2369 /* Emit the header */
2370 emit_int32 (acfg, noffsets);
2371 emit_int32 (acfg, group_size);
2372 emit_int32 (acfg, ngroups);
2373 emit_int32 (acfg, index_entry_size);
2375 /* Emit the index */
2376 for (i = 0; i < ngroups; ++i) {
2377 if (index_entry_size == 2)
2378 emit_int16 (acfg, index_offsets [i]);
2380 emit_int32 (acfg, index_offsets [i]);
2384 emit_bytes (acfg, buf, p - buf);
2386 return (int)(p - buf) + (ngroups * 4);
2390 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2394 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2398 index = g_hash_table_size (cfg->image_hash);
2399 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2400 g_ptr_array_add (cfg->image_table, image);
2406 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2409 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2411 /* FIXME: Search referenced images as well */
2412 if (!acfg->typespec_classes) {
2413 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2414 for (i = 0; i < len; ++i) {
2416 acfg->typespec_classes [i] = mono_class_get_and_inflate_typespec_checked (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL, &error);
2417 g_assert (mono_error_ok (&error)); /* FIXME error handling */
2420 for (i = 0; i < len; ++i) {
2421 if (acfg->typespec_classes [i] == klass)
2426 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2432 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2435 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2438 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2441 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2444 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2449 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2453 if (klass->generic_class) {
2455 g_assert (klass->type_token);
2457 /* Find a typespec for a class if possible */
2458 token = find_typespec_for_class (acfg, klass);
2460 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2461 encode_value (token, p, &p);
2463 MonoClass *gclass = klass->generic_class->container_class;
2464 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2465 static int count = 0;
2468 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2469 encode_klass_ref (acfg, gclass, p, &p);
2470 encode_ginst (acfg, inst, p, &p);
2474 } else if (klass->type_token) {
2475 int iindex = get_image_index (acfg, klass->image);
2477 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2479 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2480 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2482 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2483 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2484 encode_value (get_image_index (acfg, klass->image), p, &p);
2486 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2487 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2488 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2490 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2491 encode_value (klass->byval_arg.type, p, &p);
2492 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2494 encode_value (container ? 1 : 0, p, &p);
2496 encode_value (container->is_method, p, &p);
2497 g_assert (!par->gshared_constraint);
2498 if (container->is_method)
2499 encode_method_ref (acfg, container->owner.method, p, &p);
2501 encode_klass_ref (acfg, container->owner.klass, p, &p);
2503 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2504 if (par->gshared_constraint) {
2507 encode_type (acfg, par->gshared_constraint, p, &p);
2509 name = mono_generic_param_name (par);
2511 int len = strlen (name);
2513 encode_value (len, p, &p);
2514 memcpy (p, name, len);
2517 encode_value (0, p, &p);
2521 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2522 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2523 encode_type (acfg, &klass->byval_arg, p, &p);
2526 g_assert (klass->rank > 0);
2527 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2528 encode_value (klass->rank, p, &p);
2529 encode_klass_ref (acfg, klass->element_class, p, &p);
2537 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2538 * standard metadata encoding.
2541 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2543 gboolean shared = FALSE;
2546 * The encoding of generic instances is large so emit them only once.
2548 if (klass->generic_class) {
2550 g_assert (klass->type_token);
2552 /* Find a typespec for a class if possible */
2553 token = find_typespec_for_class (acfg, klass);
2556 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2561 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2565 buf2 = g_malloc (1024);
2568 encode_klass_ref_inner (acfg, klass, p, &p);
2569 g_assert (p - buf2 < 1024);
2571 offset = add_to_blob (acfg, buf2, p - buf2);
2574 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2580 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2581 encode_value (offset, p, &p);
2586 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2590 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2592 guint32 token = mono_get_field_token (field);
2595 encode_klass_ref (cfg, field->parent, p, &p);
2596 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2597 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2602 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2607 encode_value (inst->type_argc, p, &p);
2608 for (i = 0; i < inst->type_argc; ++i)
2609 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2614 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2617 MonoGenericInst *inst;
2619 inst = context->class_inst;
2621 g_assert (inst->type_argc);
2622 encode_ginst (acfg, inst, p, &p);
2624 encode_value (0, p, &p);
2626 inst = context->method_inst;
2628 g_assert (inst->type_argc);
2629 encode_ginst (acfg, inst, p, &p);
2631 encode_value (0, p, &p);
2637 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2641 g_assert (t->num_mods == 0);
2642 /* t->attrs can be ignored */
2643 //g_assert (t->attrs == 0);
2646 *p = MONO_TYPE_PINNED;
2650 *p = MONO_TYPE_BYREF;
2658 case MONO_TYPE_VOID:
2659 case MONO_TYPE_BOOLEAN:
2660 case MONO_TYPE_CHAR:
2673 case MONO_TYPE_STRING:
2674 case MONO_TYPE_OBJECT:
2675 case MONO_TYPE_TYPEDBYREF:
2677 case MONO_TYPE_VALUETYPE:
2678 case MONO_TYPE_CLASS:
2679 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2681 case MONO_TYPE_SZARRAY:
2682 encode_klass_ref (acfg, t->data.klass, p, &p);
2685 encode_type (acfg, t->data.type, p, &p);
2687 case MONO_TYPE_GENERICINST: {
2688 MonoClass *gclass = t->data.generic_class->container_class;
2689 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2691 encode_klass_ref (acfg, gclass, p, &p);
2692 encode_ginst (acfg, inst, p, &p);
2695 case MONO_TYPE_ARRAY: {
2696 MonoArrayType *array = t->data.array;
2699 encode_klass_ref (acfg, array->eklass, p, &p);
2700 encode_value (array->rank, p, &p);
2701 encode_value (array->numsizes, p, &p);
2702 for (i = 0; i < array->numsizes; ++i)
2703 encode_value (array->sizes [i], p, &p);
2704 encode_value (array->numlobounds, p, &p);
2705 for (i = 0; i < array->numlobounds; ++i)
2706 encode_value (array->lobounds [i], p, &p);
2710 case MONO_TYPE_MVAR:
2711 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2714 g_assert_not_reached ();
2721 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2727 /* Similar to the metadata encoding */
2728 if (sig->generic_param_count)
2732 if (sig->explicit_this)
2734 flags |= (sig->call_convention & 0x0F);
2738 if (sig->generic_param_count)
2739 encode_value (sig->generic_param_count, p, &p);
2740 encode_value (sig->param_count, p, &p);
2742 encode_type (acfg, sig->ret, p, &p);
2743 for (i = 0; i < sig->param_count; ++i) {
2744 if (sig->sentinelpos == i) {
2745 *p = MONO_TYPE_SENTINEL;
2748 encode_type (acfg, sig->params [i], p, &p);
2754 #define MAX_IMAGE_INDEX 250
2757 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2759 guint32 image_index = get_image_index (acfg, method->klass->image);
2760 guint32 token = method->token;
2761 MonoJumpInfoToken *ji;
2765 * The encoding for most methods is as follows:
2766 * - image index encoded as a leb128
2767 * - token index encoded as a leb128
2768 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2769 * types of method encodings.
2772 /* Mark methods which can't use aot trampolines because they need the further
2773 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2775 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2776 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2777 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2779 if (method->wrapper_type) {
2780 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2782 encode_value (method->wrapper_type, p, &p);
2784 switch (method->wrapper_type) {
2785 case MONO_WRAPPER_REMOTING_INVOKE:
2786 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2787 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2790 m = mono_marshal_method_from_wrapper (method);
2792 encode_method_ref (acfg, m, p, &p);
2795 case MONO_WRAPPER_PROXY_ISINST:
2796 case MONO_WRAPPER_LDFLD:
2797 case MONO_WRAPPER_LDFLDA:
2798 case MONO_WRAPPER_STFLD:
2799 case MONO_WRAPPER_ISINST: {
2800 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2803 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
2806 case MONO_WRAPPER_LDFLD_REMOTE:
2807 case MONO_WRAPPER_STFLD_REMOTE:
2809 case MONO_WRAPPER_ALLOC: {
2810 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2812 /* The GC name is saved once in MonoAotFileInfo */
2813 g_assert (info->alloc_type != -1);
2814 encode_value (info->alloc_type, p, &p);
2817 case MONO_WRAPPER_WRITE_BARRIER:
2819 case MONO_WRAPPER_STELEMREF: {
2820 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2823 encode_value (info->subtype, p, &p);
2824 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2825 encode_value (info->d.virtual_stelemref.kind, p, &p);
2828 case MONO_WRAPPER_UNKNOWN: {
2829 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2832 encode_value (info->subtype, p, &p);
2833 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2834 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2835 encode_klass_ref (acfg, method->klass, p, &p);
2836 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2837 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2838 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
2839 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
2842 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2843 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2846 encode_value (info->subtype, p, &p);
2847 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2848 strcpy ((char*)p, method->name);
2849 p += strlen (method->name) + 1;
2850 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2851 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2853 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
2854 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2858 case MONO_WRAPPER_SYNCHRONIZED: {
2861 m = mono_marshal_method_from_wrapper (method);
2863 g_assert (m != method);
2864 encode_method_ref (acfg, m, p, &p);
2867 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2868 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2871 encode_value (info->subtype, p, &p);
2873 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2874 encode_value (info->d.element_addr.rank, p, &p);
2875 encode_value (info->d.element_addr.elem_size, p, &p);
2876 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2877 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2879 g_assert_not_reached ();
2883 case MONO_WRAPPER_CASTCLASS: {
2884 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2887 encode_value (info->subtype, p, &p);
2890 case MONO_WRAPPER_RUNTIME_INVOKE: {
2891 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2894 encode_value (info->subtype, p, &p);
2895 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2896 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2897 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2898 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2901 case MONO_WRAPPER_DELEGATE_INVOKE:
2902 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2903 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2904 if (method->is_inflated) {
2905 /* These wrappers are identified by their class */
2906 encode_value (1, p, &p);
2907 encode_klass_ref (acfg, method->klass, p, &p);
2909 MonoMethodSignature *sig = mono_method_signature (method);
2910 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2912 encode_value (0, p, &p);
2913 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
2914 encode_value (info ? info->subtype : 0, p, &p);
2915 encode_signature (acfg, sig, p, &p);
2919 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2920 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2923 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2924 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2928 g_assert_not_reached ();
2930 } else if (mono_method_signature (method)->is_inflated) {
2932 * This is a generic method, find the original token which referenced it and
2934 * Obtain the token from information recorded by the JIT.
2936 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2938 image_index = get_image_index (acfg, ji->image);
2939 g_assert (image_index < MAX_IMAGE_INDEX);
2942 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2943 encode_value (image_index, p, &p);
2944 encode_value (token, p, &p);
2946 MonoMethod *declaring;
2947 MonoGenericContext *context = mono_method_get_context (method);
2949 g_assert (method->is_inflated);
2950 declaring = ((MonoMethodInflated*)method)->declaring;
2953 * This might be a non-generic method of a generic instance, which
2954 * doesn't have a token since the reference is generated by the JIT
2955 * like Nullable:Box/Unbox, or by generic sharing.
2957 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2958 /* Encode the klass */
2959 encode_klass_ref (acfg, method->klass, p, &p);
2960 /* Encode the method */
2961 image_index = get_image_index (acfg, method->klass->image);
2962 g_assert (image_index < MAX_IMAGE_INDEX);
2963 g_assert (declaring->token);
2964 token = declaring->token;
2965 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2966 encode_value (image_index, p, &p);
2967 encode_value (token, p, &p);
2968 encode_generic_context (acfg, context, p, &p);
2970 } else if (token == 0) {
2971 /* This might be a method of a constructed type like int[,].Set */
2972 /* Obtain the token from information recorded by the JIT */
2973 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2975 image_index = get_image_index (acfg, ji->image);
2976 g_assert (image_index < MAX_IMAGE_INDEX);
2979 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2980 encode_value (image_index, p, &p);
2981 encode_value (token, p, &p);
2984 g_assert (method->klass->rank);
2986 /* Encode directly */
2987 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2988 encode_klass_ref (acfg, method->klass, p, &p);
2989 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2990 encode_value (0, p, &p);
2991 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2992 encode_value (1, p, &p);
2993 else if (!strcmp (method->name, "Get"))
2994 encode_value (2, p, &p);
2995 else if (!strcmp (method->name, "Address"))
2996 encode_value (3, p, &p);
2997 else if (!strcmp (method->name, "Set"))
2998 encode_value (4, p, &p);
3000 g_assert_not_reached ();
3003 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3005 if (image_index >= MONO_AOT_METHODREF_MIN) {
3006 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3007 encode_value (image_index, p, &p);
3008 encode_value (mono_metadata_token_index (token), p, &p);
3010 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3017 compare_patches (gconstpointer a, gconstpointer b)
3021 i = (*(MonoJumpInfo**)a)->ip.i;
3022 j = (*(MonoJumpInfo**)b)->ip.i;
3033 static G_GNUC_UNUSED char*
3034 patch_to_string (MonoJumpInfo *patch_info)
3038 str = g_string_new ("");
3040 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3042 switch (patch_info->type) {
3043 case MONO_PATCH_INFO_VTABLE:
3044 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3049 g_string_append_printf (str, ")");
3050 return g_string_free (str, FALSE);
3056 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3059 static inline gboolean
3060 is_plt_patch (MonoJumpInfo *patch_info)
3062 switch (patch_info->type) {
3063 case MONO_PATCH_INFO_METHOD:
3064 case MONO_PATCH_INFO_INTERNAL_METHOD:
3065 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3066 case MONO_PATCH_INFO_ICALL_ADDR:
3067 case MONO_PATCH_INFO_CLASS_INIT:
3068 case MONO_PATCH_INFO_RGCTX_FETCH:
3069 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3070 case MONO_PATCH_INFO_MONITOR_ENTER:
3071 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
3072 case MONO_PATCH_INFO_MONITOR_EXIT:
3073 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3083 * Return the symbol identifying the plt entry PLT_OFFSET.
3086 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3090 * The Apple linker reorganizes object files, so it doesn't like branches to local
3091 * labels, since those have no relocations.
3093 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3095 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3102 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3104 static MonoPltEntry*
3105 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3108 gboolean synchronized = FALSE;
3109 static int synchronized_symbol_idx;
3111 if (!is_plt_patch (patch_info))
3114 if (!acfg->patch_to_plt_entry [patch_info->type])
3115 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3116 res = g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3118 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3120 * Allocate a separate PLT slot for each such patch, since some plt
3121 * entries will refer to the method itself, and some will refer to the
3125 synchronized = TRUE;
3129 MonoJumpInfo *new_ji;
3131 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3133 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3134 res->plt_offset = acfg->plt_offset;
3136 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3137 if (acfg->aot_opts.write_symbols)
3138 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3140 /* Avoid duplicate symbols because we don't cache */
3141 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3143 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3144 synchronized_symbol_idx ++;
3147 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3149 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3151 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3153 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3155 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3156 //mono_print_ji (patch_info); printf ("\n");
3157 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3159 acfg->plt_offset ++;
3168 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3169 * JI could be found if it exists, otherwise allocates a new one.
3172 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3175 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3177 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3179 return got_offset - 1;
3182 got_offset = acfg->llvm_got_offset;
3183 acfg->llvm_got_offset ++;
3185 got_offset = acfg->got_offset;
3186 acfg->got_offset ++;
3189 acfg->stats.got_slots ++;
3190 acfg->stats.got_slot_types [ji->type] ++;
3192 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3193 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3194 g_ptr_array_add (info->got_patches, ji);
3199 /* Add a method to the list of methods which need to be emitted */
3201 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3204 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3205 g_ptr_array_add (acfg->methods, method);
3206 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3207 acfg->nmethods = acfg->methods->len + 1;
3210 if (method->wrapper_type || extra)
3211 g_ptr_array_add (acfg->extra_methods, method);
3215 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3217 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3225 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3229 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3233 index = acfg->method_index;
3234 add_method_with_index (acfg, method, index, extra);
3236 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3238 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3240 acfg->method_index ++;
3246 add_method (MonoAotCompile *acfg, MonoMethod *method)
3248 return add_method_full (acfg, method, FALSE, 0);
3252 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3254 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
3255 method = mini_get_shared_method (method);
3257 if (acfg->aot_opts.log_generics)
3258 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3260 add_method_full (acfg, method, TRUE, depth);
3264 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3266 add_extra_method_with_depth (acfg, method, 0);
3270 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3272 MonoAotCompile *acfg = user_data;
3273 MonoJitICallInfo *callinfo = value;
3274 MonoMethod *wrapper;
3280 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3281 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
3284 add_method (acfg, wrapper);
3288 get_runtime_invoke_sig (MonoMethodSignature *sig)
3290 MonoMethodBuilder *mb;
3293 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3294 m = mono_mb_create_method (mb, sig, 16);
3295 return mono_marshal_get_runtime_invoke (m, FALSE);
3299 can_marshal_struct (MonoClass *klass)
3301 MonoClassField *field;
3302 gboolean can_marshal = TRUE;
3303 gpointer iter = NULL;
3304 MonoMarshalType *info;
3307 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3310 info = mono_marshal_load_type_info (klass);
3312 /* Only allow a few field types to avoid asserts in the marshalling code */
3313 while ((field = mono_class_get_fields (klass, &iter))) {
3314 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3317 switch (field->type->type) {
3322 case MONO_TYPE_BOOLEAN:
3325 case MONO_TYPE_CHAR:
3333 case MONO_TYPE_STRING:
3335 case MONO_TYPE_VALUETYPE:
3336 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3337 can_marshal = FALSE;
3339 case MONO_TYPE_SZARRAY: {
3340 gboolean has_mspec = FALSE;
3343 for (i = 0; i < info->num_fields; ++i) {
3344 if (info->fields [i].field == field && info->fields [i].mspec)
3349 can_marshal = FALSE;
3353 can_marshal = FALSE;
3359 /* Its hard to compute whenever these can be marshalled or not */
3360 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3367 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3369 /* Create a vtype instantiation */
3370 MonoGenericContext shared_context;
3372 MonoGenericInst *inst;
3373 MonoGenericContainer *container;
3374 MonoClass **constraints;
3377 memset (ctx, 0, sizeof (MonoGenericContext));
3379 if (method->klass->generic_container) {
3380 shared_context = method->klass->generic_container->context;
3381 inst = shared_context.class_inst;
3383 args = g_new0 (MonoType*, inst->type_argc);
3384 for (i = 0; i < inst->type_argc; ++i) {
3385 args [i] = &mono_defaults.int_class->byval_arg;
3387 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3389 if (method->is_generic) {
3390 container = mono_method_get_generic_container (method);
3391 shared_context = container->context;
3392 inst = shared_context.method_inst;
3394 args = g_new0 (MonoType*, inst->type_argc);
3395 for (i = 0; i < container->type_argc; ++i) {
3396 MonoGenericParamInfo *info = &container->type_params [i].info;
3397 gboolean ref_only = FALSE;
3399 if (info && info->constraints) {
3400 constraints = info->constraints;
3402 while (*constraints) {
3403 MonoClass *cklass = *constraints;
3404 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3405 /* Inflaring the method with our vtype would not be valid */
3412 args [i] = &mono_defaults.object_class->byval_arg;
3414 args [i] = &mono_defaults.int_class->byval_arg;
3416 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3421 add_wrappers (MonoAotCompile *acfg)
3423 MonoMethod *method, *m;
3425 MonoMethodSignature *sig, *csig;
3429 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3430 * so there is only one wrapper of a given type, or inlining their contents into their
3433 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3436 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3437 gboolean skip = FALSE;
3439 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3440 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3442 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3443 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3444 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3447 /* Skip methods which can not be handled by get_runtime_invoke () */
3448 sig = mono_method_signature (method);
3451 if ((sig->ret->type == MONO_TYPE_PTR) ||
3452 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3454 if (mono_class_is_open_constructed_type (sig->ret))
3457 for (j = 0; j < sig->param_count; j++) {
3458 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3460 if (mono_class_is_open_constructed_type (sig->params [j]))
3464 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3465 if (!mono_class_is_contextbound (method->klass)) {
3466 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3467 gboolean has_nullable = FALSE;
3469 for (j = 0; j < sig->param_count; j++) {
3470 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3471 has_nullable = TRUE;
3474 if (info && !has_nullable) {
3475 /* Supported by the dynamic runtime-invoke wrapper */
3479 mono_arch_dyn_call_free (info);
3484 //printf ("%s\n", mono_method_full_name (method, TRUE));
3485 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3489 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3492 /* Runtime invoke wrappers */
3494 /* void runtime-invoke () [.cctor] */
3495 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3496 csig->ret = &mono_defaults.void_class->byval_arg;
3497 add_method (acfg, get_runtime_invoke_sig (csig));
3499 /* void runtime-invoke () [Finalize] */
3500 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3502 csig->ret = &mono_defaults.void_class->byval_arg;
3503 add_method (acfg, get_runtime_invoke_sig (csig));
3505 /* void runtime-invoke (string) [exception ctor] */
3506 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3508 csig->ret = &mono_defaults.void_class->byval_arg;
3509 csig->params [0] = &mono_defaults.string_class->byval_arg;
3510 add_method (acfg, get_runtime_invoke_sig (csig));
3512 /* void runtime-invoke (string, string) [exception ctor] */
3513 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3515 csig->ret = &mono_defaults.void_class->byval_arg;
3516 csig->params [0] = &mono_defaults.string_class->byval_arg;
3517 csig->params [1] = &mono_defaults.string_class->byval_arg;
3518 add_method (acfg, get_runtime_invoke_sig (csig));
3520 /* string runtime-invoke () [Exception.ToString ()] */
3521 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3523 csig->ret = &mono_defaults.string_class->byval_arg;
3524 add_method (acfg, get_runtime_invoke_sig (csig));
3526 /* void runtime-invoke (string, Exception) [exception ctor] */
3527 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3529 csig->ret = &mono_defaults.void_class->byval_arg;
3530 csig->params [0] = &mono_defaults.string_class->byval_arg;
3531 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3532 add_method (acfg, get_runtime_invoke_sig (csig));
3534 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3535 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3537 csig->ret = &(mono_class_from_name (
3538 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3539 csig->params [0] = &mono_defaults.string_class->byval_arg;
3540 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3541 add_method (acfg, get_runtime_invoke_sig (csig));
3543 /* runtime-invoke used by finalizers */
3544 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3546 /* This is used by mono_runtime_capture_context () */
3547 method = mono_get_context_capture_method ();
3549 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3551 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3552 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3556 add_method (acfg, mono_marshal_get_stelemref ());
3558 if (MONO_ARCH_HAVE_TLS_GET) {
3559 /* Managed Allocators */
3560 nallocators = mono_gc_get_managed_allocator_types ();
3561 for (i = 0; i < nallocators; ++i) {
3562 m = mono_gc_get_managed_allocator_by_type (i);
3564 add_method (acfg, m);
3568 /* write barriers */
3569 if (mono_gc_is_moving ()) {
3570 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3571 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3574 /* Stelemref wrappers */
3576 MonoMethod **wrappers;
3579 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3580 for (i = 0; i < nwrappers; ++i)
3581 add_method (acfg, wrappers [i]);
3585 /* castclass_with_check wrapper */
3586 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3587 /* isinst_with_check wrapper */
3588 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3590 /* JIT icall wrappers */
3591 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3592 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3596 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3597 * we use the original method instead at runtime.
3598 * Since full-aot doesn't support remoting, this is not a problem.
3601 /* remoting-invoke wrappers */
3602 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3603 MonoMethodSignature *sig;
3605 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3606 method = mono_get_method (acfg->image, token, NULL);
3608 sig = mono_method_signature (method);
3610 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3611 m = mono_marshal_get_remoting_invoke_with_check (method);
3613 add_method (acfg, m);
3618 /* delegate-invoke wrappers */
3619 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3622 MonoCustomAttrInfo *cattr;
3624 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3625 klass = mono_class_get_checked (acfg->image, token, &error);
3628 mono_error_cleanup (&error);
3632 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3635 if (!klass->generic_container) {
3636 method = mono_get_delegate_invoke (klass);
3638 m = mono_marshal_get_delegate_invoke (method, NULL);
3640 add_method (acfg, m);
3642 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3644 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3646 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3648 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3650 cattr = mono_custom_attrs_from_class (klass);
3655 for (j = 0; j < cattr->num_attrs; ++j)
3656 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3658 if (j < cattr->num_attrs)
3659 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3661 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3663 MonoGenericContext ctx;
3664 MonoMethod *inst, *gshared;
3667 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3670 method = mono_get_delegate_invoke (klass);
3671 create_gsharedvt_inst (acfg, method, &ctx);
3673 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3674 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3676 m = mono_marshal_get_delegate_invoke (inst, NULL);
3677 g_assert (m->is_inflated);
3679 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3680 add_extra_method (acfg, gshared);
3683 method = mono_get_delegate_begin_invoke (klass);
3684 create_gsharedvt_inst (acfg, method, &ctx);
3686 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3687 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3689 m = mono_marshal_get_delegate_begin_invoke (inst);
3690 g_assert (m->is_inflated);
3692 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3693 add_extra_method (acfg, gshared);
3696 method = mono_get_delegate_end_invoke (klass);
3697 create_gsharedvt_inst (acfg, method, &ctx);
3699 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3700 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3702 m = mono_marshal_get_delegate_end_invoke (inst);
3703 g_assert (m->is_inflated);
3705 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3706 add_extra_method (acfg, gshared);
3711 /* array access wrappers */
3712 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3716 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3717 klass = mono_class_get_checked (acfg->image, token, &error);
3720 mono_error_cleanup (&error);
3724 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
3725 MonoMethod *m, *wrapper;
3727 /* Add runtime-invoke wrappers too */
3729 m = mono_class_get_method_from_name (klass, "Get", -1);
3731 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3732 add_extra_method (acfg, wrapper);
3733 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3735 m = mono_class_get_method_from_name (klass, "Set", -1);
3737 wrapper = mono_marshal_get_array_accessor_wrapper (m);
3738 add_extra_method (acfg, wrapper);
3739 add_extra_method (acfg, mono_marshal_get_runtime_invoke (wrapper, FALSE));
3743 /* Synchronized wrappers */
3744 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3746 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3747 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3748 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3750 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
3751 if (method->is_generic) {
3753 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
3755 MonoGenericContext ctx;
3756 MonoMethod *inst, *gshared, *m;
3759 * Create a generic wrapper for a generic instance, and AOT that.
3761 create_gsharedvt_inst (acfg, method, &ctx);
3762 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
3763 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3764 m = mono_marshal_get_synchronized_wrapper (inst);
3765 g_assert (m->is_inflated);
3766 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3767 add_method (acfg, gshared);
3769 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3774 /* pinvoke wrappers */
3775 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3778 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3780 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3781 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3783 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3784 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3785 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3789 /* native-to-managed wrappers */
3790 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3793 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3794 MonoCustomAttrInfo *cattr;
3797 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3798 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3801 * Only generate native-to-managed wrappers for methods which have an
3802 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3803 * name to avoid defining a new assembly to contain it.
3805 cattr = mono_custom_attrs_from_method (method);
3808 for (j = 0; j < cattr->num_attrs; ++j)
3809 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3811 if (j < cattr->num_attrs) {
3812 MonoCustomAttrEntry *e = &cattr->attrs [j];
3813 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3814 const char *p = (const char*)e->data;
3816 int slen, num_named, named_type;
3820 char *export_name = NULL;
3821 MonoMethod *wrapper;
3823 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3824 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3825 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3826 mono_method_full_name (method, TRUE));
3830 g_assert (sig->param_count == 1);
3831 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3834 * Decode the cattr manually since we can't create objects
3835 * during aot compilation.
3841 /* From load_cattr_value () in reflection.c */
3842 slen = mono_metadata_decode_value (p, &p);
3843 n = g_memdup (p, slen + 1);
3845 t = mono_reflection_type_from_name (n, acfg->image);
3849 klass = mono_class_from_mono_type (t);
3850 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3854 num_named = read16 (p);
3857 g_assert (num_named < 2);
3858 if (num_named == 1) {
3862 /* parse ExportSymbol attribute */
3864 named_type = *named;
3866 /* data_type = *named; */
3869 name_len = mono_metadata_decode_blob_size (named, &named);
3870 name = g_malloc (name_len + 1);
3871 memcpy (name, named, name_len);
3872 name [name_len] = 0;
3875 g_assert (named_type == 0x54);
3876 g_assert (!strcmp (name, "ExportSymbol"));
3878 /* load_cattr_value (), string case */
3879 g_assert (*named != (char)0xff);
3880 slen = mono_metadata_decode_value (named, &named);
3881 export_name = g_malloc (slen + 1);
3882 memcpy (export_name, named, slen);
3883 export_name [slen] = 0;
3887 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3888 add_method (acfg, wrapper);
3890 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3894 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3895 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3896 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3900 /* StructureToPtr/PtrToStructure wrappers */
3901 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3905 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3906 klass = mono_class_get_checked (acfg->image, token, &error);
3909 mono_error_cleanup (&error);
3913 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3914 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3915 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3916 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3922 has_type_vars (MonoClass *klass)
3924 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3927 return has_type_vars (klass->element_class);
3928 if (klass->generic_class) {
3929 MonoGenericContext *context = &klass->generic_class->context;
3930 if (context->class_inst) {
3933 for (i = 0; i < context->class_inst->type_argc; ++i)
3934 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3938 if (klass->generic_container)
3944 is_vt_inst (MonoGenericInst *inst)
3948 for (i = 0; i < inst->type_argc; ++i) {
3949 MonoType *t = inst->type_argv [i];
3950 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
3957 method_has_type_vars (MonoMethod *method)
3959 if (has_type_vars (method->klass))
3962 if (method->is_inflated) {
3963 MonoGenericContext *context = mono_method_get_context (method);
3964 if (context->method_inst) {
3967 for (i = 0; i < context->method_inst->type_argc; ++i)
3968 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3975 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3978 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3980 /* This might lead to a huge code blowup so only do it if neccesary */
3981 if (!acfg->aot_opts.full_aot && !force)
3984 add_generic_class_with_depth (acfg, klass, 0, ref);
3988 check_type_depth (MonoType *t, int depth)
3996 case MONO_TYPE_GENERICINST: {
3997 MonoGenericClass *gklass = t->data.generic_class;
3998 MonoGenericInst *ginst = gklass->context.class_inst;
4001 for (i = 0; i < ginst->type_argc; ++i) {
4002 if (check_type_depth (ginst->type_argv [i], depth + 1))
4016 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4019 * add_generic_class:
4021 * Add all methods of a generic class.
4024 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4027 MonoClassField *field;
4029 gboolean use_gsharedvt = FALSE;
4031 if (!acfg->ginst_hash)
4032 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4034 mono_class_init (klass);
4036 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4039 if (has_type_vars (klass))
4042 if (!klass->generic_class && !klass->rank)
4045 if (klass->exception_type)
4048 if (!acfg->ginst_hash)
4049 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4051 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4054 if (check_type_depth (&klass->byval_arg, 0))
4057 if (acfg->aot_opts.log_generics)
4058 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4060 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4063 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4064 * Enable this only for some classes since gsharedvt might not support all methods.
4066 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) &&
4067 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4068 use_gsharedvt = TRUE;
4071 while ((method = mono_class_get_methods (klass, &iter))) {
4072 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4074 * This is partial sharing, and we can't handle it yet
4079 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4081 add_types_from_method_header (acfg, method);
4085 if (method->is_generic)
4090 * FIXME: Instances which are referenced by these methods are not added,
4091 * for example Array.Resize<int> for List<int>.Add ().
4093 add_extra_method_with_depth (acfg, method, depth + 1);
4097 while ((field = mono_class_get_fields (klass, &iter))) {
4098 if (field->type->type == MONO_TYPE_GENERICINST)
4099 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4102 if (klass->delegate) {
4103 method = mono_get_delegate_invoke (klass);
4105 method = mono_marshal_get_delegate_invoke (method, NULL);
4107 if (acfg->aot_opts.log_generics)
4108 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
4110 add_method (acfg, method);
4113 /* Add superclasses */
4115 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4118 * For ICollection<T>, add instances of the helper methods
4119 * in Array, since a T[] could be cast to ICollection<T>.
4121 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4122 (!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"))) {
4123 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4124 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4128 if (!strcmp (klass->name, "IEnumerator`1"))
4129 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4131 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4133 /* Add the T[]/InternalEnumerator class */
4134 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4138 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4139 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4143 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
4144 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4148 while ((method = mono_class_get_methods (array_class, &iter))) {
4149 if (strstr (method->name, name_prefix)) {
4150 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4152 add_extra_method_with_depth (acfg, m, depth);
4156 g_free (name_prefix);
4159 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4160 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4161 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4162 MonoClass *icomparable, *gcomparer;
4163 MonoGenericContext ctx;
4164 MonoType *args [16];
4166 memset (&ctx, 0, sizeof (ctx));
4168 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
4169 g_assert (icomparable);
4170 args [0] = &tclass->byval_arg;
4171 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4173 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
4174 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4175 g_assert (gcomparer);
4176 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
4180 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4181 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4182 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4183 MonoClass *iface, *gcomparer;
4184 MonoGenericContext ctx;
4185 MonoType *args [16];
4187 memset (&ctx, 0, sizeof (ctx));
4189 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4191 args [0] = &tclass->byval_arg;
4192 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4194 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
4195 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4196 g_assert (gcomparer);
4197 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
4203 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4206 MonoGenericContext ctx;
4207 MonoType *args [16];
4209 if (acfg->aot_opts.no_instances)
4212 memset (&ctx, 0, sizeof (ctx));
4214 for (i = 0; i < ninsts; ++i) {
4215 args [0] = insts [i];
4216 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4217 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
4222 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4224 MonoMethodHeader *header;
4225 MonoMethodSignature *sig;
4228 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4230 sig = mono_method_signature (method);
4233 for (j = 0; j < sig->param_count; ++j)
4234 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4235 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4238 header = mono_method_get_header (method);
4241 for (j = 0; j < header->num_locals; ++j)
4242 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4243 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4245 mono_loader_clear_error ();
4250 * add_generic_instances:
4252 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4255 add_generic_instances (MonoAotCompile *acfg)
4260 MonoGenericContext *context;
4262 if (acfg->aot_opts.no_instances)
4265 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4267 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4268 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4271 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4272 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4273 mono_error_cleanup (&error);
4277 if (method->klass->image != acfg->image)
4280 context = mono_method_get_context (method);
4282 if (context && ((context->class_inst && context->class_inst->is_open)))
4286 * For open methods, create an instantiation which can be passed to the JIT.
4287 * FIXME: Handle class_inst as well.
4289 if (context && context->method_inst && context->method_inst->is_open) {
4291 MonoGenericContext shared_context;
4292 MonoGenericInst *inst;
4293 MonoType **type_argv;
4295 MonoMethod *declaring_method;
4296 gboolean supported = TRUE;
4298 /* Check that the context doesn't contain open constructed types */
4299 if (context->class_inst) {
4300 inst = context->class_inst;
4301 for (i = 0; i < inst->type_argc; ++i) {
4302 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)
4304 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4308 if (context->method_inst) {
4309 inst = context->method_inst;
4310 for (i = 0; i < inst->type_argc; ++i) {
4311 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)
4313 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4321 memset (&shared_context, 0, sizeof (MonoGenericContext));
4323 inst = context->class_inst;
4325 type_argv = g_new0 (MonoType*, inst->type_argc);
4326 for (i = 0; i < inst->type_argc; ++i) {
4327 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)
4328 type_argv [i] = &mono_defaults.object_class->byval_arg;
4330 type_argv [i] = inst->type_argv [i];
4333 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4337 inst = context->method_inst;
4339 type_argv = g_new0 (MonoType*, inst->type_argc);
4340 for (i = 0; i < inst->type_argc; ++i) {
4341 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)
4342 type_argv [i] = &mono_defaults.object_class->byval_arg;
4344 type_argv [i] = inst->type_argv [i];
4347 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4351 if (method->is_generic || method->klass->generic_container)
4352 declaring_method = method;
4354 declaring_method = mono_method_get_declaring_generic_method (method);
4356 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4357 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4361 * If the method is fully sharable, it was already added in place of its
4362 * generic definition.
4364 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4368 * FIXME: Partially shared methods are not shared here, so we end up with
4369 * many identical methods.
4371 add_extra_method (acfg, method);
4374 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4378 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4380 klass = mono_class_get_checked (acfg->image, token, &error);
4381 if (!klass || klass->rank) {
4382 mono_error_cleanup (&error);
4386 add_generic_class (acfg, klass, FALSE, "typespec");
4389 /* Add types of args/locals */
4390 for (i = 0; i < acfg->methods->len; ++i) {
4391 method = g_ptr_array_index (acfg->methods, i);
4392 add_types_from_method_header (acfg, method);
4395 if (acfg->image == mono_defaults.corlib) {
4397 MonoType *insts [256];
4400 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4401 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4402 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4403 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4404 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4405 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4406 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4407 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4408 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4409 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4410 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4411 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4413 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4414 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4416 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4417 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4419 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4421 /* Add instances of the array generic interfaces for primitive types */
4422 /* This will add instances of the InternalArray_ helper methods in Array too */
4423 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4425 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4426 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4428 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4429 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4431 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4434 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4435 * used for all instances of GetGenericValueImpl by the AOT runtime.
4438 MonoGenericContext ctx;
4439 MonoType *args [16];
4440 MonoMethod *get_method;
4441 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4443 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4447 memset (&ctx, 0, sizeof (ctx));
4448 args [0] = &mono_defaults.object_class->byval_arg;
4449 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4450 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4451 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4455 /* Same for CompareExchange<T>/Exchange<T> */
4457 MonoGenericContext ctx;
4458 MonoType *args [16];
4460 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4461 gpointer iter = NULL;
4463 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4464 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4466 memset (&ctx, 0, sizeof (ctx));
4467 args [0] = &mono_defaults.object_class->byval_arg;
4468 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4469 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4470 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4475 /* Same for Volatile.Read/Write<T> */
4477 MonoGenericContext ctx;
4478 MonoType *args [16];
4480 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4481 gpointer iter = NULL;
4483 if (volatile_klass) {
4484 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4485 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4487 memset (&ctx, 0, sizeof (ctx));
4488 args [0] = &mono_defaults.object_class->byval_arg;
4489 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4490 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4491 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4500 * is_direct_callable:
4502 * Return whenever the method identified by JI is directly callable without
4503 * going through the PLT.
4506 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4508 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4509 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4511 gboolean direct_callable = TRUE;
4513 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4514 direct_callable = FALSE;
4515 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4516 // FIXME: Maybe call the wrapper directly ?
4517 direct_callable = FALSE;
4519 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4520 /* Disable this so all calls go through load_method (), see the
4521 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4522 * mono_debugger_agent_init ().
4524 direct_callable = FALSE;
4527 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
4528 /* sgen does some initialization when the allocator method is created */
4529 direct_callable = FALSE;
4530 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
4531 /* we don't know at compile time whether sgen is concurrent or not */
4532 direct_callable = FALSE;
4534 if (direct_callable)
4537 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4538 if (acfg->aot_opts.direct_pinvoke)
4540 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4541 if (acfg->aot_opts.direct_icalls)
4549 #ifdef MONO_ARCH_AOT_SUPPORTED
4551 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4553 MonoImage *image = method->klass->image;
4554 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4555 MonoTableInfo *tables = image->tables;
4556 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4557 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4558 guint32 im_cols [MONO_IMPLMAP_SIZE];
4561 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4565 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4568 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4570 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4573 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4575 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4582 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
4584 if (a->native_offset == b->native_offset)
4585 return a->il_offset - b->il_offset;
4587 return a->native_offset - b->native_offset;
4591 * compute_line_numbers:
4593 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
4596 static MonoDebugSourceLocation**
4597 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
4599 MonoDebugMethodInfo *minfo;
4600 MonoDebugLineNumberEntry *ln_array;
4601 MonoDebugSourceLocation *loc;
4602 int i, prev_line, prev_il_offset;
4603 int *native_to_il_offset = NULL;
4604 MonoDebugSourceLocation **res;
4607 minfo = mono_debug_lookup_method (method);
4610 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
4611 if (debug_info->code_size != code_size)
4614 g_assert (code_size);
4616 /* Compute the native->IL offset mapping */
4618 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
4619 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
4621 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (gpointer)compare_lne);
4623 native_to_il_offset = g_new0 (int, code_size + 1);
4625 for (i = 0; i < debug_info->num_line_numbers; ++i) {
4627 MonoDebugLineNumberEntry *lne = &ln_array [i];
4630 for (j = 0; j < lne->native_offset; ++j)
4631 native_to_il_offset [j] = -1;
4634 if (i < debug_info->num_line_numbers - 1) {
4635 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
4637 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
4638 native_to_il_offset [j] = lne->il_offset;
4640 for (j = lne->native_offset; j < code_size; ++j)
4641 native_to_il_offset [j] = lne->il_offset;
4646 /* Compute the native->line number mapping */
4647 res = g_new0 (MonoDebugSourceLocation*, code_size);
4648 prev_il_offset = -1;
4651 for (i = 0; i < code_size; ++i) {
4652 int il_offset = native_to_il_offset [i];
4654 if (il_offset == -1 || il_offset == prev_il_offset)
4656 prev_il_offset = il_offset;
4657 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4658 if (!(loc && loc->source_file))
4660 if (loc->row == prev_line) {
4661 mono_debug_symfile_free_location (loc);
4664 prev_line = loc->row;
4665 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
4667 /* This will cover the prolog too */
4677 get_file_index (MonoAotCompile *acfg, const char *source_file)
4681 // FIXME: Free these
4682 if (!acfg->dwarf_ln_filenames)
4683 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
4684 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
4686 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
4687 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
4688 emit_unset_mode (acfg);
4689 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
4701 * emit_and_reloc_code:
4703 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4704 * is true, calls are made through the GOT too. This is used for emitting trampolines
4705 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4706 * since trampolines are needed to make PTL work.
4709 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
4711 int i, pindex, start_index;
4713 MonoJumpInfo *patch_info;
4714 MonoDebugSourceLocation **locs = NULL;
4716 #ifdef MONO_ARCH_AOT_SUPPORTED
4717 gboolean direct_call, external_call;
4719 const char *direct_call_target = 0;
4720 const char *direct_pinvoke;
4723 if (acfg->gas_line_numbers && method && debug_info) {
4724 locs = compute_line_numbers (method, code_len, debug_info);
4726 int findex = get_file_index (acfg, "<unknown>");
4727 emit_unset_mode (acfg);
4728 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
4732 /* Collect and sort relocations */
4733 patches = g_ptr_array_new ();
4734 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4735 g_ptr_array_add (patches, patch_info);
4736 g_ptr_array_sort (patches, compare_patches);
4739 for (i = 0; i < code_len; i += INST_LEN) {
4741 for (pindex = start_index; pindex < patches->len; ++pindex) {
4742 patch_info = g_ptr_array_index (patches, pindex);
4743 if (patch_info->ip.i >= i)
4747 if (locs && locs [i]) {
4748 MonoDebugSourceLocation *loc = locs [i];
4751 findex = get_file_index (acfg, loc->source_file);
4752 emit_unset_mode (acfg);
4753 fprintf (acfg->fp, ".loc %d %d 0\n", findex, loc->row);
4754 mono_debug_symfile_free_location (loc);
4758 #ifdef MONO_ARCH_AOT_SUPPORTED
4759 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4760 start_index = pindex;
4762 switch (patch_info->type) {
4763 case MONO_PATCH_INFO_NONE:
4765 case MONO_PATCH_INFO_GOT_OFFSET: {
4768 arch_emit_got_offset (acfg, code + i, &code_size);
4769 i += code_size - INST_LEN;
4771 patch_info->type = MONO_PATCH_INFO_NONE;
4774 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
4775 int code_size, index;
4776 char *selector = (void*)patch_info->data.target;
4778 if (!acfg->objc_selector_to_index)
4779 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
4780 if (!acfg->objc_selectors)
4781 acfg->objc_selectors = g_ptr_array_new ();
4782 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
4786 index = acfg->objc_selector_index;
4787 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
4788 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
4789 acfg->objc_selector_index ++;
4792 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
4793 i += code_size - INST_LEN;
4795 patch_info->type = MONO_PATCH_INFO_NONE;
4800 * If this patch is a call, try emitting a direct call instead of
4801 * through a PLT entry. This is possible if the called method is in
4802 * the same assembly and requires no initialization.
4804 direct_call = FALSE;
4805 external_call = FALSE;
4806 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4807 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4808 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4809 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4811 direct_call_target = callee_cfg->asm_symbol;
4812 patch_info->type = MONO_PATCH_INFO_NONE;
4813 acfg->stats.direct_calls ++;
4816 acfg->stats.all_calls ++;
4817 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4818 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4819 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4820 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4822 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4823 if (direct_pinvoke) {
4825 g_assert (strlen (direct_pinvoke) < 1000);
4826 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4829 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4830 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4831 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4832 /* Call to a C function implementing a jit icall */
4834 external_call = TRUE;
4835 g_assert (strlen (sym) < 1000);
4836 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4838 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4839 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4840 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4841 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4842 /* Call to a jit icall without a wrapper */
4844 external_call = TRUE;
4845 g_assert (strlen (sym) < 1000);
4846 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4851 patch_info->type = MONO_PATCH_INFO_NONE;
4852 acfg->stats.direct_calls ++;
4855 if (!got_only && !direct_call) {
4856 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4858 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4860 direct_call_target = plt_entry->symbol;
4862 /* Nullify the patch */
4863 patch_info->type = MONO_PATCH_INFO_NONE;
4864 plt_entry->jit_used = TRUE;
4871 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
4872 i += call_size - INST_LEN;
4876 got_slot = get_got_offset (acfg, FALSE, patch_info);
4878 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
4879 i += code_size - INST_LEN;
4885 #endif /* MONO_ARCH_AOT_SUPPORTED */
4888 /* Find next patch */
4890 for (pindex = start_index; pindex < patches->len; ++pindex) {
4891 patch_info = g_ptr_array_index (patches, pindex);
4892 if (patch_info->ip.i >= i)
4896 /* Try to emit multiple bytes at once */
4897 if (pindex < patches->len && patch_info->ip.i > i) {
4900 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
4901 if (locs && locs [limit])
4905 emit_code_bytes (acfg, code + i, limit - i);
4906 i = limit - INST_LEN;
4908 emit_code_bytes (acfg, code + i, INST_LEN);
4919 * Return a modified version of S which only includes characters permissible in symbols.
4922 sanitize_symbol (MonoAotCompile *acfg, char *s)
4924 gboolean process = FALSE;
4933 for (i = 0; i < len; ++i)
4934 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
4939 gs = g_string_sized_new (len);
4940 for (i = 0; i < len; ++i) {
4942 if (c <= 0x7f && (isalnum (c) || c == '_')) {
4943 g_string_append_c (gs, c);
4944 } else if (c > 0x7f) {
4945 /* multi-byte utf8 */
4946 g_string_append_printf (gs, "_0x%x", c);
4949 while (c >> 6 == 0x2) {
4950 g_string_append_printf (gs, "%x", c);
4954 g_string_append_printf (gs, "_");
4957 g_string_append_c (gs, '_');
4961 res = mono_mempool_strdup (acfg->mempool, gs->str);
4962 g_string_free (gs, TRUE);
4967 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4969 char *name1, *name2, *cached;
4970 int i, j, len, count;
4971 MonoMethod *cached_method;
4973 name1 = mono_method_full_name (method, TRUE);
4976 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4977 if ((!prefix || !*prefix) && name1 [0] == 'L')
4981 len = strlen (name1);
4982 name2 = malloc (strlen (prefix) + len + 16);
4983 memcpy (name2, prefix, strlen (prefix));
4984 j = strlen (prefix);
4985 for (i = 0; i < len; ++i) {
4986 if (isalnum (name1 [i])) {
4987 name2 [j ++] = name1 [i];
4988 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4990 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4993 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5003 cached_method = g_hash_table_lookup (cache, name2);
5004 if (!(cached_method && cached_method != method))
5006 sprintf (name2 + j, "_%d", count);
5010 cached = g_strdup (name2);
5011 g_hash_table_insert (cache, cached, method);
5017 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5022 char *debug_sym = NULL;
5023 char *symbol = NULL;
5024 int func_alignment = AOT_FUNC_ALIGNMENT;
5027 method = cfg->orig_method;
5028 code = cfg->native_code;
5030 method_index = get_method_index (acfg, method);
5031 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5033 /* Make the labels local */
5034 emit_section_change (acfg, ".text", 0);
5035 emit_alignment_code (acfg, func_alignment);
5037 if (acfg->global_symbols && acfg->need_no_dead_strip)
5038 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5040 emit_label (acfg, cfg->asm_symbol);
5042 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5044 * Write a C style symbol for every method, this has two uses:
5045 * - it works on platforms where the dwarf debugging info is not
5047 * - it allows the setting of breakpoints of aot-ed methods.
5049 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5050 cfg->asm_debug_symbol = g_strdup (debug_sym);
5052 if (acfg->need_no_dead_strip)
5053 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5054 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5055 emit_label (acfg, debug_sym);
5058 export_name = g_hash_table_lookup (acfg->export_names, method);
5060 /* Emit a global symbol for the method */
5061 emit_global_inner (acfg, export_name, TRUE);
5062 emit_label (acfg, export_name);
5065 if (cfg->verbose_level > 0)
5066 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
5068 acfg->stats.code_size += cfg->code_len;
5070 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5072 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 ()));
5076 if (acfg->aot_opts.write_symbols) {
5078 emit_symbol_size (acfg, debug_sym, ".");
5080 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5084 emit_label (acfg, symbol);
5091 * Encode PATCH_INFO into its disk representation.
5094 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5098 switch (patch_info->type) {
5099 case MONO_PATCH_INFO_NONE:
5101 case MONO_PATCH_INFO_IMAGE:
5102 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5104 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5105 case MONO_PATCH_INFO_JIT_TLS_ID:
5106 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5107 case MONO_PATCH_INFO_GC_NURSERY_START:
5109 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5110 encode_value (patch_info->data.index, p, &p);
5112 case MONO_PATCH_INFO_METHOD_REL:
5113 encode_value ((gint)patch_info->data.offset, p, &p);
5115 case MONO_PATCH_INFO_SWITCH: {
5116 gpointer *table = (gpointer *)patch_info->data.table->table;
5119 encode_value (patch_info->data.table->table_size, p, &p);
5120 for (k = 0; k < patch_info->data.table->table_size; k++)
5121 encode_value ((int)(gssize)table [k], p, &p);
5124 case MONO_PATCH_INFO_METHODCONST:
5125 case MONO_PATCH_INFO_METHOD:
5126 case MONO_PATCH_INFO_METHOD_JUMP:
5127 case MONO_PATCH_INFO_ICALL_ADDR:
5128 case MONO_PATCH_INFO_METHOD_RGCTX:
5129 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5130 encode_method_ref (acfg, patch_info->data.method, p, &p);
5132 case MONO_PATCH_INFO_INTERNAL_METHOD:
5133 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5134 guint32 len = strlen (patch_info->data.name);
5136 encode_value (len, p, &p);
5138 memcpy (p, patch_info->data.name, len);
5143 case MONO_PATCH_INFO_LDSTR: {
5144 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5145 guint32 token = patch_info->data.token->token;
5146 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5147 encode_value (image_index, p, &p);
5148 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5151 case MONO_PATCH_INFO_RVA:
5152 case MONO_PATCH_INFO_DECLSEC:
5153 case MONO_PATCH_INFO_LDTOKEN:
5154 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5155 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5156 encode_value (patch_info->data.token->token, p, &p);
5157 encode_value (patch_info->data.token->has_context, p, &p);
5158 if (patch_info->data.token->has_context)
5159 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5161 case MONO_PATCH_INFO_EXC_NAME: {
5162 MonoClass *ex_class;
5165 mono_class_from_name (mono_defaults.exception_class->image,
5166 "System", patch_info->data.target);
5167 g_assert (ex_class);
5168 encode_klass_ref (acfg, ex_class, p, &p);
5171 case MONO_PATCH_INFO_R4:
5172 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5174 case MONO_PATCH_INFO_R8:
5175 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5176 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5178 case MONO_PATCH_INFO_VTABLE:
5179 case MONO_PATCH_INFO_CLASS:
5180 case MONO_PATCH_INFO_IID:
5181 case MONO_PATCH_INFO_ADJUSTED_IID:
5182 case MONO_PATCH_INFO_CLASS_INIT:
5183 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5185 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5186 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5187 if (patch_info->data.del_tramp->method) {
5188 encode_value (1, p, &p);
5189 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5191 encode_value (0, p, &p);
5193 encode_value (patch_info->data.del_tramp->virtual, p, &p);
5195 case MONO_PATCH_INFO_FIELD:
5196 case MONO_PATCH_INFO_SFLDA:
5197 encode_field_info (acfg, patch_info->data.field, p, &p);
5199 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5201 case MONO_PATCH_INFO_RGCTX_FETCH: {
5202 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5207 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5208 * reference the same method, so encode the method only once.
5210 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5212 buf2 = g_malloc (1024);
5215 encode_method_ref (acfg, entry->method, p2, &p2);
5216 g_assert (p2 - buf2 < 1024);
5218 offset = add_to_blob (acfg, buf2, p2 - buf2);
5221 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5226 encode_value (offset, p, &p);
5227 g_assert ((int)entry->info_type < 256);
5228 g_assert (entry->data->type < 256);
5229 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5230 encode_patch (acfg, entry->data, p, &p);
5233 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5234 case MONO_PATCH_INFO_MONITOR_ENTER:
5235 case MONO_PATCH_INFO_MONITOR_ENTER_V4:
5236 case MONO_PATCH_INFO_MONITOR_EXIT:
5237 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5239 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
5240 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
5241 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
5243 case MONO_PATCH_INFO_SIGNATURE:
5244 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5246 case MONO_PATCH_INFO_TLS_OFFSET:
5247 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5249 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5250 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5251 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5253 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5254 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5257 encode_method_ref (acfg, info->method, p, &p);
5258 encode_value (info->num_entries, p, &p);
5259 for (i = 0; i < info->num_entries; ++i) {
5260 MonoRuntimeGenericContextInfoTemplate *template = &info->entries [i];
5262 encode_value (template->info_type, p, &p);
5263 switch (mini_rgctx_info_type_to_patch_info_type (template->info_type)) {
5264 case MONO_PATCH_INFO_CLASS:
5265 encode_klass_ref (acfg, mono_class_from_mono_type (template->data), p, &p);
5267 case MONO_PATCH_INFO_FIELD:
5268 encode_field_info (acfg, template->data, p, &p);
5271 g_assert_not_reached ();
5277 case MONO_PATCH_INFO_LDSTR_LIT: {
5278 const char *s = patch_info->data.target;
5279 int len = strlen (s);
5281 encode_value (len, p, &p);
5282 memcpy (p, s, len + 1);
5286 case MONO_PATCH_INFO_VIRT_METHOD:
5287 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5288 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5290 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5293 g_warning ("unable to handle jump info %d", patch_info->type);
5294 g_assert_not_reached ();
5301 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5304 guint32 pindex, offset;
5305 MonoJumpInfo *patch_info;
5307 encode_value (n_patches, p, &p);
5309 for (pindex = 0; pindex < patches->len; ++pindex) {
5310 patch_info = g_ptr_array_index (patches, pindex);
5312 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5316 offset = get_got_offset (acfg, llvm, patch_info);
5317 encode_value (offset, p, &p);
5324 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5328 int pindex, buf_size, n_patches;
5330 MonoJumpInfo *patch_info;
5331 guint32 method_index;
5333 guint32 first_got_offset;
5335 method = cfg->orig_method;
5337 method_index = get_method_index (acfg, method);
5339 /* Sort relocations */
5340 patches = g_ptr_array_new ();
5341 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5342 g_ptr_array_add (patches, patch_info);
5343 g_ptr_array_sort (patches, compare_patches);
5345 first_got_offset = acfg->cfgs [method_index]->got_offset;
5347 /**********************/
5348 /* Encode method info */
5349 /**********************/
5351 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5352 p = buf = g_malloc (buf_size);
5354 if (mono_class_get_cctor (method->klass))
5355 encode_klass_ref (acfg, method->klass, p, &p);
5357 /* Not needed when loading the method */
5358 encode_value (0, p, &p);
5361 if (cfg->opt & MONO_OPT_SHARED) {
5362 encode_value (g_list_length (cfg->ldstr_list), p, &p);
5363 for (l = cfg->ldstr_list; l; l = l->next) {
5364 encode_value ((long)l->data, p, &p);
5368 /* Used only in shared mode */
5369 g_assert (!cfg->ldstr_list);
5372 for (pindex = 0; pindex < patches->len; ++pindex) {
5373 patch_info = g_ptr_array_index (patches, pindex);
5375 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5376 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5377 patch_info->type = MONO_PATCH_INFO_NONE;
5382 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5383 /* Stored in a GOT slot initialized at module load time */
5384 patch_info->type = MONO_PATCH_INFO_NONE;
5388 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5389 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START) {
5390 /* Stored in a GOT slot initialized at module load time */
5391 patch_info->type = MONO_PATCH_INFO_NONE;
5395 if (is_plt_patch (patch_info)) {
5396 /* Calls are made through the PLT */
5397 patch_info->type = MONO_PATCH_INFO_NONE;
5405 g_assert (cfg->has_got_slots);
5407 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5409 acfg->stats.info_size += p - buf;
5411 g_assert (p - buf < buf_size);
5413 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5418 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5420 guint32 cache_index;
5423 /* Reuse the unwind module to canonize and store unwind info entries */
5424 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5426 /* Use +/- 1 to distinguish 0s from missing entries */
5427 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5435 * It would be easier to use assembler symbols, but the caller needs an
5438 offset = acfg->unwind_info_offset;
5439 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5440 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5443 encode_value (encoded_len, p, &p);
5445 acfg->unwind_info_offset += encoded_len + (p - buf);
5451 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5454 guint32 debug_info_size, seq_points_size;
5456 MonoMethodHeader *header;
5457 guint8 *p, *buf, *debug_info;
5458 MonoJitInfo *jinfo = cfg->jit_info;
5460 gboolean use_unwind_ops = FALSE;
5461 MonoSeqPointInfo *seq_points;
5463 code = cfg->native_code;
5464 header = cfg->header;
5466 if (!acfg->aot_opts.nodebug) {
5467 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5470 debug_info_size = 0;
5473 seq_points = cfg->seq_point_info;
5474 seq_points_size = (store_seq_points)? seq_point_info_get_write_size (seq_points) : 0;
5476 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5478 p = buf = g_malloc (buf_size);
5480 use_unwind_ops = cfg->unwind_ops != NULL;
5482 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points_size ? 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);
5484 encode_value (flags, p, &p);
5486 if (use_unwind_ops) {
5487 guint32 encoded_len;
5489 guint32 unwind_desc;
5491 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5493 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5494 encode_value (unwind_desc, p, &p);
5496 encode_value (jinfo->unwind_info, p, &p);
5499 /*Encode the number of holes before the number of clauses to make decoding easier*/
5500 if (jinfo->has_try_block_holes) {
5501 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5502 encode_value (table->num_holes, p, &p);
5505 if (jinfo->has_arch_eh_info) {
5507 * In AOT mode, the code length is calculated from the address of the previous method,
5508 * which could include alignment padding, so calculating the start of the epilog as
5509 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
5511 encode_value (jinfo->code_size, p, &p);
5514 /* Exception table */
5515 if (cfg->compile_llvm) {
5517 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
5518 * since the information is only available to llc. Instead, we let llc save the data
5519 * into the LSDA, and read it from there at runtime.
5521 /* The assembly might be CIL stripped so emit the data ourselves */
5522 if (header->num_clauses)
5523 encode_value (header->num_clauses, p, &p);
5525 for (k = 0; k < header->num_clauses; ++k) {
5526 MonoExceptionClause *clause;
5528 clause = &header->clauses [k];
5530 encode_value (clause->flags, p, &p);
5531 if (clause->data.catch_class) {
5532 encode_value (1, p, &p);
5533 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
5535 encode_value (0, p, &p);
5538 /* Emit a list of nesting clauses */
5539 for (i = 0; i < header->num_clauses; ++i) {
5541 MonoExceptionClause *clause1 = &header->clauses [cindex1];
5543 MonoExceptionClause *clause2 = &header->clauses [cindex2];
5545 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
5546 encode_value (i, p, &p);
5548 encode_value (-1, p, &p);
5551 if (jinfo->num_clauses)
5552 encode_value (jinfo->num_clauses, p, &p);
5554 for (k = 0; k < jinfo->num_clauses; ++k) {
5555 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
5557 encode_value (ei->flags, p, &p);
5558 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
5559 /* Not used for catch clauses */
5560 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
5561 encode_value (ei->exvar_offset, p, &p);
5563 encode_value (ei->exvar_offset, p, &p);
5566 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
5567 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
5569 if (ei->data.catch_class) {
5573 buf2 = g_malloc (4096);
5575 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
5577 g_assert (len < 4096);
5578 encode_value (len, p, &p);
5579 memcpy (p, buf2, len);
5583 encode_value (0, p, &p);
5587 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
5588 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
5589 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
5593 if (jinfo->has_try_block_holes) {
5594 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5595 for (i = 0; i < table->num_holes; ++i) {
5596 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
5597 encode_value (hole->clause, p, &p);
5598 encode_value (hole->length, p, &p);
5599 encode_value (hole->offset, p, &p);
5603 if (jinfo->has_arch_eh_info) {
5604 MonoArchEHJitInfo *eh_info;
5606 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5607 encode_value (eh_info->stack_size, p, &p);
5608 encode_value (eh_info->epilog_size, p, &p);
5611 if (jinfo->has_generic_jit_info) {
5612 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
5613 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
5617 encode_value (gi->nlocs, p, &p);
5619 for (i = 0; i < gi->nlocs; ++i) {
5620 MonoDwarfLocListEntry *entry = &gi->locations [i];
5622 encode_value (entry->is_reg ? 1 : 0, p, &p);
5623 encode_value (entry->reg, p, &p);
5625 encode_value (entry->offset, p, &p);
5627 g_assert (entry->from == 0);
5629 encode_value (entry->from, p, &p);
5630 encode_value (entry->to, p, &p);
5633 if (!cfg->compile_llvm) {
5634 encode_value (gi->has_this ? 1 : 0, p, &p);
5635 encode_value (gi->this_reg, p, &p);
5636 encode_value (gi->this_offset, p, &p);
5641 * Need to encode jinfo->method too, since it is not equal to 'method'
5642 * when using generic sharing.
5644 buf2 = g_malloc (4096);
5646 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
5648 g_assert (len < 4096);
5649 encode_value (len, p, &p);
5650 memcpy (p, buf2, len);
5654 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
5655 MonoMethodInflated *inflated;
5656 MonoGenericContext *context;
5657 MonoGenericInst *inst;
5659 g_assert (jinfo->d.method->is_inflated);
5660 inflated = (MonoMethodInflated*)jinfo->d.method;
5661 context = &inflated->context;
5663 encode_value (1, p, &p);
5664 if (context->class_inst) {
5665 inst = context->class_inst;
5667 encode_value (inst->type_argc, p, &p);
5668 for (i = 0; i < inst->type_argc; ++i)
5669 encode_value (gsctx->var_is_vt [i], p, &p);
5671 encode_value (0, p, &p);
5673 if (context->method_inst) {
5674 inst = context->method_inst;
5676 encode_value (inst->type_argc, p, &p);
5677 for (i = 0; i < inst->type_argc; ++i)
5678 encode_value (gsctx->mvar_is_vt [i], p, &p);
5680 encode_value (0, p, &p);
5683 encode_value (0, p, &p);
5687 if (seq_points_size)
5688 p += seq_point_info_write (seq_points, p);
5690 g_assert (debug_info_size < buf_size);
5692 encode_value (debug_info_size, p, &p);
5693 if (debug_info_size) {
5694 memcpy (p, debug_info, debug_info_size);
5695 p += debug_info_size;
5696 g_free (debug_info);
5701 encode_value (cfg->gc_map_size, p, &p);
5702 /* The GC map requires 4 bytes of alignment */
5703 while ((gsize)p % 4)
5705 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5706 p += cfg->gc_map_size;
5709 acfg->stats.ex_info_size += p - buf;
5711 g_assert (p - buf < buf_size);
5714 /* The GC Map requires 4 byte alignment */
5715 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5720 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5723 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
5725 int i, buf_size, res;
5726 gboolean no_special_static, cant_encode;
5727 gpointer iter = NULL;
5730 mono_error_cleanup (&error);
5734 p = buf = g_malloc (buf_size);
5736 /* Mark as unusable */
5737 encode_value (-1, p, &p);
5739 res = add_to_blob (acfg, buf, p - buf);
5745 buf_size = 10240 + (klass->vtable_size * 16);
5746 p = buf = g_malloc (buf_size);
5750 mono_class_init (klass);
5752 mono_class_get_nested_types (klass, &iter);
5753 g_assert (klass->nested_classes_inited);
5755 mono_class_setup_vtable (klass);
5758 * Emit all the information which is required for creating vtables so
5759 * the runtime does not need to create the MonoMethod structures which
5760 * take up a lot of space.
5763 no_special_static = !mono_class_has_special_static_fields (klass);
5765 /* Check whenever we have enough info to encode the vtable */
5766 cant_encode = FALSE;
5767 for (i = 0; i < klass->vtable_size; ++i) {
5768 MonoMethod *cm = klass->vtable [i];
5770 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5774 mono_class_has_finalizer (klass);
5776 if (klass->generic_container || cant_encode) {
5777 encode_value (-1, p, &p);
5779 encode_value (klass->vtable_size, p, &p);
5780 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);
5781 if (klass->has_cctor)
5782 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5783 if (klass->has_finalize)
5784 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5786 encode_value (klass->instance_size, p, &p);
5787 encode_value (mono_class_data_size (klass), p, &p);
5788 encode_value (klass->packing_size, p, &p);
5789 encode_value (klass->min_align, p, &p);
5791 for (i = 0; i < klass->vtable_size; ++i) {
5792 MonoMethod *cm = klass->vtable [i];
5795 encode_method_ref (acfg, cm, p, &p);
5797 encode_value (0, p, &p);
5801 acfg->stats.class_info_size += p - buf;
5803 g_assert (p - buf < buf_size);
5804 res = add_to_blob (acfg, buf, p - buf);
5811 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5813 char *debug_sym = NULL;
5817 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
5818 /* Need to add a prefix to create unique symbols */
5819 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
5821 prefix = g_strdup ("plt_");
5825 case MONO_PATCH_INFO_METHOD:
5826 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
5828 case MONO_PATCH_INFO_INTERNAL_METHOD:
5829 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
5831 case MONO_PATCH_INFO_CLASS_INIT:
5832 s = mono_type_get_name (&ji->data.klass->byval_arg);
5833 debug_sym = g_strdup_printf ("%s__class_init_%s", prefix, s);
5836 case MONO_PATCH_INFO_RGCTX_FETCH:
5837 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
5839 case MONO_PATCH_INFO_ICALL_ADDR: {
5840 char *s = get_debug_sym (ji->data.method, "", cache);
5842 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
5846 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5847 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
5849 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5850 debug_sym = g_strdup_printf ("%s_generic_class_init", prefix);
5858 return sanitize_symbol (acfg, debug_sym);
5862 * Calls made from AOTed code are routed through a table of jumps similar to the
5863 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5864 * control to the AOT runtime through a trampoline.
5867 emit_plt (MonoAotCompile *acfg)
5873 sprintf (symbol, "plt");
5875 emit_section_change (acfg, ".text", 0);
5876 emit_alignment_code (acfg, NACL_SIZE(16, kNaClAlignment));
5877 emit_label (acfg, symbol);
5878 emit_label (acfg, acfg->plt_symbol);
5880 for (i = 0; i < acfg->plt_offset; ++i) {
5881 char *debug_sym = NULL;
5882 MonoPltEntry *plt_entry = NULL;
5886 * The first plt entry is unused.
5890 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5892 debug_sym = plt_entry->debug_sym;
5894 if (acfg->thumb_mixed && !plt_entry->jit_used)
5895 /* Emit only a thumb version */
5898 /* Skip plt entries not actually called */
5899 if (!plt_entry->jit_used && !plt_entry->llvm_used)
5902 if (acfg->llvm && !acfg->thumb_mixed) {
5903 emit_label (acfg, plt_entry->llvm_symbol);
5905 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5906 #if defined(TARGET_MACH)
5907 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
5913 if (acfg->need_no_dead_strip) {
5914 emit_unset_mode (acfg);
5915 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5917 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5918 emit_label (acfg, debug_sym);
5921 emit_label (acfg, plt_entry->symbol);
5923 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
5926 emit_symbol_size (acfg, debug_sym, ".");
5929 if (acfg->thumb_mixed) {
5930 /* Make sure the ARM symbols don't alias the thumb ones */
5931 emit_zero_bytes (acfg, 16);
5934 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5937 for (i = 0; i < acfg->plt_offset; ++i) {
5938 char *debug_sym = NULL;
5939 MonoPltEntry *plt_entry = NULL;
5944 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5946 /* Skip plt entries not actually called by LLVM code */
5947 if (!plt_entry->llvm_used)
5950 if (acfg->aot_opts.write_symbols) {
5951 if (plt_entry->debug_sym)
5952 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5956 #if defined(TARGET_MACH)
5957 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5958 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5960 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5961 emit_label (acfg, debug_sym);
5963 fprintf (acfg->fp, "\n.thumb_func\n");
5965 emit_label (acfg, plt_entry->llvm_symbol);
5968 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
5970 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
5973 emit_symbol_size (acfg, debug_sym, ".");
5979 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5981 sprintf (symbol, "plt_end");
5982 emit_label (acfg, symbol);
5986 * emit_trampoline_full:
5988 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5989 * create_jit_info_for_trampoline ().
5991 static G_GNUC_UNUSED void
5992 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5994 char start_symbol [256];
5995 char end_symbol [256];
5997 guint32 buf_size, info_offset;
5998 MonoJumpInfo *patch_info;
6011 code_size = info->code_size;
6013 unwind_ops = info->unwind_ops;
6015 #ifdef __native_client_codegen__
6016 mono_nacl_fix_patches (code, ji);
6021 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6023 emit_section_change (acfg, ".text", 0);
6024 emit_global (acfg, start_symbol, TRUE);
6025 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6026 emit_label (acfg, start_symbol);
6028 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6029 emit_label (acfg, symbol);
6032 * The code should access everything through the GOT, so we pass
6035 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6037 emit_symbol_size (acfg, start_symbol, ".");
6040 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6041 emit_label (acfg, end_symbol);
6046 /* Sort relocations */
6047 patches = g_ptr_array_new ();
6048 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6049 if (patch_info->type != MONO_PATCH_INFO_NONE)
6050 g_ptr_array_add (patches, patch_info);
6051 g_ptr_array_sort (patches, compare_patches);
6053 buf_size = patches->len * 128 + 128;
6054 buf = g_malloc (buf_size);
6057 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6058 g_assert (p - buf < buf_size);
6060 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6062 info_offset = add_to_blob (acfg, buf, p - buf);
6064 emit_section_change (acfg, RODATA_SECT, 0);
6065 emit_global (acfg, symbol, FALSE);
6066 emit_label (acfg, symbol);
6068 emit_int32 (acfg, info_offset);
6072 guint32 encoded_len;
6076 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6078 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6079 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6082 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6083 emit_int32 (acfg, uw_offset);
6086 /* Emit debug info */
6090 sprintf (symbol, "%s", name);
6091 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6094 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6098 static G_GNUC_UNUSED void
6099 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6101 emit_trampoline_full (acfg, got_offset, info, FALSE);
6105 emit_trampolines (MonoAotCompile *acfg)
6108 char end_symbol [256];
6109 int i, tramp_got_offset;
6110 MonoAotTrampoline ntype;
6111 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6115 if (!acfg->aot_opts.full_aot)
6118 g_assert (acfg->image->assembly);
6120 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6121 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6122 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6123 MonoTrampInfo *info;
6126 * Emit the generic trampolines.
6128 * We could save some code by treating the generic trampolines as a wrapper
6129 * method, but that approach has its own complexities, so we choose the simpler
6132 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6133 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6134 #ifdef DISABLE_REMOTING
6135 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6138 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6139 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6142 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6143 emit_trampoline (acfg, acfg->got_offset, info);
6146 mono_arch_get_nullified_class_init_trampoline (&info);
6147 emit_trampoline (acfg, acfg->got_offset, info);
6148 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
6149 mono_arch_create_monitor_enter_trampoline (&info, FALSE, TRUE);
6150 emit_trampoline (acfg, acfg->got_offset, info);
6151 #if defined(MONO_ARCH_MONITOR_LOCK_TAKEN_REG)
6152 mono_arch_create_monitor_enter_trampoline (&info, TRUE, TRUE);
6153 emit_trampoline (acfg, acfg->got_offset, info);
6155 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
6156 emit_trampoline (acfg, acfg->got_offset, info);
6159 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
6160 emit_trampoline (acfg, acfg->got_offset, info);
6162 /* Emit the exception related code pieces */
6163 mono_arch_get_restore_context (&info, TRUE);
6164 emit_trampoline (acfg, acfg->got_offset, info);
6165 mono_arch_get_call_filter (&info, TRUE);
6166 emit_trampoline (acfg, acfg->got_offset, info);
6167 mono_arch_get_throw_exception (&info, TRUE);
6168 emit_trampoline (acfg, acfg->got_offset, info);
6169 mono_arch_get_rethrow_exception (&info, TRUE);
6170 emit_trampoline (acfg, acfg->got_offset, info);
6171 mono_arch_get_throw_corlib_exception (&info, TRUE);
6172 emit_trampoline (acfg, acfg->got_offset, info);
6174 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6175 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6176 emit_trampoline (acfg, acfg->got_offset, info);
6177 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6178 emit_trampoline (acfg, acfg->got_offset, info);
6181 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6182 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6184 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6186 /* Create a separate out trampoline for more information in stack traces */
6187 info->name = g_strdup ("gsharedvt_out_trampoline");
6188 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6192 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6194 GSList *l = mono_arch_get_trampolines (TRUE);
6197 MonoTrampInfo *info = l->data;
6199 emit_trampoline (acfg, acfg->got_offset, info);
6205 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6208 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6209 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6210 emit_trampoline (acfg, acfg->got_offset, info);
6212 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6213 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6214 emit_trampoline (acfg, acfg->got_offset, info);
6217 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6218 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6219 emit_trampoline (acfg, acfg->got_offset, info);
6225 /* delegate_invoke_impl trampolines */
6226 l = mono_arch_get_delegate_invoke_impls ();
6228 MonoTrampInfo *info = l->data;
6230 emit_trampoline (acfg, acfg->got_offset, info);
6235 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6237 /* Emit trampolines which are numerous */
6240 * These include the following:
6241 * - specific trampolines
6242 * - static rgctx invoke trampolines
6244 * These trampolines have the same code, they are parameterized by GOT
6246 * They are defined in this file, in the arch_... routines instead of
6247 * in tramp-<ARCH>.c, since it is easier to do it this way.
6251 * When running in aot-only mode, we can't create specific trampolines at
6252 * runtime, so we create a few, and save them in the AOT file.
6253 * Normal trampolines embed their argument as a literal inside the
6254 * trampoline code, we can't do that here, so instead we embed an offset
6255 * which needs to be added to the trampoline address to get the address of
6256 * the GOT slot which contains the argument value.
6257 * The generated trampolines jump to the generic trampolines using another
6258 * GOT slot, which will be setup by the AOT loader to point to the
6259 * generic trampoline code of the given type.
6263 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6267 emit_section_change (acfg, ".text", 0);
6269 tramp_got_offset = acfg->got_offset;
6271 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6273 case MONO_AOT_TRAMP_SPECIFIC:
6274 sprintf (symbol, "specific_trampolines");
6276 case MONO_AOT_TRAMP_STATIC_RGCTX:
6277 sprintf (symbol, "static_rgctx_trampolines");
6279 case MONO_AOT_TRAMP_IMT_THUNK:
6280 sprintf (symbol, "imt_thunks");
6282 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6283 sprintf (symbol, "gsharedvt_arg_trampolines");
6286 g_assert_not_reached ();
6289 sprintf (end_symbol, "%s_e", symbol);
6291 if (acfg->aot_opts.write_symbols)
6292 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6294 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6295 emit_label (acfg, symbol);
6297 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6299 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6303 case MONO_AOT_TRAMP_SPECIFIC:
6304 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6305 tramp_got_offset += 2;
6307 case MONO_AOT_TRAMP_STATIC_RGCTX:
6308 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6309 tramp_got_offset += 2;
6311 case MONO_AOT_TRAMP_IMT_THUNK:
6312 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6313 tramp_got_offset += 1;
6315 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6316 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6317 tramp_got_offset += 2;
6320 g_assert_not_reached ();
6322 #ifdef __native_client_codegen__
6323 /* align to avoid 32-byte boundary crossings */
6324 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6327 if (!acfg->trampoline_size [ntype]) {
6328 g_assert (tramp_size);
6329 acfg->trampoline_size [ntype] = tramp_size;
6333 emit_label (acfg, end_symbol);
6334 emit_int32 (acfg, 0);
6337 arch_emit_specific_trampoline_pages (acfg);
6339 /* Reserve some entries at the end of the GOT for our use */
6340 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6343 acfg->got_offset += acfg->num_trampoline_got_entries;
6347 str_begins_with (const char *str1, const char *str2)
6349 int len = strlen (str2);
6350 return strncmp (str1, str2, len) == 0;
6354 mono_aot_readonly_field_override (MonoClassField *field)
6357 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6358 char *p = rdv->name;
6360 len = strlen (field->parent->name_space);
6361 if (strncmp (p, field->parent->name_space, len))
6366 len = strlen (field->parent->name);
6367 if (strncmp (p, field->parent->name, len))
6372 if (strcmp (p, field->name))
6374 switch (rdv->type) {
6376 return &rdv->value.i1;
6378 return &rdv->value.i2;
6380 return &rdv->value.i4;
6389 add_readonly_value (MonoAotOptions *opts, const char *val)
6394 /* the format of val is:
6395 * namespace.typename.fieldname=type/value
6396 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6398 fval = strrchr (val, '/');
6400 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6403 tval = strrchr (val, '=');
6405 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6408 rdv = g_new0 (ReadOnlyValue, 1);
6409 rdv->name = g_malloc0 (tval - val + 1);
6410 memcpy (rdv->name, val, tval - val);
6413 if (strncmp (tval, "i1", 2) == 0) {
6414 rdv->value.i1 = atoi (fval);
6415 rdv->type = MONO_TYPE_I1;
6416 } else if (strncmp (tval, "i2", 2) == 0) {
6417 rdv->value.i2 = atoi (fval);
6418 rdv->type = MONO_TYPE_I2;
6419 } else if (strncmp (tval, "i4", 2) == 0) {
6420 rdv->value.i4 = atoi (fval);
6421 rdv->type = MONO_TYPE_I4;
6423 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6426 rdv->next = readonly_values;
6427 readonly_values = rdv;
6431 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
6433 gchar **args, **ptr;
6435 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
6436 for (ptr = args; ptr && *ptr; ptr ++) {
6437 const char *arg = *ptr;
6439 if (str_begins_with (arg, "outfile=")) {
6440 opts->outfile = g_strdup (arg + strlen ("outfile="));
6441 } else if (str_begins_with (arg, "llvm-outfile=")) {
6442 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
6443 } else if (str_begins_with (arg, "save-temps")) {
6444 opts->save_temps = TRUE;
6445 } else if (str_begins_with (arg, "keep-temps")) {
6446 opts->save_temps = TRUE;
6447 } else if (str_begins_with (arg, "write-symbols")) {
6448 opts->write_symbols = TRUE;
6449 } else if (str_begins_with (arg, "no-write-symbols")) {
6450 opts->write_symbols = FALSE;
6451 } else if (str_begins_with (arg, "metadata-only")) {
6452 opts->metadata_only = TRUE;
6453 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
6454 opts->bind_to_runtime_version = TRUE;
6455 } else if (str_begins_with (arg, "full")) {
6456 opts->full_aot = TRUE;
6457 } else if (str_begins_with (arg, "threads=")) {
6458 opts->nthreads = atoi (arg + strlen ("threads="));
6459 } else if (str_begins_with (arg, "static")) {
6460 opts->static_link = TRUE;
6461 opts->no_dlsym = TRUE;
6462 } else if (str_begins_with (arg, "asmonly")) {
6463 opts->asm_only = TRUE;
6464 } else if (str_begins_with (arg, "asmwriter")) {
6465 opts->asm_writer = TRUE;
6466 } else if (str_begins_with (arg, "nodebug")) {
6467 opts->nodebug = TRUE;
6468 } else if (str_begins_with (arg, "dwarfdebug")) {
6469 opts->dwarf_debug = TRUE;
6470 } else if (str_begins_with (arg, "nopagetrampolines")) {
6471 opts->use_trampolines_page = FALSE;
6472 } else if (str_begins_with (arg, "ntrampolines=")) {
6473 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
6474 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
6475 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
6476 } else if (str_begins_with (arg, "nimt-trampolines=")) {
6477 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
6478 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
6479 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
6480 } else if (str_begins_with (arg, "autoreg")) {
6481 opts->autoreg = TRUE;
6482 } else if (str_begins_with (arg, "tool-prefix=")) {
6483 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
6484 } else if (str_begins_with (arg, "ld-flags=")) {
6485 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
6486 } else if (str_begins_with (arg, "soft-debug")) {
6487 opts->soft_debug = TRUE;
6488 } else if (str_begins_with (arg, "gen-seq-points-file")) {
6489 opts->gen_seq_points_file = TRUE;
6490 } else if (str_begins_with (arg, "direct-pinvoke")) {
6491 opts->direct_pinvoke = TRUE;
6492 } else if (str_begins_with (arg, "direct-icalls")) {
6493 opts->direct_icalls = TRUE;
6494 } else if (str_begins_with (arg, "no-direct-calls")) {
6495 opts->no_direct_calls = TRUE;
6496 } else if (str_begins_with (arg, "print-skipped")) {
6497 opts->print_skipped_methods = TRUE;
6498 } else if (str_begins_with (arg, "stats")) {
6500 } else if (str_begins_with (arg, "no-instances")) {
6501 opts->no_instances = TRUE;
6502 } else if (str_begins_with (arg, "log-generics")) {
6503 opts->log_generics = TRUE;
6504 } else if (str_begins_with (arg, "log-instances=")) {
6505 opts->log_instances = TRUE;
6506 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
6507 } else if (str_begins_with (arg, "log-instances")) {
6508 opts->log_instances = TRUE;
6509 } else if (str_begins_with (arg, "internal-logfile=")) {
6510 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
6511 } else if (str_begins_with (arg, "mtriple=")) {
6512 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
6513 } else if (str_begins_with (arg, "llvm-path=")) {
6514 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
6515 if (!g_str_has_suffix (opts->llvm_path, G_DIR_SEPARATOR_S)) {
6516 gchar *old = opts->llvm_path;
6517 opts->llvm_path = g_strconcat (opts->llvm_path, G_DIR_SEPARATOR_S, NULL);
6520 } else if (!strcmp (arg, "llvm")) {
6522 } else if (str_begins_with (arg, "readonly-value=")) {
6523 add_readonly_value (opts, arg + strlen ("readonly-value="));
6524 } else if (str_begins_with (arg, "info")) {
6525 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
6527 } else if (str_begins_with (arg, "gc-maps")) {
6528 mini_gc_enable_gc_maps_for_aot ();
6529 } else if (str_begins_with (arg, "dump")) {
6530 opts->dump_json = TRUE;
6531 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
6532 printf ("Supported options for --aot:\n");
6533 printf (" outfile=\n");
6534 printf (" llvm-outfile=\n");
6535 printf (" save-temps\n");
6536 printf (" keep-temps\n");
6537 printf (" write-symbols\n");
6538 printf (" metadata-only\n");
6539 printf (" bind-to-runtime-version\n");
6541 printf (" threads=\n");
6542 printf (" static\n");
6543 printf (" asmonly\n");
6544 printf (" asmwriter\n");
6545 printf (" nodebug\n");
6546 printf (" dwarfdebug\n");
6547 printf (" ntrampolines=\n");
6548 printf (" nrgctx-trampolines=\n");
6549 printf (" nimt-trampolines=\n");
6550 printf (" ngsharedvt-trampolines=\n");
6551 printf (" autoreg\n");
6552 printf (" tool-prefix=\n");
6553 printf (" readonly-value=\n");
6554 printf (" soft-debug\n");
6555 printf (" gen-seq-points-file\n");
6556 printf (" gc-maps\n");
6557 printf (" print-skipped\n");
6558 printf (" no-instances\n");
6559 printf (" stats\n");
6562 printf (" help/?\n");
6565 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
6570 if (opts->use_trampolines_page) {
6571 opts->ntrampolines = 0;
6572 opts->nrgctx_trampolines = 0;
6573 opts->nimt_trampolines = 0;
6574 opts->ngsharedvt_arg_trampolines = 0;
6580 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
6582 MonoMethod *method = (MonoMethod*)key;
6583 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
6584 MonoAotCompile *acfg = user_data;
6585 MonoJumpInfoToken *new_ji;
6587 new_ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
6588 new_ji->image = ji->image;
6589 new_ji->token = ji->token;
6590 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
6594 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
6596 if (klass->type_token)
6598 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
6601 return can_encode_class (acfg, klass->element_class);
6606 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
6608 if (method->wrapper_type) {
6609 switch (method->wrapper_type) {
6610 case MONO_WRAPPER_NONE:
6611 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
6612 case MONO_WRAPPER_XDOMAIN_INVOKE:
6613 case MONO_WRAPPER_STFLD:
6614 case MONO_WRAPPER_LDFLD:
6615 case MONO_WRAPPER_LDFLDA:
6616 case MONO_WRAPPER_LDFLD_REMOTE:
6617 case MONO_WRAPPER_STFLD_REMOTE:
6618 case MONO_WRAPPER_STELEMREF:
6619 case MONO_WRAPPER_ISINST:
6620 case MONO_WRAPPER_PROXY_ISINST:
6621 case MONO_WRAPPER_ALLOC:
6622 case MONO_WRAPPER_REMOTING_INVOKE:
6623 case MONO_WRAPPER_UNKNOWN:
6624 case MONO_WRAPPER_WRITE_BARRIER:
6625 case MONO_WRAPPER_DELEGATE_INVOKE:
6626 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
6627 case MONO_WRAPPER_DELEGATE_END_INVOKE:
6628 case MONO_WRAPPER_SYNCHRONIZED:
6630 case MONO_WRAPPER_MANAGED_TO_MANAGED:
6631 case MONO_WRAPPER_CASTCLASS: {
6632 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
6641 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
6645 if (!method->token) {
6646 /* The method is part of a constructed type like Int[,].Set (). */
6647 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
6648 if (method->klass->rank)
6658 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
6660 switch (patch_info->type) {
6661 case MONO_PATCH_INFO_METHOD:
6662 case MONO_PATCH_INFO_METHODCONST:
6663 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
6664 MonoMethod *method = patch_info->data.method;
6666 return can_encode_method (acfg, method);
6668 case MONO_PATCH_INFO_VTABLE:
6669 case MONO_PATCH_INFO_CLASS_INIT:
6670 case MONO_PATCH_INFO_CLASS:
6671 case MONO_PATCH_INFO_IID:
6672 case MONO_PATCH_INFO_ADJUSTED_IID:
6673 if (!can_encode_class (acfg, patch_info->data.klass)) {
6674 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6678 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
6679 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
6680 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
6685 case MONO_PATCH_INFO_RGCTX_FETCH: {
6686 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
6688 if (!can_encode_method (acfg, entry->method))
6690 if (!can_encode_patch (acfg, entry->data))
6704 * AOT compile a given method.
6705 * This function might be called by multiple threads, so it must be thread-safe.
6708 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6711 MonoJumpInfo *patch_info;
6714 MonoMethod *wrapped;
6717 if (acfg->aot_opts.metadata_only)
6720 mono_acfg_lock (acfg);
6721 index = get_method_index (acfg, method);
6722 mono_acfg_unlock (acfg);
6724 /* fixme: maybe we can also precompile wrapper methods */
6725 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6726 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6727 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6728 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6732 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6735 wrapped = mono_marshal_method_from_wrapper (method);
6736 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6737 // FIXME: The wrapper should be generic too, but it is not
6740 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6743 InterlockedIncrement (&acfg->stats.mcount);
6746 if (method->is_generic || method->klass->generic_container) {
6747 InterlockedIncrement (&acfg->stats.genericcount);
6752 //acfg->aot_opts.print_skipped_methods = TRUE;
6755 * Since these methods are the only ones which are compiled with
6756 * AOT support, and they are not used by runtime startup/shutdown code,
6757 * the runtime will not see AOT methods during AOT compilation,so it
6758 * does not need to support them by creating a fake GOT etc.
6760 flags = JIT_FLAG_AOT;
6761 if (acfg->aot_opts.full_aot)
6762 flags |= JIT_FLAG_FULL_AOT;
6764 flags |= JIT_FLAG_LLVM;
6765 if (acfg->aot_opts.no_direct_calls)
6766 flags |= JIT_FLAG_NO_DIRECT_ICALLS;
6767 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0);
6768 mono_loader_clear_error ();
6770 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6771 if (acfg->aot_opts.print_skipped_methods)
6772 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6773 InterlockedIncrement (&acfg->stats.genericcount);
6776 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6777 if (acfg->aot_opts.print_skipped_methods)
6778 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6779 /* Let the exception happen at runtime */
6783 if (cfg->disable_aot) {
6784 if (acfg->aot_opts.print_skipped_methods)
6785 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6786 InterlockedIncrement (&acfg->stats.ocount);
6787 mono_destroy_compile (cfg);
6790 cfg->method_index = index;
6792 /* Nullify patches which need no aot processing */
6793 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6794 switch (patch_info->type) {
6795 case MONO_PATCH_INFO_LABEL:
6796 case MONO_PATCH_INFO_BB:
6797 patch_info->type = MONO_PATCH_INFO_NONE;
6804 /* Collect method->token associations from the cfg */
6805 mono_acfg_lock (acfg);
6806 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6807 mono_acfg_unlock (acfg);
6808 g_hash_table_destroy (cfg->token_info_hash);
6809 cfg->token_info_hash = NULL;
6812 * Check for absolute addresses.
6815 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6816 switch (patch_info->type) {
6817 case MONO_PATCH_INFO_ABS:
6818 /* unable to handle this */
6827 if (acfg->aot_opts.print_skipped_methods)
6828 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6829 InterlockedIncrement (&acfg->stats.abscount);
6830 mono_destroy_compile (cfg);
6834 /* Lock for the rest of the code */
6835 mono_acfg_lock (acfg);
6838 * Check for methods/klasses we can't encode.
6841 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6842 if (!can_encode_patch (acfg, patch_info))
6847 if (acfg->aot_opts.print_skipped_methods)
6848 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6849 acfg->stats.ocount++;
6850 mono_destroy_compile (cfg);
6851 mono_acfg_unlock (acfg);
6855 if (method->is_inflated && acfg->aot_opts.log_instances) {
6856 if (acfg->instances_logfile)
6857 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6859 printf ("%s ### %d\n", mono_method_full_name (method, TRUE), cfg->code_size);
6862 /* Adds generic instances referenced by this method */
6864 * The depth is used to avoid infinite loops when generic virtual recursion is
6867 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6868 if (!acfg->aot_opts.no_instances && depth < 32) {
6869 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6870 switch (patch_info->type) {
6871 case MONO_PATCH_INFO_METHOD: {
6872 MonoMethod *m = patch_info->data.method;
6873 if (m->is_inflated) {
6874 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6875 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6876 !method_has_type_vars (m)) {
6877 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6878 if (acfg->aot_opts.full_aot)
6879 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6881 add_extra_method_with_depth (acfg, m, depth + 1);
6882 add_types_from_method_header (acfg, m);
6885 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6887 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
6888 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
6890 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
6891 add_extra_method_with_depth (acfg, m, depth + 1);
6895 case MONO_PATCH_INFO_VTABLE: {
6896 MonoClass *klass = patch_info->data.klass;
6898 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6899 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6902 case MONO_PATCH_INFO_SFLDA: {
6903 MonoClass *klass = patch_info->data.field->parent;
6905 /* The .cctor needs to run at runtime. */
6906 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6907 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6916 /* Determine whenever the method has GOT slots */
6917 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6918 switch (patch_info->type) {
6919 case MONO_PATCH_INFO_GOT_OFFSET:
6920 case MONO_PATCH_INFO_NONE:
6921 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6922 case MONO_PATCH_INFO_GC_NURSERY_START:
6924 case MONO_PATCH_INFO_IMAGE:
6925 /* The assembly is stored in GOT slot 0 */
6926 if (patch_info->data.image != acfg->image)
6927 cfg->has_got_slots = TRUE;
6930 if (!is_plt_patch (patch_info))
6931 cfg->has_got_slots = TRUE;
6936 if (!cfg->has_got_slots)
6937 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6940 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6942 /* Make a copy of the patch info which is in the mempool */
6944 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6946 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6947 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6950 patches = new_patch_info;
6952 patches_end->next = new_patch_info;
6953 patches_end = new_patch_info;
6955 cfg->patch_info = patches;
6957 /* Make a copy of the unwind info */
6959 GSList *l, *unwind_ops;
6963 for (l = cfg->unwind_ops; l; l = l->next) {
6964 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6965 memcpy (op, l->data, sizeof (MonoUnwindOp));
6966 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6968 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6970 /* Make a copy of the argument/local info */
6972 MonoInst **args, **locals;
6973 MonoMethodSignature *sig;
6974 MonoMethodHeader *header;
6977 sig = mono_method_signature (method);
6978 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6979 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6980 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6981 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6985 header = mono_method_get_header (method);
6986 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6987 for (i = 0; i < header->num_locals; ++i) {
6988 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6989 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6991 cfg->locals = locals;
6994 /* Free some fields used by cfg to conserve memory */
6995 mono_mempool_destroy (cfg->mempool);
6996 cfg->mempool = NULL;
6997 g_free (cfg->varinfo);
6998 cfg->varinfo = NULL;
7002 mono_regstate_free (cfg->rs);
7006 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7008 while (index >= acfg->cfgs_size) {
7009 MonoCompile **new_cfgs;
7012 new_size = acfg->cfgs_size * 2;
7013 new_cfgs = g_new0 (MonoCompile*, new_size);
7014 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7015 g_free (acfg->cfgs);
7016 acfg->cfgs = new_cfgs;
7017 acfg->cfgs_size = new_size;
7019 acfg->cfgs [index] = cfg;
7021 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7024 if (cfg->orig_method->wrapper_type)
7025 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7028 mono_acfg_unlock (acfg);
7030 InterlockedIncrement (&acfg->stats.ccount);
7034 compile_thread_main (gpointer *user_data)
7036 MonoDomain *domain = user_data [0];
7037 MonoAotCompile *acfg = user_data [1];
7038 GPtrArray *methods = user_data [2];
7041 mono_thread_attach (domain);
7043 for (i = 0; i < methods->len; ++i)
7044 compile_method (acfg, g_ptr_array_index (methods, i));
7048 load_profile_files (MonoAotCompile *acfg)
7052 int file_index, res, method_index, i;
7055 GList *unordered, *l;
7060 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7062 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7067 infile = fopen (tmp, "r");
7070 printf ("Using profile data file '%s'\n", tmp);
7075 res = fscanf (infile, "%32s\n", ver);
7076 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7077 printf ("Profile file has wrong version or invalid.\n");
7084 MonoMethodDesc *desc;
7087 if (fgets (name, 1023, infile) == NULL)
7090 /* Kill the newline */
7091 if (strlen (name) > 0)
7092 name [strlen (name) - 1] = '\0';
7094 desc = mono_method_desc_new (name, TRUE);
7096 method = mono_method_desc_search_in_image (desc, acfg->image);
7098 if (method && mono_method_get_token (method)) {
7099 token = mono_method_get_token (method);
7100 method_index = mono_metadata_token_index (token) - 1;
7103 for (i = 0; i < acfg->method_order->len; ++i) {
7104 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7110 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7112 //printf ("No method found matching '%s'.\n", name);
7118 /* Add missing methods */
7120 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7122 for (i = 0; i < acfg->method_order->len; ++i) {
7123 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7129 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7131 unordered = g_list_reverse (unordered);
7132 for (l = unordered; l; l = l->next)
7133 g_ptr_array_add (acfg->method_order, l->data);
7136 /* Used by the LLVM backend */
7138 mono_aot_get_got_offset (MonoJumpInfo *ji)
7140 return get_got_offset (llvm_acfg, TRUE, ji);
7144 mono_aot_get_method_name (MonoCompile *cfg)
7146 if (llvm_acfg->aot_opts.static_link)
7147 /* Include the assembly name too to avoid duplicate symbol errors */
7148 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7150 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7154 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
7156 return is_direct_callable (llvm_acfg, NULL, patch_info);
7160 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
7162 MonoPltEntry *plt_entry;
7164 plt_entry = get_plt_entry (llvm_acfg, patch_info);
7165 plt_entry->llvm_used = FALSE;
7169 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
7171 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
7172 MonoPltEntry *plt_entry;
7173 const char *sym = NULL;
7176 ji->data.target = data;
7178 if (!can_encode_patch (llvm_acfg, ji))
7181 if (llvm_acfg->aot_opts.direct_icalls) {
7182 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
7183 /* Call to a C function implementing a jit icall */
7184 sym = mono_lookup_jit_icall_symbol (data);
7185 } else if (type == MONO_PATCH_INFO_ICALL_ADDR) {
7186 MonoMethod *method = (gpointer)data;
7187 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
7188 sym = mono_lookup_icall_symbol (method);
7191 return g_strdup (sym);
7194 plt_entry = get_plt_entry (llvm_acfg, ji);
7195 plt_entry->llvm_used = TRUE;
7197 #if defined(TARGET_MACH)
7198 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
7200 return g_strdup_printf (plt_entry->llvm_symbol);
7205 mono_aot_get_method_index (MonoMethod *method)
7207 g_assert (llvm_acfg);
7208 return get_method_index (llvm_acfg, method);
7212 mono_aot_patch_info_dup (MonoJumpInfo* ji)
7216 mono_acfg_lock (llvm_acfg);
7217 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
7218 mono_acfg_unlock (llvm_acfg);
7224 execute_system (const char * command)
7229 // We need an extra set of quotes around the whole command to properly handle commands
7230 // with spaces since internally the command is called through "cmd /c.
7231 command = g_strdup_printf ("\"%s\"", command);
7233 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
7234 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
7235 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
7236 status = _wsystem (wstr);
7241 status = system (command);
7252 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
7256 emit_llvm_file (MonoAotCompile *acfg)
7258 char *command, *opts, *tempbc, *output_fname;
7260 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
7261 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
7265 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
7266 * a lot of time, and doesn't seem to save much space.
7267 * The following optimizations cannot be enabled:
7269 * - 'jump-threading' changes our blockaddress references to int constants.
7270 * - 'basiccg' fails because it contains:
7271 * if (CS && !isa<IntrinsicInst>(II)) {
7272 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
7273 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
7274 * The opt list below was produced by taking the output of:
7275 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
7276 * then removing tailcallelim + the global opts.
7277 * strip-dead-prototypes deletes unused intrinsics definitions.
7279 opts = g_strdup ("-instcombine -simplifycfg");
7280 //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");
7281 /* The dse pass is disabled because of #13734 and #17616 */
7283 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
7284 * // If we have no DataLayout information around, then the size of the store
7285 * // is inferrable from the pointee type. If they are the same type, then
7286 * // we know that the store is safe.
7287 * if (AA.getDataLayout() == 0 &&
7288 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
7289 * return OverwriteComplete;
7290 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
7292 opts = g_strdup ("-targetlibinfo -no-aa -basicaa -notti -instcombine -simplifycfg -inline-cost -inline -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");
7294 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s.opt.bc\" \"%s.bc\"", acfg->aot_opts.llvm_path, opts, acfg->tmpbasename, acfg->tmpbasename);
7295 aot_printf (acfg, "Executing opt: %s\n", command);
7296 if (execute_system (command) != 0)
7301 if (!acfg->llc_args)
7302 acfg->llc_args = g_string_new ("");
7304 /* Verbose asm slows down llc greatly */
7305 g_string_append (acfg->llc_args, " -asm-verbose=false");
7307 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
7309 if (acfg->aot_opts.mtriple)
7310 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
7312 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s", acfg->llvm_eh_frame_symbol);
7314 #if defined(TARGET_MACH) && defined(TARGET_ARM)
7315 /* ios requires PIC code now */
7316 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7318 if (llvm_acfg->aot_opts.static_link)
7319 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
7321 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
7323 unlink (acfg->tmpfname);
7325 if (acfg->llvm_owriter) {
7326 /* Emit an object file directly */
7327 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
7328 g_string_append_printf (acfg->llc_args, " -filetype=obj");
7330 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
7332 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
7333 g_free (output_fname);
7335 aot_printf (acfg, "Executing llc: %s\n", command);
7337 if (execute_system (command) != 0)
7344 emit_code (MonoAotCompile *acfg)
7346 int oindex, i, prev_index;
7349 #if defined(TARGET_POWERPC64)
7350 sprintf (symbol, ".Lgot_addr");
7351 emit_section_change (acfg, ".text", 0);
7352 emit_alignment (acfg, 8);
7353 emit_label (acfg, symbol);
7354 emit_pointer (acfg, acfg->got_symbol);
7358 * This global symbol is used to compute the address of each method using the
7359 * code_offsets array. It is also used to compute the memory ranges occupied by
7360 * AOT code, so it must be equal to the address of the first emitted method.
7362 emit_section_change (acfg, ".text", 0);
7363 emit_alignment_code (acfg, 8);
7365 for (i = 0; i < acfg->nmethods; ++i) {
7366 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
7367 acfg->methods_symbol = g_strdup (acfg->cfgs [i]->asm_symbol);
7372 if (!acfg->methods_symbol) {
7373 sprintf (symbol, "methods");
7374 emit_label (acfg, symbol);
7375 acfg->methods_symbol = g_strdup (symbol);
7377 emit_label (acfg, "jit_code_start");
7380 * Emit some padding so the local symbol for the first method doesn't have the
7381 * same address as 'methods'.
7383 #if defined(__default_codegen__)
7384 emit_padding (acfg, 16);
7385 #elif defined(__native_client_codegen__)
7387 const int kPaddingSize = 16;
7388 guint8 pad_buffer[kPaddingSize];
7389 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
7390 emit_bytes (acfg, pad_buffer, kPaddingSize);
7394 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7398 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7400 cfg = acfg->cfgs [i];
7405 method = cfg->orig_method;
7407 /* Emit unbox trampoline */
7408 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7409 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
7411 emit_section_change (acfg, ".text", 0);
7412 #ifdef __native_client_codegen__
7413 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
7416 if (acfg->thumb_mixed && cfg->compile_llvm) {
7417 emit_set_thumb_mode (acfg);
7418 fprintf (acfg->fp, "\n.thumb_func\n");
7421 emit_label (acfg, symbol);
7423 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
7425 if (acfg->thumb_mixed && cfg->compile_llvm)
7426 emit_set_arm_mode (acfg);
7429 if (cfg->compile_llvm)
7430 acfg->stats.llvm_count ++;
7432 emit_method_code (acfg, cfg);
7435 emit_section_change (acfg, ".text", 0);
7436 emit_alignment_code (acfg, 8);
7437 emit_label (acfg, "jit_code_end");
7439 /* To distinguish it from the next symbol */
7440 emit_padding (acfg, 4);
7443 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
7444 * from optimizing them away, since it doesn't see that code_offsets references them.
7445 * JITted methods don't need this since they are referenced using assembler local
7447 * FIXME: This is why write-symbols doesn't work on OSX ?
7449 if (acfg->llvm && acfg->need_no_dead_strip) {
7450 fprintf (acfg->fp, "\n");
7451 for (i = 0; i < acfg->nmethods; ++i) {
7452 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
7453 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
7458 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
7459 * This is PIE code, and the linker can update it if needed.
7461 sprintf (symbol, "method_addresses");
7462 emit_section_change (acfg, ".text", 1);
7463 emit_alignment_code (acfg, 8);
7464 emit_label (acfg, symbol);
7465 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
7466 emit_unset_mode (acfg);
7467 if (acfg->need_no_dead_strip)
7468 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
7470 for (i = 0; i < acfg->nmethods; ++i) {
7471 #ifdef MONO_ARCH_AOT_SUPPORTED
7475 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
7477 arch_emit_direct_call (acfg, "method_addresses", FALSE, FALSE, NULL, &call_size);
7481 sprintf (symbol, "method_addresses_end");
7482 emit_label (acfg, symbol);
7485 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
7486 sprintf (symbol, "unbox_trampolines");
7487 emit_section_change (acfg, RODATA_SECT, 0);
7488 emit_alignment (acfg, 8);
7489 emit_label (acfg, symbol);
7492 for (i = 0; i < acfg->nmethods; ++i) {
7497 cfg = acfg->cfgs [i];
7501 method = cfg->orig_method;
7503 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7504 index = get_method_index (acfg, method);
7506 emit_int32 (acfg, index);
7507 /* Make sure the table is sorted by index */
7508 g_assert (index > prev_index);
7512 sprintf (symbol, "unbox_trampolines_end");
7513 emit_label (acfg, symbol);
7514 emit_int32 (acfg, 0);
7516 /* Emit a separate table with the trampoline addresses/offsets */
7517 sprintf (symbol, "unbox_trampoline_addresses");
7518 emit_section_change (acfg, ".text", 0);
7519 emit_alignment_code (acfg, 8);
7520 emit_label (acfg, symbol);
7522 for (i = 0; i < acfg->nmethods; ++i) {
7527 cfg = acfg->cfgs [i];
7531 method = cfg->orig_method;
7533 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
7534 #ifdef MONO_ARCH_AOT_SUPPORTED
7537 index = get_method_index (acfg, method);
7538 sprintf (symbol, "ut_%d", index);
7540 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
7544 emit_int32 (acfg, 0);
7548 emit_info (MonoAotCompile *acfg)
7554 offsets = g_new0 (gint32, acfg->nmethods);
7556 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
7557 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
7559 if (acfg->cfgs [i]) {
7560 emit_method_info (acfg, acfg->cfgs [i]);
7561 offsets [i] = acfg->cfgs [i]->method_info_offset;
7567 sprintf (symbol, "method_info_offsets");
7568 emit_section_change (acfg, RODATA_SECT, 1);
7569 emit_alignment (acfg, 8);
7570 emit_label (acfg, symbol);
7572 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7577 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
7579 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
7580 #define mix(a,b,c) { \
7581 a -= c; a ^= rot(c, 4); c += b; \
7582 b -= a; b ^= rot(a, 6); a += c; \
7583 c -= b; c ^= rot(b, 8); b += a; \
7584 a -= c; a ^= rot(c,16); c += b; \
7585 b -= a; b ^= rot(a,19); a += c; \
7586 c -= b; c ^= rot(b, 4); b += a; \
7588 #define final(a,b,c) { \
7589 c ^= b; c -= rot(b,14); \
7590 a ^= c; a -= rot(c,11); \
7591 b ^= a; b -= rot(a,25); \
7592 c ^= b; c -= rot(b,16); \
7593 a ^= c; a -= rot(c,4); \
7594 b ^= a; b -= rot(a,14); \
7595 c ^= b; c -= rot(b,24); \
7599 mono_aot_type_hash (MonoType *t1)
7601 guint hash = t1->type;
7603 hash |= t1->byref << 6; /* do not collide with t1->type values */
7605 case MONO_TYPE_VALUETYPE:
7606 case MONO_TYPE_CLASS:
7607 case MONO_TYPE_SZARRAY:
7608 /* check if the distribution is good enough */
7609 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
7611 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
7612 case MONO_TYPE_ARRAY:
7613 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
7614 case MONO_TYPE_GENERICINST:
7615 return ((hash << 5) - hash) ^ 0;
7622 * mono_aot_method_hash:
7624 * Return a hash code for methods which only depends on metadata.
7627 mono_aot_method_hash (MonoMethod *method)
7629 MonoMethodSignature *sig;
7633 guint32 *hashes_start, *hashes;
7635 MonoGenericInst *class_ginst = NULL;
7636 MonoGenericInst *ginst = NULL;
7638 /* Similar to the hash in mono_method_get_imt_slot () */
7640 sig = mono_method_signature (method);
7642 if (method->klass->generic_class)
7643 class_ginst = method->klass->generic_class->context.class_inst;
7644 if (method->is_inflated)
7645 ginst = ((MonoMethodInflated*)method)->context.method_inst;
7647 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
7648 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
7649 hashes = hashes_start;
7651 /* Some wrappers are assigned to random classes */
7652 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
7653 klass = method->klass;
7655 klass = mono_defaults.object_class;
7657 if (!method->wrapper_type) {
7660 if (klass->generic_class)
7661 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
7663 full_name = mono_type_full_name (&klass->byval_arg);
7665 hashes [0] = mono_metadata_str_hash (full_name);
7669 hashes [0] = mono_metadata_str_hash (klass->name);
7670 hashes [1] = mono_metadata_str_hash (klass->name_space);
7672 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
7673 /* The method name includes a stringified pointer */
7676 hashes [2] = mono_metadata_str_hash (method->name);
7677 hashes [3] = method->wrapper_type;
7678 hashes [4] = mono_aot_type_hash (sig->ret);
7680 for (i = 0; i < sig->param_count; i++) {
7681 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
7684 for (i = 0; i < class_ginst->type_argc; ++i)
7685 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
7688 for (i = 0; i < ginst->type_argc; ++i)
7689 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
7691 g_assert (hindex == hashes_count);
7693 /* Setup internal state */
7694 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
7696 /* Handle most of the hashes */
7697 while (hashes_count > 3) {
7706 /* Handle the last 3 hashes (all the case statements fall through) */
7707 switch (hashes_count) {
7708 case 3 : c += hashes [2];
7709 case 2 : b += hashes [1];
7710 case 1 : a += hashes [0];
7712 case 0: /* nothing left to add */
7716 free (hashes_start);
7725 * mono_aot_get_array_helper_from_wrapper;
7727 * Get the helper method in Array called by an array wrapper method.
7730 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
7734 MonoGenericContext ctx;
7735 MonoType *args [16];
7736 char *mname, *iname, *s, *s2, *helper_name = NULL;
7738 prefix = "System.Collections.Generic";
7739 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
7740 s2 = strstr (s, "`1.");
7746 //printf ("X: %s %s\n", iname, mname);
7748 if (!strcmp (iname, "IList"))
7749 helper_name = g_strdup_printf ("InternalArray__%s", mname);
7751 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
7752 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
7754 g_free (helper_name);
7757 if (m->is_generic) {
7759 memset (&ctx, 0, sizeof (ctx));
7760 args [0] = &method->klass->element_class->byval_arg;
7761 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
7762 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
7763 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
7769 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7771 typedef struct HashEntry {
7772 guint32 key, value, index;
7773 struct HashEntry *next;
7777 * emit_extra_methods:
7779 * Emit methods which are not in the METHOD table, like wrappers.
7782 emit_extra_methods (MonoAotCompile *acfg)
7784 int i, table_size, buf_size;
7787 guint32 *info_offsets;
7790 HashEntry *entry, *new_entry;
7791 int nmethods, max_chain_length;
7794 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7796 /* Emit method info */
7798 for (i = 0; i < acfg->extra_methods->len; ++i) {
7799 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7800 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7806 p = buf = g_malloc (buf_size);
7810 method = cfg->method_to_register;
7812 encode_method_ref (acfg, method, p, &p);
7814 g_assert ((p - buf) < buf_size);
7816 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7821 * Construct a chained hash table for mapping indexes in extra_method_info to
7824 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7825 table = g_ptr_array_sized_new (table_size);
7826 for (i = 0; i < table_size; ++i)
7827 g_ptr_array_add (table, NULL);
7828 chain_lengths = g_new0 (int, table_size);
7829 max_chain_length = 0;
7830 for (i = 0; i < acfg->extra_methods->len; ++i) {
7831 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7832 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7838 key = info_offsets [i];
7839 value = get_method_index (acfg, method);
7841 hash = mono_aot_method_hash (method) % table_size;
7842 //printf ("X: %s %x\n", mono_method_full_name (method, 1), mono_aot_method_hash (method));
7844 chain_lengths [hash] ++;
7845 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7847 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7848 new_entry->key = key;
7849 new_entry->value = value;
7851 entry = g_ptr_array_index (table, hash);
7852 if (entry == NULL) {
7853 new_entry->index = hash;
7854 g_ptr_array_index (table, hash) = new_entry;
7857 entry = entry->next;
7859 entry->next = new_entry;
7860 new_entry->index = table->len;
7861 g_ptr_array_add (table, new_entry);
7865 //printf ("MAX: %d\n", max_chain_length);
7867 /* Emit the table */
7868 sprintf (symbol, "extra_method_table");
7869 emit_section_change (acfg, RODATA_SECT, 0);
7870 emit_alignment (acfg, 8);
7871 emit_label (acfg, symbol);
7873 emit_int32 (acfg, table_size);
7874 for (i = 0; i < table->len; ++i) {
7875 HashEntry *entry = g_ptr_array_index (table, i);
7877 if (entry == NULL) {
7878 emit_int32 (acfg, 0);
7879 emit_int32 (acfg, 0);
7880 emit_int32 (acfg, 0);
7882 //g_assert (entry->key > 0);
7883 emit_int32 (acfg, entry->key);
7884 emit_int32 (acfg, entry->value);
7886 emit_int32 (acfg, entry->next->index);
7888 emit_int32 (acfg, 0);
7893 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7894 * This is used by mono_aot_find_jit_info ().
7896 sprintf (symbol, "extra_method_info_offsets");
7897 emit_section_change (acfg, RODATA_SECT, 0);
7898 emit_alignment (acfg, 8);
7899 emit_label (acfg, symbol);
7901 emit_int32 (acfg, acfg->extra_methods->len);
7902 for (i = 0; i < acfg->extra_methods->len; ++i) {
7903 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7905 emit_int32 (acfg, get_method_index (acfg, method));
7906 emit_int32 (acfg, info_offsets [i]);
7911 emit_exception_info (MonoAotCompile *acfg)
7916 SeqPointData sp_data;
7917 gboolean seq_points_to_file = FALSE;
7919 offsets = g_new0 (gint32, acfg->nmethods);
7920 for (i = 0; i < acfg->nmethods; ++i) {
7921 if (acfg->cfgs [i]) {
7922 MonoCompile *cfg = acfg->cfgs [i];
7924 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
7925 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
7926 gboolean method_seq_points_to_file = acfg->aot_opts.gen_seq_points_file &&
7927 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
7928 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
7930 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
7931 offsets [i] = cfg->ex_info_offset;
7933 if (method_seq_points_to_file) {
7934 if (!seq_points_to_file) {
7935 seq_point_data_init (&sp_data, acfg->nmethods);
7936 seq_points_to_file = TRUE;
7938 seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
7945 if (seq_points_to_file) {
7946 char *seq_points_aot_file;
7947 mono_image_get_aot_seq_point_path (acfg->image, &seq_points_aot_file);
7948 seq_point_data_write (&sp_data, seq_points_aot_file);
7949 seq_point_data_free (&sp_data);
7950 g_free (seq_points_aot_file);
7953 sprintf (symbol, "ex_info_offsets");
7954 emit_section_change (acfg, RODATA_SECT, 1);
7955 emit_alignment (acfg, 8);
7956 emit_label (acfg, symbol);
7958 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7963 emit_unwind_info (MonoAotCompile *acfg)
7969 * The unwind info contains a lot of duplicates so we emit each unique
7970 * entry once, and only store the offset from the start of the table in the
7974 sprintf (symbol, "unwind_info");
7975 emit_section_change (acfg, RODATA_SECT, 1);
7976 emit_alignment (acfg, 8);
7977 emit_label (acfg, symbol);
7979 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7980 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7981 guint8 *unwind_info;
7982 guint32 unwind_info_len;
7986 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7989 encode_value (unwind_info_len, p, &p);
7990 emit_bytes (acfg, buf, p - buf);
7991 emit_bytes (acfg, unwind_info, unwind_info_len);
7993 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7998 emit_class_info (MonoAotCompile *acfg)
8004 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
8005 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
8006 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
8008 sprintf (symbol, "class_info_offsets");
8009 emit_section_change (acfg, RODATA_SECT, 1);
8010 emit_alignment (acfg, 8);
8011 emit_label (acfg, symbol);
8013 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
8017 typedef struct ClassNameTableEntry {
8018 guint32 token, index;
8019 struct ClassNameTableEntry *next;
8020 } ClassNameTableEntry;
8023 emit_class_name_table (MonoAotCompile *acfg)
8026 guint32 token, hash;
8031 ClassNameTableEntry *entry, *new_entry;
8034 * Construct a chained hash table for mapping class names to typedef tokens.
8036 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
8037 table = g_ptr_array_sized_new (table_size);
8038 for (i = 0; i < table_size; ++i)
8039 g_ptr_array_add (table, NULL);
8040 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
8042 token = MONO_TOKEN_TYPE_DEF | (i + 1);
8043 klass = mono_class_get_checked (acfg->image, token, &error);
8045 mono_error_cleanup (&error);
8048 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8049 hash = mono_metadata_str_hash (full_name) % table_size;
8052 /* FIXME: Allocate from the mempool */
8053 new_entry = g_new0 (ClassNameTableEntry, 1);
8054 new_entry->token = token;
8056 entry = g_ptr_array_index (table, hash);
8057 if (entry == NULL) {
8058 new_entry->index = hash;
8059 g_ptr_array_index (table, hash) = new_entry;
8062 entry = entry->next;
8064 entry->next = new_entry;
8065 new_entry->index = table->len;
8066 g_ptr_array_add (table, new_entry);
8070 /* Emit the table */
8071 sprintf (symbol, "class_name_table");
8072 emit_section_change (acfg, RODATA_SECT, 0);
8073 emit_alignment (acfg, 8);
8074 emit_label (acfg, symbol);
8076 /* FIXME: Optimize memory usage */
8077 g_assert (table_size < 65000);
8078 emit_int16 (acfg, table_size);
8079 g_assert (table->len < 65000);
8080 for (i = 0; i < table->len; ++i) {
8081 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
8083 if (entry == NULL) {
8084 emit_int16 (acfg, 0);
8085 emit_int16 (acfg, 0);
8087 emit_int16 (acfg, mono_metadata_token_index (entry->token));
8089 emit_int16 (acfg, entry->next->index);
8091 emit_int16 (acfg, 0);
8097 emit_image_table (MonoAotCompile *acfg)
8103 * The image table is small but referenced in a lot of places.
8104 * So we emit it at once, and reference its elements by an index.
8107 sprintf (symbol, "image_table");
8108 emit_section_change (acfg, RODATA_SECT, 1);
8109 emit_alignment (acfg, 8);
8110 emit_label (acfg, symbol);
8112 emit_int32 (acfg, acfg->image_table->len);
8113 for (i = 0; i < acfg->image_table->len; i++) {
8114 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
8115 MonoAssemblyName *aname = &image->assembly->aname;
8117 /* FIXME: Support multi-module assemblies */
8118 g_assert (image->assembly->image == image);
8120 emit_string (acfg, image->assembly_name);
8121 emit_string (acfg, image->guid);
8122 emit_string (acfg, aname->culture ? aname->culture : "");
8123 emit_string (acfg, (const char*)aname->public_key_token);
8125 emit_alignment (acfg, 8);
8126 emit_int32 (acfg, aname->flags);
8127 emit_int32 (acfg, aname->major);
8128 emit_int32 (acfg, aname->minor);
8129 emit_int32 (acfg, aname->build);
8130 emit_int32 (acfg, aname->revision);
8135 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
8138 int i, first_plt_got_patch = 0, buf_size;
8140 guint32 *got_info_offsets;
8141 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
8143 /* Add the patches needed by the PLT to the GOT */
8145 acfg->plt_got_offset_base = acfg->got_offset;
8146 first_plt_got_patch = info->got_patches->len;
8147 for (i = 1; i < acfg->plt_offset; ++i) {
8148 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
8150 g_ptr_array_add (info->got_patches, plt_entry->ji);
8152 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
8155 acfg->got_offset += acfg->plt_offset;
8160 * - optimize offsets table.
8161 * - reduce number of exported symbols.
8162 * - emit info for a klass only once.
8163 * - determine when a method uses a GOT slot which is guaranteed to be already
8165 * - clean up and document the code.
8166 * - use String.Empty in class libs.
8169 /* Encode info required to decode shared GOT entries */
8170 buf_size = info->got_patches->len * 128;
8171 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
8172 got_info_offsets = mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
8174 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
8176 if (acfg->plt_offset)
8177 acfg->plt_got_info_offsets [0] = 0;
8179 for (i = 0; i < info->got_patches->len; ++i) {
8180 MonoJumpInfo *ji = g_ptr_array_index (info->got_patches, i);
8185 encode_value (ji->type, p, &p);
8187 encode_patch (acfg, ji, p, &p);
8188 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
8189 g_assert (p - buf <= buf_size);
8190 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8192 if (!llvm && i >= first_plt_got_patch)
8193 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
8194 acfg->stats.got_info_size += p - buf;
8197 /* Emit got_info_offsets table */
8199 sprintf (symbol, "llvm_got_info_offsets");
8201 sprintf (symbol, "got_info_offsets");
8202 emit_section_change (acfg, RODATA_SECT, 1);
8203 emit_alignment (acfg, 8);
8204 emit_label (acfg, symbol);
8206 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
8207 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
8211 emit_got (MonoAotCompile *acfg)
8215 /* Don't make GOT global so accesses to it don't need relocations */
8216 sprintf (symbol, "%s", acfg->got_symbol);
8217 emit_section_change (acfg, ".bss", 0);
8218 emit_alignment (acfg, 8);
8219 emit_local_symbol (acfg, symbol, "got_end", FALSE);
8220 emit_label (acfg, symbol);
8221 if (acfg->got_offset > 0)
8222 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8224 sprintf (symbol, "got_end");
8225 emit_label (acfg, symbol);
8228 typedef struct GlobalsTableEntry {
8229 guint32 value, index;
8230 struct GlobalsTableEntry *next;
8231 } GlobalsTableEntry;
8234 emit_globals (MonoAotCompile *acfg)
8240 GlobalsTableEntry *entry, *new_entry;
8242 if (!acfg->aot_opts.static_link)
8246 * When static linking, we emit a table containing our globals.
8250 * Construct a chained hash table for mapping global names to their index in
8251 * the globals table.
8253 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
8254 table = g_ptr_array_sized_new (table_size);
8255 for (i = 0; i < table_size; ++i)
8256 g_ptr_array_add (table, NULL);
8257 for (i = 0; i < acfg->globals->len; ++i) {
8258 char *name = g_ptr_array_index (acfg->globals, i);
8260 hash = mono_metadata_str_hash (name) % table_size;
8262 /* FIXME: Allocate from the mempool */
8263 new_entry = g_new0 (GlobalsTableEntry, 1);
8264 new_entry->value = i;
8266 entry = g_ptr_array_index (table, hash);
8267 if (entry == NULL) {
8268 new_entry->index = hash;
8269 g_ptr_array_index (table, hash) = new_entry;
8272 entry = entry->next;
8274 entry->next = new_entry;
8275 new_entry->index = table->len;
8276 g_ptr_array_add (table, new_entry);
8280 /* Emit the table */
8281 sprintf (symbol, ".Lglobals_hash");
8282 emit_section_change (acfg, RODATA_SECT, 0);
8283 emit_alignment (acfg, 8);
8284 emit_label (acfg, symbol);
8286 /* FIXME: Optimize memory usage */
8287 g_assert (table_size < 65000);
8288 emit_int16 (acfg, table_size);
8289 for (i = 0; i < table->len; ++i) {
8290 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
8292 if (entry == NULL) {
8293 emit_int16 (acfg, 0);
8294 emit_int16 (acfg, 0);
8296 emit_int16 (acfg, entry->value + 1);
8298 emit_int16 (acfg, entry->next->index);
8300 emit_int16 (acfg, 0);
8304 /* Emit the names */
8305 for (i = 0; i < acfg->globals->len; ++i) {
8306 char *name = g_ptr_array_index (acfg->globals, i);
8308 sprintf (symbol, "name_%d", i);
8309 emit_section_change (acfg, RODATA_SECT, 1);
8311 emit_alignment (acfg, 4);
8313 emit_label (acfg, symbol);
8314 emit_string (acfg, name);
8317 /* Emit the globals table */
8318 sprintf (symbol, "globals");
8319 emit_section_change (acfg, ".data", 0);
8320 /* This is not a global, since it is accessed by the init function */
8321 emit_alignment (acfg, 8);
8322 emit_label (acfg, symbol);
8324 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
8325 emit_pointer (acfg, symbol);
8327 for (i = 0; i < acfg->globals->len; ++i) {
8328 char *name = g_ptr_array_index (acfg->globals, i);
8330 sprintf (symbol, "name_%d", i);
8331 emit_pointer (acfg, symbol);
8333 g_assert (strlen (name) < sizeof (symbol));
8334 sprintf (symbol, "%s", name);
8335 emit_pointer (acfg, symbol);
8337 /* Null terminate the table */
8338 emit_int32 (acfg, 0);
8339 emit_int32 (acfg, 0);
8343 emit_autoreg (MonoAotCompile *acfg)
8348 * Emit a function into the .ctor section which will be called by the ELF
8349 * loader to register this module with the runtime.
8351 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
8354 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
8356 arch_emit_autoreg (acfg, symbol);
8362 emit_mem_end (MonoAotCompile *acfg)
8366 sprintf (symbol, "mem_end");
8367 emit_section_change (acfg, ".text", 1);
8368 emit_alignment_code (acfg, 8);
8369 emit_label (acfg, symbol);
8373 * Emit a structure containing all the information not stored elsewhere.
8376 emit_file_info (MonoAotCompile *acfg)
8381 const char *gc_name;
8384 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
8386 if (acfg->aot_opts.bind_to_runtime_version) {
8387 build_info = mono_get_runtime_build_info ();
8388 emit_string_symbol (acfg, "runtime_version", build_info);
8389 g_free (build_info);
8391 emit_string_symbol (acfg, "runtime_version", "");
8394 /* Emit a string holding the assembly name */
8395 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
8398 * The managed allocators are GC specific, so can't use an AOT image created by one GC
8401 gc_name = mono_gc_get_gc_name ();
8402 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
8404 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
8405 emit_section_change (acfg, ".data", 0);
8406 emit_alignment (acfg, 8);
8407 emit_label (acfg, symbol);
8408 if (!acfg->aot_opts.static_link)
8409 emit_global (acfg, symbol, FALSE);
8411 /* The data emitted here must match MonoAotFileInfo. */
8413 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
8414 emit_int32 (acfg, 0);
8417 * We emit pointers to our data structures instead of emitting global symbols which
8418 * point to them, to reduce the number of globals, and because using globals leads to
8419 * various problems (i.e. arm/thumb).
8421 emit_pointer (acfg, acfg->got_symbol);
8423 emit_pointer (acfg, acfg->llvm_got_symbol);
8425 emit_pointer (acfg, NULL);
8426 emit_pointer (acfg, acfg->methods_symbol);
8427 emit_pointer (acfg, "jit_code_start");
8428 emit_pointer (acfg, "jit_code_end");
8431 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
8433 emit_pointer (acfg, acfg->llvm_eh_frame_symbol);
8435 emit_pointer (acfg, NULL);
8437 emit_pointer (acfg, "blob");
8438 emit_pointer (acfg, "class_name_table");
8439 emit_pointer (acfg, "class_info_offsets");
8440 emit_pointer (acfg, "method_info_offsets");
8441 emit_pointer (acfg, "ex_info_offsets");
8442 emit_pointer (acfg, "method_addresses");
8443 emit_pointer (acfg, "extra_method_info_offsets");
8444 emit_pointer (acfg, "extra_method_table");
8445 emit_pointer (acfg, "got_info_offsets");
8447 emit_pointer (acfg, "llvm_got_info_offsets");
8449 emit_pointer (acfg, NULL);
8450 emit_pointer (acfg, "unwind_info");
8451 emit_pointer (acfg, "mem_end");
8452 emit_pointer (acfg, "image_table");
8453 emit_pointer (acfg, "plt");
8454 emit_pointer (acfg, "plt_end");
8455 emit_pointer (acfg, "assembly_guid");
8456 emit_pointer (acfg, "runtime_version");
8457 if (acfg->num_trampoline_got_entries) {
8458 emit_pointer (acfg, "specific_trampolines");
8459 emit_pointer (acfg, "static_rgctx_trampolines");
8460 emit_pointer (acfg, "imt_thunks");
8461 emit_pointer (acfg, "gsharedvt_arg_trampolines");
8463 emit_pointer (acfg, NULL);
8464 emit_pointer (acfg, NULL);
8465 emit_pointer (acfg, NULL);
8466 emit_pointer (acfg, NULL);
8468 if (acfg->thumb_mixed) {
8469 emit_pointer (acfg, "thumb_end");
8471 emit_pointer (acfg, NULL);
8473 if (acfg->aot_opts.static_link) {
8474 emit_pointer (acfg, "globals");
8476 emit_pointer (acfg, NULL);
8478 emit_pointer (acfg, "assembly_name");
8479 emit_pointer (acfg, "unbox_trampolines");
8480 emit_pointer (acfg, "unbox_trampolines_end");
8481 emit_pointer (acfg, "unbox_trampoline_addresses");
8483 emit_int32 (acfg, acfg->plt_got_offset_base);
8484 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
8485 emit_int32 (acfg, acfg->plt_offset);
8486 emit_int32 (acfg, acfg->nmethods);
8487 emit_int32 (acfg, acfg->flags);
8488 emit_int32 (acfg, acfg->opts);
8489 emit_int32 (acfg, acfg->simd_opts);
8490 emit_int32 (acfg, gc_name_offset);
8492 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8493 emit_int32 (acfg, acfg->num_trampolines [i]);
8494 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8495 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
8496 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8497 emit_int32 (acfg, acfg->trampoline_size [i]);
8498 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
8500 #if defined (TARGET_ARM) && defined (TARGET_MACH)
8505 memset (&t, 0, sizeof (MonoType));
8506 t.type = MONO_TYPE_R8;
8507 mono_type_size (&t, &align);
8508 emit_int32 (acfg, align);
8510 memset (&t, 0, sizeof (MonoType));
8511 t.type = MONO_TYPE_I8;
8512 mono_type_size (&t, &align);
8514 emit_int32 (acfg, align);
8517 emit_int32 (acfg, MONO_ABI_ALIGNOF (double));
8518 emit_int32 (acfg, MONO_ABI_ALIGNOF (gint64));
8520 emit_int32 (acfg, MONO_TRAMPOLINE_NUM);
8521 emit_int32 (acfg, acfg->tramp_page_size);
8522 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
8523 emit_int32 (acfg, acfg->tramp_page_code_offsets [i]);
8525 if (acfg->aot_opts.static_link) {
8529 * Emit a global symbol which can be passed by an embedding app to
8530 * mono_aot_register_module (). The symbol points to a pointer to the the file info
8533 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
8535 /* Get rid of characters which cannot occur in symbols */
8537 for (p = symbol; *p; ++p) {
8538 if (!(isalnum (*p) || *p == '_'))
8541 acfg->static_linking_symbol = g_strdup (symbol);
8542 emit_global_inner (acfg, symbol, FALSE);
8543 emit_alignment (acfg, sizeof (gpointer));
8544 emit_label (acfg, symbol);
8545 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
8550 emit_blob (MonoAotCompile *acfg)
8554 sprintf (symbol, "blob");
8555 emit_section_change (acfg, RODATA_SECT, 1);
8556 emit_alignment (acfg, 8);
8557 emit_label (acfg, symbol);
8559 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
8563 emit_objc_selectors (MonoAotCompile *acfg)
8568 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
8573 * cat > foo.m << EOF
8576 * return @selector(print:);
8581 img_writer_emit_unset_mode (acfg->w);
8582 g_assert (acfg->fp);
8583 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
8584 fprintf (acfg->fp, ".align 3\n");
8585 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8586 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
8587 emit_label (acfg, symbol);
8588 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
8589 emit_pointer (acfg, symbol);
8592 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
8593 for (i = 0; i < acfg->objc_selectors->len; ++i) {
8594 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
8595 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
8598 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
8599 fprintf (acfg->fp, ".align 3\n");
8600 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
8601 fprintf (acfg->fp, ".long 0\n");
8602 fprintf (acfg->fp, ".long 16\n");
8606 emit_dwarf_info (MonoAotCompile *acfg)
8608 #ifdef EMIT_DWARF_INFO
8612 /* DIEs for methods */
8613 for (i = 0; i < acfg->nmethods; ++i) {
8614 MonoCompile *cfg = acfg->cfgs [i];
8619 // FIXME: LLVM doesn't define .Lme_...
8620 if (cfg->compile_llvm)
8623 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
8625 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, 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 ()));
8631 collect_methods (MonoAotCompile *acfg)
8634 MonoImage *image = acfg->image;
8636 /* Collect methods */
8637 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
8640 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
8642 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8645 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
8646 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
8647 mono_error_cleanup (&error);
8651 /* Load all methods eagerly to skip the slower lazy loading code */
8652 mono_class_setup_methods (method->klass);
8654 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
8655 /* Compile the wrapper instead */
8656 /* We do this here instead of add_wrappers () because it is easy to do it here */
8657 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
8661 /* FIXME: Some mscorlib methods don't have debug info */
8663 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
8664 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
8665 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
8666 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
8667 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
8668 if (!mono_debug_lookup_method (method)) {
8669 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
8676 /* Since we add the normal methods first, their index will be equal to their zero based token index */
8677 add_method_with_index (acfg, method, i, FALSE);
8678 acfg->method_index ++;
8681 /* gsharedvt methods */
8682 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
8685 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
8687 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
8690 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
8691 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
8694 if (strcmp (method->name, "gshared2"))
8698 if (!strstr (method->klass->image->name, "mini"))
8701 if (method->is_generic || method->klass->generic_container) {
8702 MonoMethod *gshared;
8704 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
8705 add_extra_method (acfg, gshared);
8709 add_generic_instances (acfg);
8711 if (acfg->aot_opts.full_aot)
8712 add_wrappers (acfg);
8717 compile_methods (MonoAotCompile *acfg)
8721 if (acfg->aot_opts.nthreads > 0) {
8726 gpointer *user_data;
8727 MonoMethod **methods;
8729 methods_len = acfg->methods->len;
8731 len = acfg->methods->len / acfg->aot_opts.nthreads;
8734 * Partition the list of methods into fragments, and hand it to threads to
8737 threads = g_ptr_array_new ();
8738 /* Make a copy since acfg->methods is modified by compile_method () */
8739 methods = g_new0 (MonoMethod*, methods_len);
8740 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
8741 for (i = 0; i < methods_len; ++i)
8742 methods [i] = g_ptr_array_index (acfg->methods, i);
8744 while (i < methods_len) {
8745 frag = g_ptr_array_new ();
8746 for (j = 0; j < len; ++j) {
8747 if (i < methods_len) {
8748 g_ptr_array_add (frag, methods [i]);
8753 user_data = g_new0 (gpointer, 3);
8754 user_data [0] = mono_domain_get ();
8755 user_data [1] = acfg;
8756 user_data [2] = frag;
8758 handle = mono_threads_create_thread ((gpointer)compile_thread_main, user_data, 0, 0, NULL);
8759 g_ptr_array_add (threads, handle);
8763 for (i = 0; i < threads->len; ++i) {
8764 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
8770 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
8771 for (i = methods_len; i < acfg->methods->len; ++i) {
8772 /* This can new methods to acfg->methods */
8773 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
8778 compile_asm (MonoAotCompile *acfg)
8780 char *command, *objfile;
8781 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
8782 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
8783 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
8785 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
8786 #define AS_OPTIONS "--64"
8787 #elif defined(TARGET_POWERPC64)
8788 #define AS_OPTIONS "-a64 -mppc64"
8789 #define LD_OPTIONS "-m elf64ppc"
8790 #elif defined(sparc) && SIZEOF_VOID_P == 8
8791 #define AS_OPTIONS "-xarch=v9"
8792 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8793 #define AS_OPTIONS "-arch i386"
8795 #define AS_OPTIONS ""
8798 #ifdef __native_client_codegen__
8799 #if defined(TARGET_AMD64)
8800 #define AS_NAME "nacl64-as"
8802 #define AS_NAME "nacl-as"
8804 #elif defined(TARGET_OSX)
8805 #define AS_NAME "clang"
8807 #define AS_NAME "as"
8811 #define LD_OPTIONS ""
8815 #define LD_NAME "ld -shared -G"
8816 #elif defined(__ppc__) && defined(TARGET_MACH)
8817 #define LD_NAME "gcc -dynamiclib"
8818 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
8819 #define LD_NAME "clang --shared"
8820 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
8821 #define LD_NAME "gcc -shared --dll"
8822 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
8823 #define LD_NAME "clang -m32 -dynamiclib"
8826 if (acfg->aot_opts.asm_only) {
8827 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
8828 if (acfg->aot_opts.static_link)
8829 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8831 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
8835 if (acfg->aot_opts.static_link) {
8836 if (acfg->aot_opts.outfile)
8837 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8839 objfile = g_strdup_printf ("%s.o", acfg->image->name);
8841 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
8845 g_string_append (acfg->as_args, "-c -x assembler");
8848 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);
8849 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8850 if (execute_system (command) != 0) {
8856 if (acfg->llvm && !acfg->llvm_owriter) {
8857 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", acfg->llvm_ofile, acfg->llvm_sfile);
8858 aot_printf (acfg, "Executing the native assembler: %s\n", command);
8859 if (execute_system (command) != 0) {
8868 if (acfg->aot_opts.static_link) {
8869 aot_printf (acfg, "Output file: '%s'.\n", objfile);
8870 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
8875 if (acfg->aot_opts.outfile)
8876 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8878 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
8880 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8883 llvm_ofile = g_strdup (acfg->llvm_ofile);
8885 llvm_ofile = g_strdup ("");
8888 /* replace the ; flags separators with spaces */
8889 g_strdelimit (ld_flags, ";", ' ');
8892 command = g_strdup_printf ("%s -o %s %s %s.o %s", LD_NAME, tmp_outfile_name, llvm_ofile, acfg->tmpfname, ld_flags);
8894 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s.o %s", tool_prefix, LD_OPTIONS, tmp_outfile_name, llvm_ofile,
8895 acfg->tmpfname, ld_flags);
8897 aot_printf (acfg, "Executing the native linker: %s\n", command);
8898 if (execute_system (command) != 0) {
8899 g_free (tmp_outfile_name);
8900 g_free (outfile_name);
8909 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
8910 printf ("Stripping the binary: %s\n", com);
8911 execute_system (com);
8914 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8916 * gas generates 'mapping symbols' each time code and data is mixed, which
8917 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8919 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8920 aot_printf (acfg, "Stripping the binary: %s\n", command);
8921 if (execute_system (command) != 0) {
8922 g_free (tmp_outfile_name);
8923 g_free (outfile_name);
8930 rename (tmp_outfile_name, outfile_name);
8932 #if defined(TARGET_MACH)
8933 command = g_strdup_printf ("dsymutil %s", outfile_name);
8934 aot_printf (acfg, "Executing dsymutil: %s\n", command);
8935 if (execute_system (command) != 0) {
8940 if (!acfg->aot_opts.save_temps)
8943 g_free (tmp_outfile_name);
8944 g_free (outfile_name);
8947 if (acfg->aot_opts.save_temps)
8948 aot_printf (acfg, "Retained input file.\n");
8950 unlink (acfg->tmpfname);
8955 static void init_got_info (GotInfo *info)
8959 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8960 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8961 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8962 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8963 info->got_patches = g_ptr_array_new ();
8966 static MonoAotCompile*
8967 acfg_create (MonoAssembly *ass, guint32 opts)
8969 MonoImage *image = ass->image;
8970 MonoAotCompile *acfg;
8972 acfg = g_new0 (MonoAotCompile, 1);
8973 acfg->methods = g_ptr_array_new ();
8974 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8975 acfg->method_depth = g_hash_table_new (NULL, NULL);
8976 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8977 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8978 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8979 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
8980 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8981 acfg->image_hash = g_hash_table_new (NULL, NULL);
8982 acfg->image_table = g_ptr_array_new ();
8983 acfg->globals = g_ptr_array_new ();
8984 acfg->image = image;
8986 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8987 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8988 acfg->mempool = mono_mempool_new ();
8989 acfg->extra_methods = g_ptr_array_new ();
8990 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8991 acfg->unwind_ops = g_ptr_array_new ();
8992 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8993 acfg->method_order = g_ptr_array_new ();
8994 acfg->export_names = g_hash_table_new (NULL, NULL);
8995 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8996 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8997 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8998 mono_mutex_init_recursive (&acfg->mutex);
9000 init_got_info (&acfg->got_info);
9001 init_got_info (&acfg->llvm_got_info);
9007 got_info_free (GotInfo *info)
9011 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
9012 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
9013 g_free (info->patch_to_got_offset_by_type);
9014 g_hash_table_destroy (info->patch_to_got_offset);
9015 g_ptr_array_free (info->got_patches, TRUE);
9019 acfg_free (MonoAotCompile *acfg)
9023 img_writer_destroy (acfg->w);
9024 for (i = 0; i < acfg->nmethods; ++i)
9026 g_free (acfg->cfgs [i]);
9027 g_free (acfg->cfgs);
9028 g_free (acfg->static_linking_symbol);
9029 g_free (acfg->got_symbol);
9030 g_free (acfg->plt_symbol);
9031 g_ptr_array_free (acfg->methods, TRUE);
9032 g_ptr_array_free (acfg->image_table, TRUE);
9033 g_ptr_array_free (acfg->globals, TRUE);
9034 g_ptr_array_free (acfg->unwind_ops, TRUE);
9035 g_hash_table_destroy (acfg->method_indexes);
9036 g_hash_table_destroy (acfg->method_depth);
9037 g_hash_table_destroy (acfg->plt_offset_to_entry);
9038 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
9039 if (acfg->patch_to_plt_entry [i])
9040 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
9042 g_free (acfg->patch_to_plt_entry);
9043 g_hash_table_destroy (acfg->method_to_cfg);
9044 g_hash_table_destroy (acfg->token_info_hash);
9045 g_hash_table_destroy (acfg->method_to_pinvoke_import);
9046 g_hash_table_destroy (acfg->image_hash);
9047 g_hash_table_destroy (acfg->unwind_info_offsets);
9048 g_hash_table_destroy (acfg->method_label_hash);
9049 g_hash_table_destroy (acfg->export_names);
9050 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
9051 g_hash_table_destroy (acfg->klass_blob_hash);
9052 g_hash_table_destroy (acfg->method_blob_hash);
9053 got_info_free (&acfg->got_info);
9054 got_info_free (&acfg->llvm_got_info);
9055 mono_mempool_destroy (acfg->mempool);
9059 #define WRAPPER(e,n) n,
9060 static const char* const
9061 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
9062 #include "mono/metadata/wrapper-types.h"
9066 static G_GNUC_UNUSED const char*
9067 get_wrapper_type_name (int type)
9069 return wrapper_type_names [type];
9075 static void aot_dump (MonoAotCompile *acfg)
9081 json_writer_init (&writer);
9083 json_writer_object_begin(&writer);
9086 json_writer_indent (&writer);
9087 json_writer_object_key(&writer, "methods");
9088 json_writer_array_begin (&writer);
9091 for (i = 0; i < acfg->nmethods; ++i) {
9096 cfg = acfg->cfgs [i];
9100 method = cfg->orig_method;
9102 json_writer_indent (&writer);
9103 json_writer_object_begin(&writer);
9105 json_writer_indent (&writer);
9106 json_writer_object_key(&writer, "name");
9107 json_writer_printf (&writer, "\"%s\",\n", method->name);
9109 json_writer_indent (&writer);
9110 json_writer_object_key(&writer, "signature");
9111 json_writer_printf (&writer, "\"%s\",\n", mono_method_full_name (method,
9112 /*signature=*/TRUE));
9114 json_writer_indent (&writer);
9115 json_writer_object_key(&writer, "code_size");
9116 json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
9118 klass = method->klass;
9120 json_writer_indent (&writer);
9121 json_writer_object_key(&writer, "class");
9122 json_writer_printf (&writer, "\"%s\",\n", klass->name);
9124 json_writer_indent (&writer);
9125 json_writer_object_key(&writer, "namespace");
9126 json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
9128 json_writer_indent (&writer);
9129 json_writer_object_key(&writer, "wrapper_type");
9130 json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
9132 json_writer_indent_pop (&writer);
9133 json_writer_indent (&writer);
9134 json_writer_object_end (&writer);
9135 json_writer_printf (&writer, ",\n");
9138 json_writer_indent_pop (&writer);
9139 json_writer_indent (&writer);
9140 json_writer_array_end (&writer);
9141 json_writer_printf (&writer, ",\n");
9145 json_writer_indent_push (&writer);
9146 json_writer_indent (&writer);
9147 json_writer_object_key(&writer, "plt");
9148 json_writer_array_begin (&writer);
9150 for (i = 0; i < acfg->plt_offset; ++i) {
9151 MonoPltEntry *plt_entry = NULL;
9156 * The first plt entry is unused.
9160 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9163 json_writer_indent (&writer);
9164 json_writer_printf (&writer, "{ ");
9165 json_writer_object_key(&writer, "symbol");
9166 json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
9169 json_writer_indent_pop (&writer);
9170 json_writer_indent (&writer);
9171 json_writer_array_end (&writer);
9172 json_writer_printf (&writer, ",\n");
9177 json_writer_indent_push (&writer);
9178 json_writer_indent (&writer);
9179 json_writer_object_key(&writer, "got");
9180 json_writer_array_begin (&writer);
9182 json_writer_indent_push (&writer);
9183 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
9184 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
9186 json_writer_indent (&writer);
9187 json_writer_printf (&writer, "{ ");
9188 json_writer_object_key(&writer, "patch_name");
9189 json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
9192 json_writer_indent_pop (&writer);
9193 json_writer_indent (&writer);
9194 json_writer_array_end (&writer);
9195 json_writer_printf (&writer, ",\n");
9198 json_writer_indent_pop (&writer);
9199 json_writer_indent (&writer);
9200 json_writer_object_end (&writer);
9202 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
9203 dumpfile = fopen (dumpname, "w+");
9206 fprintf (dumpfile, "%s", writer.text->str);
9209 json_writer_destroy (&writer);
9213 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
9215 MonoImage *image = ass->image;
9218 MonoAotCompile *acfg;
9219 char *outfile_name, *tmp_outfile_name, *p;
9220 char llvm_stats_msg [256];
9224 acfg = acfg_create (ass, opts);
9226 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
9227 acfg->aot_opts.write_symbols = TRUE;
9228 acfg->aot_opts.ntrampolines = 1024;
9229 acfg->aot_opts.nrgctx_trampolines = 1024;
9230 acfg->aot_opts.nimt_trampolines = 128;
9231 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
9232 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
9233 acfg->aot_opts.llvm_path = g_strdup ("");
9235 acfg->aot_opts.use_trampolines_page = TRUE;
9238 mono_aot_parse_options (aot_options, &acfg->aot_opts);
9240 if (acfg->aot_opts.logfile) {
9241 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
9244 if (acfg->aot_opts.static_link)
9245 acfg->aot_opts.autoreg = TRUE;
9247 //acfg->aot_opts.print_skipped_methods = TRUE;
9249 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED) || !defined(ENABLE_GSHAREDVT)
9250 if (opts & MONO_OPT_GSHAREDVT) {
9251 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
9256 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
9258 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
9259 if (acfg->aot_opts.full_aot) {
9260 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
9265 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
9266 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
9270 if (acfg->aot_opts.static_link)
9271 acfg->aot_opts.asm_writer = TRUE;
9273 if (acfg->aot_opts.soft_debug) {
9274 MonoDebugOptions *opt = mini_get_debug_options ();
9276 opt->mdb_optimizations = TRUE;
9277 opt->gen_sdb_seq_points = TRUE;
9279 if (!mono_debug_enabled ()) {
9280 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
9283 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
9286 if (mono_use_llvm || acfg->aot_opts.llvm) {
9288 acfg->aot_opts.asm_writer = TRUE;
9289 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
9291 if (acfg->aot_opts.soft_debug) {
9292 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
9298 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
9299 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
9304 * Emit all LLVM code into a separate assembly/object file and link with it
9307 if (!acfg->aot_opts.asm_only)
9308 acfg->llvm_owriter = TRUE;
9311 if (acfg->aot_opts.full_aot)
9312 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
9314 if (acfg->aot_opts.instances_logfile_path) {
9315 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
9316 if (!acfg->instances_logfile) {
9317 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
9322 load_profile_files (acfg);
9324 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
9325 #ifdef MONO_ARCH_GSHARED_SUPPORTED
9326 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
9328 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
9329 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
9330 if (acfg->opts & MONO_OPT_GSHAREDVT)
9331 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
9334 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
9338 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
9339 /* Get rid of characters which cannot occur in symbols */
9340 for (p = acfg->assembly_name_sym; *p; ++p) {
9341 if (!(isalnum (*p) || *p == '_'))
9345 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->assembly_name_sym);
9346 acfg->llvm_got_symbol_base = g_strdup_printf ("mono_aot_%s_llvm_got", acfg->assembly_name_sym);
9347 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->assembly_name_sym);
9349 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
9351 acfg->llvm_got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->llvm_got_symbol_base);
9352 acfg->llvm_eh_frame_symbol = g_strdup_printf ("mono_aot_%s_eh_frame", acfg->assembly_name_sym);
9355 acfg->method_index = 1;
9357 if (acfg->aot_opts.full_aot)
9358 mono_set_partial_sharing_supported (TRUE);
9360 res = collect_methods (acfg);
9364 acfg->cfgs_size = acfg->methods->len + 32;
9365 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
9367 /* PLT offset 0 is reserved for the PLT trampoline */
9368 acfg->plt_offset = 1;
9373 mono_llvm_create_aot_module (acfg->llvm_got_symbol_base, TRUE, TRUE);
9377 /* GOT offset 0 is reserved for the address of the current assembly */
9381 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9382 ji->type = MONO_PATCH_INFO_IMAGE;
9383 ji->data.image = acfg->image;
9385 get_got_offset (acfg, FALSE, ji);
9386 get_got_offset (acfg, TRUE, ji);
9388 /* Slot 1 is reserved for the mscorlib got addr */
9389 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9390 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
9391 get_got_offset (acfg, FALSE, ji);
9392 get_got_offset (acfg, TRUE, ji);
9394 /* This is very common */
9395 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9396 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
9397 get_got_offset (acfg, FALSE, ji);
9398 get_got_offset (acfg, TRUE, ji);
9400 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9401 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
9402 get_got_offset (acfg, FALSE, ji);
9403 get_got_offset (acfg, TRUE, ji);
9405 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
9406 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
9407 get_got_offset (acfg, FALSE, ji);
9408 get_got_offset (acfg, TRUE, ji);
9413 compile_methods (acfg);
9417 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
9425 if (acfg->aot_opts.asm_only) {
9426 if (acfg->aot_opts.outfile) {
9427 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9428 acfg->tmpbasename = g_strdup (acfg->tmpfname);
9430 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
9431 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9433 g_assert (acfg->aot_opts.llvm_outfile);
9434 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
9436 acfg->tmpbasename = g_strdup_printf ("%s", "temp");
9437 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
9438 acfg->llvm_sfile = g_strdup ("temp-llvm.s");
9439 acfg->llvm_ofile = g_strdup ("temp-llvm.o");
9442 res = emit_llvm_file (acfg);
9448 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
9449 if (acfg->aot_opts.outfile)
9450 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9452 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9455 * Can't use g_file_open_tmp () as it will be deleted at exit, and
9456 * it might be in another file system so the rename () won't work.
9458 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9460 acfg->fp = fopen (tmp_outfile_name, "w");
9462 aot_printf (acfg, "Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
9466 acfg->w = img_writer_create (acfg->fp, TRUE);
9467 acfg->use_bin_writer = TRUE;
9469 if (acfg->aot_opts.asm_only) {
9470 if (acfg->aot_opts.outfile)
9471 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9473 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
9474 acfg->fp = fopen (acfg->tmpfname, "w+");
9476 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
9477 acfg->fp = fdopen (i, "w+");
9479 if (acfg->fp == 0) {
9480 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
9483 acfg->w = img_writer_create (acfg->fp, FALSE);
9485 tmp_outfile_name = NULL;
9486 outfile_name = NULL;
9489 /* Compute symbols for methods */
9490 for (i = 0; i < acfg->nmethods; ++i) {
9491 if (acfg->cfgs [i]) {
9492 MonoCompile *cfg = acfg->cfgs [i];
9493 int method_index = get_method_index (acfg, cfg->orig_method);
9495 if (COMPILE_LLVM (cfg))
9496 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
9497 else if (acfg->global_symbols || acfg->llvm)
9498 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
9500 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
9501 cfg->asm_debug_symbol = cfg->asm_symbol;
9505 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.asm_only && acfg->aot_opts.gnu_asm) {
9507 * CLANG supports GAS .file/.loc directives, so emit line number information this way
9508 * FIXME: CLANG only emits line number info for .loc directives followed by assembly, not
9511 //acfg->gas_line_numbers = TRUE;
9514 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
9515 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
9516 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
9519 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE, !acfg->gas_line_numbers);
9522 img_writer_emit_start (acfg->w);
9525 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
9527 if (acfg->thumb_mixed) {
9530 * This global symbol marks the end of THUMB code, and the beginning of ARM
9531 * code generated by our JIT.
9533 sprintf (symbol, "thumb_end");
9534 emit_section_change (acfg, ".text", 0);
9535 emit_alignment_code (acfg, 8);
9536 emit_label (acfg, symbol);
9537 emit_zero_bytes (acfg, 16);
9539 fprintf (acfg->fp, ".arm\n");
9546 emit_extra_methods (acfg);
9548 emit_trampolines (acfg);
9550 emit_class_name_table (acfg);
9552 emit_got_info (acfg, FALSE);
9554 emit_got_info (acfg, TRUE);
9556 emit_exception_info (acfg);
9558 emit_unwind_info (acfg);
9560 emit_class_info (acfg);
9564 emit_image_table (acfg);
9568 emit_file_info (acfg);
9572 emit_objc_selectors (acfg);
9574 emit_globals (acfg);
9576 emit_autoreg (acfg);
9579 emit_dwarf_info (acfg);
9580 mono_dwarf_writer_close (acfg->dwarf);
9583 emit_mem_end (acfg);
9585 if (acfg->need_pt_gnu_stack) {
9586 /* This is required so the .so doesn't have an executable stack */
9587 /* The bin writer already emits this */
9588 if (!acfg->use_bin_writer)
9589 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
9594 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
9597 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
9599 strcpy (llvm_stats_msg, "");
9601 all_sizes = acfg->stats.code_size + acfg->stats.info_size + acfg->stats.ex_info_size + acfg->stats.unwind_info_size + acfg->stats.class_info_size + acfg->stats.got_info_size + acfg->stats.offsets_size + acfg->stats.plt_size;
9603 aot_printf (acfg, "Code: %d(%d%%) Info: %d(%d%%) Ex Info: %d(%d%%) Unwind Info: %d(%d%%) Class Info: %d(%d%%) PLT: %d(%d%%) GOT Info: %d(%d%%) Offsets: %d(%d%%) GOT: %d\n",
9604 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
9605 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
9606 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
9607 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
9608 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
9609 acfg->stats.plt_size ? (int)acfg->stats.plt_size : (int)acfg->plt_offset, acfg->stats.plt_size ? (int)(acfg->stats.plt_size * 100 / all_sizes) : 0,
9610 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
9611 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
9612 (int)(acfg->got_offset * sizeof (gpointer)));
9613 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
9614 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
9616 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
9617 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
9618 if (acfg->stats.genericcount)
9619 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
9620 if (acfg->stats.abscount)
9621 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
9622 if (acfg->stats.lmfcount)
9623 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
9624 if (acfg->stats.ocount)
9625 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
9628 res = img_writer_emit_writeout (acfg->w);
9633 if (acfg->use_bin_writer) {
9634 int err = rename (tmp_outfile_name, outfile_name);
9637 aot_printf (acfg, "Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
9641 res = compile_asm (acfg);
9648 acfg->stats.link_time = TV_ELAPSED (atv, btv);
9650 if (acfg->aot_opts.stats) {
9653 aot_printf (acfg, "GOT slot distribution:\n");
9654 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
9655 if (acfg->stats.got_slot_types [i])
9656 aot_printf (acfg, "\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
9659 aot_printf (acfg, "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);
9661 if (acfg->aot_opts.dump_json)
9674 mono_aot_readonly_field_override (MonoClassField *field)
9680 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)