2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
7 * Johan Lorensson (lateralusx.github@gmail.com)
9 * (C) 2002 Ximian, Inc.
10 * Copyright 2003-2011 Novell, Inc
11 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <sys/types.h>
36 #include <mono/metadata/abi-details.h>
37 #include <mono/metadata/tabledefs.h>
38 #include <mono/metadata/class.h>
39 #include <mono/metadata/object.h>
40 #include <mono/metadata/tokentype.h>
41 #include <mono/metadata/appdomain.h>
42 #include <mono/metadata/debug-helpers.h>
43 #include <mono/metadata/assembly.h>
44 #include <mono/metadata/metadata-internals.h>
45 #include <mono/metadata/reflection-internals.h>
46 #include <mono/metadata/marshal.h>
47 #include <mono/metadata/gc-internals.h>
48 #include <mono/metadata/mempool-internals.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/threads-types.h>
51 #include <mono/utils/mono-logger-internals.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-time.h>
54 #include <mono/utils/mono-mmap.h>
55 #include <mono/utils/mono-rand.h>
56 #include <mono/utils/json.h>
57 #include <mono/utils/mono-threads-coop.h>
58 #include <mono/profiler/mono-profiler-aot.h>
59 #include <mono/io-layer/io-layer.h>
61 #include "aot-compiler.h"
62 #include "seq-points.h"
63 #include "image-writer.h"
64 #include "dwarfwriter.h"
66 #include "mini-llvm.h"
68 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
71 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
72 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
73 #define TARGET_X86_64_WIN32_MSVC
76 #if defined(TARGET_X86_64_WIN32_MSVC)
77 #define TARGET_WIN32_MSVC
80 #if defined(__linux__) || defined(__native_client_codegen__)
81 #define RODATA_SECT ".rodata"
82 #elif defined(TARGET_MACH)
83 #define RODATA_SECT ".section __TEXT, __const"
84 #elif defined(TARGET_WIN32_MSVC)
85 #define RODATA_SECT ".rdata"
87 #define RODATA_SECT ".text"
90 #define TV_DECLARE(name) gint64 name
91 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
92 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
94 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
95 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
96 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
103 typedef struct ClassProfileData ClassProfileData;
107 ClassProfileData **argv;
108 MonoGenericInst *inst;
111 struct ClassProfileData {
112 ImageProfileData *image;
114 GInstProfileData *inst;
119 ClassProfileData *klass;
124 GInstProfileData *inst;
129 GHashTable *images, *classes, *ginsts, *methods;
132 /* predefined values for static readonly fields without needed to run the .cctor */
133 typedef struct _ReadOnlyValue ReadOnlyValue;
134 struct _ReadOnlyValue {
137 int type; /* to be used later for typechecking to prevent user errors */
146 static ReadOnlyValue *readonly_values;
148 typedef struct MonoAotOptions {
152 GList *profile_files;
154 gboolean write_symbols;
155 gboolean metadata_only;
156 gboolean bind_to_runtime_version;
159 gboolean static_link;
163 gboolean dwarf_debug;
165 gboolean log_generics;
166 gboolean log_instances;
167 gboolean gen_msym_dir;
168 char *gen_msym_dir_path;
169 gboolean direct_pinvoke;
170 gboolean direct_icalls;
171 gboolean no_direct_calls;
172 gboolean use_trampolines_page;
173 gboolean no_instances;
179 int nrgctx_trampolines;
180 int nimt_trampolines;
181 int ngsharedvt_arg_trampolines;
182 int nrgctx_fetch_trampolines;
183 gboolean print_skipped_methods;
190 char *instances_logfile_path;
197 METHOD_CAT_GSHAREDVT,
203 typedef struct MonoAotStats {
204 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
205 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
206 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
207 int got_slots, offsets_size;
208 int method_categories [METHOD_CAT_NUM];
209 int got_slot_types [MONO_PATCH_INFO_NUM];
210 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
211 int jit_time, gen_time, link_time;
214 typedef struct GotInfo {
215 GHashTable *patch_to_got_offset;
216 GHashTable **patch_to_got_offset_by_type;
217 GPtrArray *got_patches;
220 typedef struct MonoAotCompile {
223 GHashTable *method_indexes;
224 GHashTable *method_depth;
227 GHashTable **patch_to_plt_entry;
228 GHashTable *plt_offset_to_entry;
229 //GHashTable *patch_to_got_offset;
230 //GHashTable **patch_to_got_offset_by_type;
231 //GPtrArray *got_patches;
232 GotInfo got_info, llvm_got_info;
233 GHashTable *image_hash;
234 GHashTable *method_to_cfg;
235 GHashTable *token_info_hash;
236 GHashTable *method_to_pinvoke_import;
237 GPtrArray *extra_methods;
238 GPtrArray *image_table;
240 GPtrArray *method_order;
241 GHashTable *export_names;
242 /* Maps MonoClass* -> blob offset */
243 GHashTable *klass_blob_hash;
244 /* Maps MonoMethod* -> blob offset */
245 GHashTable *method_blob_hash;
246 GHashTable *gsharedvt_in_signatures;
247 GHashTable *gsharedvt_out_signatures;
248 guint32 *plt_got_info_offsets;
249 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
250 /* Number of GOT entries reserved for trampolines */
251 guint32 num_trampoline_got_entries;
252 guint32 tramp_page_size;
254 guint32 table_offsets [MONO_AOT_TABLE_NUM];
255 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
256 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
257 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
258 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
260 MonoAotOptions aot_opts;
264 MonoMemPool *mempool;
267 char *static_linking_symbol;
269 gboolean gas_line_numbers;
270 /* Whenever to emit an object file directly from llc */
271 gboolean llvm_owriter;
272 gboolean llvm_owriter_supported;
274 MonoDwarfWriter *dwarf;
281 GHashTable *unwind_info_offsets;
282 GPtrArray *unwind_ops;
283 guint32 unwind_info_offset;
286 char *llvm_got_symbol;
288 char *llvm_eh_frame_symbol;
289 GHashTable *method_label_hash;
290 const char *temp_prefix;
291 const char *user_symbol_prefix;
292 const char *llvm_label_prefix;
293 const char *inst_directive;
295 guint32 label_generator;
297 gboolean has_jitted_code;
298 MonoAotFileFlags flags;
299 MonoDynamicStream blob;
300 gboolean blob_closed;
301 GHashTable *typespec_classes;
304 char *assembly_name_sym;
305 GHashTable *plt_entry_debug_sym_cache;
306 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
307 GHashTable *ginst_hash;
308 GHashTable *dwarf_ln_filenames;
309 gboolean global_symbols;
310 int objc_selector_index, objc_selector_index_2;
311 GPtrArray *objc_selectors;
312 GHashTable *objc_selector_to_index;
315 FILE *instances_logfile;
323 char *symbol, *llvm_symbol, *debug_sym;
325 gboolean jit_used, llvm_used;
328 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
329 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
331 /* This points to the current acfg in LLVM mode */
332 static MonoAotCompile *llvm_acfg;
334 #ifdef HAVE_ARRAY_ELEM_INIT
335 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
336 #define MSGSTRFIELD1(line) str##line
337 static const struct msgstr_t {
338 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
339 #include "patch-info.h"
342 #define PATCH_INFO(a,b) b,
343 #include "patch-info.h"
346 static const gint16 opidx [] = {
347 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
348 #include "patch-info.h"
352 static G_GNUC_UNUSED const char*
353 get_patch_name (int info)
355 return (const char*)&opstr + opidx [info];
359 #define PATCH_INFO(a,b) b,
360 static const char* const
361 patch_types [MONO_PATCH_INFO_NUM + 1] = {
362 #include "patch-info.h"
366 static G_GNUC_UNUSED const char*
367 get_patch_name (int info)
369 return patch_types [info];
375 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
378 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
381 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
384 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
387 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
393 output = acfg->logfile;
397 va_start (args, format);
398 vfprintf (output, format, args);
403 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
409 output = acfg->logfile;
413 va_start (args, format);
414 vfprintf (output, format, args);
419 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
424 if (mono_error_ok (error))
428 output = acfg->logfile;
432 va_start (args, format);
433 vfprintf (output, format, args);
435 mono_error_cleanup (error);
437 g_error ("FullAOT cannot continue if there are loader errors");
440 /* Wrappers around the image writer functions */
442 #define MAX_SYMBOL_SIZE 256
444 static inline const char *
445 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
447 gsize needed_size = length;
449 g_assert (NULL != symbol);
450 g_assert (NULL != mangled_symbol);
451 g_assert (0 != length);
453 #if defined(TARGET_WIN32) && defined(TARGET_X86)
454 if (symbol && '_' != symbol [0]) {
455 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
457 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
460 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
463 g_assert (0 <= needed_size && needed_size < length);
464 return mangled_symbol;
468 mangle_symbol_alloc (const char * symbol)
470 g_assert (NULL != symbol);
472 #if defined(TARGET_WIN32) && defined(TARGET_X86)
473 if (symbol && '_' != symbol [0]) {
474 return g_strdup_printf ("_%s", symbol);
477 return g_strdup_printf ("%s", symbol);
480 return g_strdup_printf ("%s", symbol);
485 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
487 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
490 #if defined(TARGET_WIN32) && defined(TARGET_X86)
493 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
495 const char * mangled_symbol_name = name;
496 char * mangled_symbol_name_alloc = NULL;
499 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
500 mangled_symbol_name = mangled_symbol_name_alloc;
503 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
504 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
506 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
508 if (NULL != mangled_symbol_name_alloc) {
509 g_free (mangled_symbol_name_alloc);
516 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
518 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
524 emit_label (MonoAotCompile *acfg, const char *name)
526 mono_img_writer_emit_label (acfg->w, name);
530 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
532 mono_img_writer_emit_bytes (acfg->w, buf, size);
536 emit_string (MonoAotCompile *acfg, const char *value)
538 mono_img_writer_emit_string (acfg->w, value);
542 emit_line (MonoAotCompile *acfg)
544 mono_img_writer_emit_line (acfg->w);
548 emit_alignment (MonoAotCompile *acfg, int size)
550 mono_img_writer_emit_alignment (acfg->w, size);
554 emit_alignment_code (MonoAotCompile *acfg, int size)
556 if (acfg->align_pad_value)
557 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
559 mono_img_writer_emit_alignment (acfg->w, size);
563 emit_padding (MonoAotCompile *acfg, int size)
568 if (acfg->align_pad_value) {
569 for (i = 0; i < 16; ++i)
570 buf [i] = acfg->align_pad_value;
572 memset (buf, 0, sizeof (buf));
575 for (i = 0; i < size; i += 16) {
577 emit_bytes (acfg, buf, size - i);
579 emit_bytes (acfg, buf, 16);
584 emit_pointer (MonoAotCompile *acfg, const char *target)
586 mono_img_writer_emit_pointer (acfg->w, target);
590 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
592 if (prefix [0] != '\0') {
593 char *s = g_strdup_printf ("%s%s", prefix, target);
594 mono_img_writer_emit_pointer (acfg->w, s);
597 mono_img_writer_emit_pointer (acfg->w, target);
602 emit_int16 (MonoAotCompile *acfg, int value)
604 mono_img_writer_emit_int16 (acfg->w, value);
608 emit_int32 (MonoAotCompile *acfg, int value)
610 mono_img_writer_emit_int32 (acfg->w, value);
614 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
616 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
620 emit_zero_bytes (MonoAotCompile *acfg, int num)
622 mono_img_writer_emit_zero_bytes (acfg->w, num);
626 emit_byte (MonoAotCompile *acfg, guint8 val)
628 mono_img_writer_emit_byte (acfg->w, val);
631 #if defined(TARGET_WIN32) && defined(TARGET_X86)
633 static G_GNUC_UNUSED void
634 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
636 const char * mangled_symbol_name = name;
637 char * mangled_symbol_name_alloc = NULL;
639 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
640 mangled_symbol_name = mangled_symbol_name_alloc;
642 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
643 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
645 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
647 if (NULL != mangled_symbol_name_alloc) {
648 g_free (mangled_symbol_name_alloc);
654 static G_GNUC_UNUSED void
655 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
657 mono_img_writer_emit_global (acfg->w, name, func);
662 static inline gboolean
663 link_shared_library (MonoAotCompile *acfg)
665 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
668 static inline gboolean
669 add_to_global_symbol_table (MonoAotCompile *acfg)
671 #ifdef TARGET_WIN32_MSVC
672 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
674 return acfg->aot_opts.no_dlsym;
679 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
681 if (add_to_global_symbol_table (acfg))
682 g_ptr_array_add (acfg->globals, g_strdup (name));
684 if (acfg->aot_opts.no_dlsym) {
685 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
687 emit_global_inner (acfg, name, func);
692 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
694 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
697 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
699 emit_info_symbol (MonoAotCompile *acfg, const char *name)
701 char symbol [MAX_SYMBOL_SIZE];
704 emit_label (acfg, name);
705 /* LLVM generated code references this */
706 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
707 emit_label (acfg, symbol);
708 emit_global_inner (acfg, symbol, FALSE);
710 emit_label (acfg, name);
715 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
718 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
722 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
724 /* On apple, all symbols need to be aligned to avoid warnings from ld */
725 emit_alignment (acfg, 4);
727 mono_img_writer_emit_label (acfg->w, name);
728 mono_img_writer_emit_string (acfg->w, value);
731 static G_GNUC_UNUSED void
732 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
735 guint8 b = value & 0x7f;
737 if (value != 0) /* more bytes to come */
743 static G_GNUC_UNUSED void
744 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
747 gboolean negative = (value < 0);
754 /* the following is unnecessary if the
755 * implementation of >>= uses an arithmetic rather
756 * than logical shift for a signed left operand
760 value |= - ((gint64)1 <<(size - 7));
761 /* sign bit of byte is second high order bit (0x40) */
762 if ((value == 0 && !(byte & 0x40)) ||
763 (value == -1 && (byte & 0x40)))
767 emit_byte (acfg, byte);
771 static G_GNUC_UNUSED void
772 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
777 guint8 b = value & 0x7f;
779 if (value != 0) /* more bytes to come */
787 static G_GNUC_UNUSED void
788 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
791 gboolean negative = (value < 0);
799 /* the following is unnecessary if the
800 * implementation of >>= uses an arithmetic rather
801 * than logical shift for a signed left operand
805 value |= - (1 <<(size - 7));
806 /* sign bit of byte is second high order bit (0x40) */
807 if ((value == 0 && !(byte & 0x40)) ||
808 (value == -1 && (byte & 0x40)))
819 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
822 buf [0] = (val >> 0) & 0xff;
823 buf [1] = (val >> 8) & 0xff;
824 buf [2] = (val >> 16) & 0xff;
825 buf [3] = (val >> 24) & 0xff;
831 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
833 buf [0] = (val >> 0) & 0xff;
834 buf [1] = (val >> 8) & 0xff;
840 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
842 int len = strlen (s);
844 memcpy (buf, s, len + 1);
845 *endbuf = buf + len + 1;
849 emit_unset_mode (MonoAotCompile *acfg)
851 mono_img_writer_emit_unset_mode (acfg->w);
854 static G_GNUC_UNUSED void
855 emit_set_thumb_mode (MonoAotCompile *acfg)
857 emit_unset_mode (acfg);
858 fprintf (acfg->fp, ".code 16\n");
861 static G_GNUC_UNUSED void
862 emit_set_arm_mode (MonoAotCompile *acfg)
864 emit_unset_mode (acfg);
865 fprintf (acfg->fp, ".code 32\n");
869 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
874 g_assert (size % 4 == 0);
875 emit_unset_mode (acfg);
876 for (i = 0; i < size; i += 4)
877 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
879 emit_bytes (acfg, buf, size);
883 /* ARCHITECTURE SPECIFIC CODE */
885 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
886 #define EMIT_DWARF_INFO 1
889 #ifdef TARGET_WIN32_MSVC
890 #undef EMIT_DWARF_INFO
893 #if defined(TARGET_ARM)
894 #define AOT_FUNC_ALIGNMENT 4
896 #define AOT_FUNC_ALIGNMENT 16
899 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
900 #define PPC_LD_OP "ld"
901 #define PPC_LDX_OP "ldx"
903 #define PPC_LD_OP "lwz"
904 #define PPC_LDX_OP "lwzx"
907 #ifdef TARGET_X86_64_WIN32_MSVC
908 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
910 #define AOT_TARGET_STR "AMD64"
915 #define AOT_TARGET_STR "ARM (MACH)"
917 #define AOT_TARGET_STR "ARM (!MACH)"
923 #define AOT_TARGET_STR "ARM64 (MACH)"
925 #define AOT_TARGET_STR "ARM64 (!MACH)"
929 #ifdef TARGET_POWERPC64
930 #ifdef __mono_ilp32__
931 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
933 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
936 #ifdef TARGET_POWERPC
937 #ifdef __mono_ilp32__
938 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
940 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
947 #define AOT_TARGET_STR "X86 (WIN32)"
948 #elif defined(__native_client_codegen__)
949 #define AOT_TARGET_STR "X86 (native client codegen)"
951 #define AOT_TARGET_STR "X86 (!native client codegen)"
955 #ifndef AOT_TARGET_STR
956 #define AOT_TARGET_STR ""
960 arch_init (MonoAotCompile *acfg)
962 acfg->llc_args = g_string_new ("");
963 acfg->as_args = g_string_new ("");
964 acfg->llvm_owriter_supported = TRUE;
967 * The prefix LLVM likes to put in front of symbol names on darwin.
968 * The mach-os specs require this for globals, but LLVM puts them in front of all
969 * symbols. We need to handle this, since we need to refer to LLVM generated
972 acfg->llvm_label_prefix = "";
973 acfg->user_symbol_prefix = "";
975 #if defined(TARGET_X86)
976 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
979 #if defined(TARGET_AMD64)
980 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
982 acfg->align_pad_value = 0x90;
986 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
987 g_string_append (acfg->llc_args, "-mattr=+v6");
989 #if defined(ARM_FPU_VFP_HARD)
990 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
991 g_string_append (acfg->as_args, " -mfpu=vfp3");
992 #elif defined(ARM_FPU_VFP)
993 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
994 g_string_append (acfg->as_args, " -mfpu=vfp3");
996 g_string_append (acfg->llc_args, " -soft-float");
999 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1000 acfg->thumb_mixed = TRUE;
1002 if (acfg->aot_opts.mtriple)
1003 mono_arch_set_target (acfg->aot_opts.mtriple);
1007 acfg->inst_directive = ".inst";
1008 if (acfg->aot_opts.mtriple)
1009 mono_arch_set_target (acfg->aot_opts.mtriple);
1013 acfg->user_symbol_prefix = "_";
1014 acfg->llvm_label_prefix = "_";
1015 acfg->inst_directive = ".word";
1016 acfg->need_no_dead_strip = TRUE;
1017 acfg->aot_opts.gnu_asm = TRUE;
1020 #if defined(__linux__) && !defined(TARGET_ARM)
1021 acfg->need_pt_gnu_stack = TRUE;
1025 acfg->global_symbols = TRUE;
1028 #ifdef TARGET_ANDROID
1029 acfg->llvm_owriter_supported = FALSE;
1036 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1038 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1042 g_assert (acfg->fp);
1043 emit_unset_mode (acfg);
1045 offset = (int)(got_slot * sizeof (gpointer));
1047 /* clang's integrated assembler */
1048 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1049 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1050 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1053 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1054 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1055 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1060 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1064 g_assert (acfg->fp);
1065 emit_unset_mode (acfg);
1067 /* ldr rt, target */
1068 reg = arm_get_ldr_lit_reg (code);
1070 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1071 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1072 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1078 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1080 g_assert (acfg->fp);
1081 emit_unset_mode (acfg);
1082 if (ji && ji->relocation == MONO_R_ARM64_B) {
1083 fprintf (acfg->fp, "b %s\n", target);
1086 g_assert (ji->relocation == MONO_R_ARM64_BL);
1087 fprintf (acfg->fp, "bl %s\n", target);
1093 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1097 /* ldr rt, target */
1098 reg = arm_get_ldr_lit_reg (code);
1099 arm64_emit_load_got_slot (acfg, reg, got_slot);
1104 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1106 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1107 fprintf (acfg->fp, "br x16\n");
1108 /* Used by mono_aot_get_plt_info_offset () */
1109 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1113 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1119 /* The common code */
1122 /* The trampoline address is in IP0 */
1123 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1124 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1125 /* Compute the data slot address */
1126 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1127 /* Trampoline argument */
1128 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1130 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1131 arm_brx (code, ARMREG_IP0);
1134 emit_code_bytes (acfg, buf, code - buf);
1140 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1146 count = (pagesize - common_tramp_size) / specific_tramp_size;
1147 for (i = 0; i < count; ++i) {
1149 arm_adrx (code, ARMREG_IP0, code);
1150 /* Branch to the generic code */
1151 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1152 /* This has to be 2 pointers long */
1155 g_assert (code - buf == specific_tramp_size);
1156 emit_code_bytes (acfg, buf, code - buf);
1161 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1165 guint8 *labels [16];
1166 int common_tramp_size;
1167 int specific_tramp_size = 2 * 8;
1171 if (!acfg->aot_opts.use_trampolines_page)
1175 /* Have to match the target pagesize */
1178 pagesize = mono_pagesize ();
1180 acfg->tramp_page_size = pagesize;
1182 /* The specific trampolines */
1183 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1184 emit_alignment (acfg, pagesize);
1185 emit_global (acfg, symbol, TRUE);
1186 emit_label (acfg, symbol);
1188 /* The common code */
1189 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1190 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1192 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1194 /* The rgctx trampolines */
1195 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1196 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1197 emit_alignment (acfg, pagesize);
1198 emit_global (acfg, symbol, TRUE);
1199 emit_label (acfg, symbol);
1201 /* The common code */
1202 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1203 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1205 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1207 /* The gsharedvt arg trampolines */
1208 /* These are the same as the specific trampolines */
1209 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1210 emit_alignment (acfg, pagesize);
1211 emit_global (acfg, symbol, TRUE);
1212 emit_label (acfg, symbol);
1214 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1215 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1217 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1219 /* The IMT trampolines */
1220 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1221 emit_alignment (acfg, pagesize);
1222 emit_global (acfg, symbol, TRUE);
1223 emit_label (acfg, symbol);
1227 /* The trampoline address is in IP0 */
1228 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1229 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1230 /* Compute the data slot address */
1231 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1232 /* Trampoline argument */
1233 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1235 /* Same as arch_emit_imt_trampoline () */
1237 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1238 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1240 arm_bcc (code, ARMCOND_EQ, 0);
1242 /* End-of-loop check */
1244 arm_cbzx (code, ARMREG_IP0, 0);
1247 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1248 arm_b (code, labels [0]);
1251 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1252 /* Load vtable slot addr */
1253 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1254 /* Load vtable slot */
1255 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1256 arm_brx (code, ARMREG_IP0);
1259 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1260 /* Load fail addr */
1261 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1262 arm_brx (code, ARMREG_IP0);
1264 emit_code_bytes (acfg, buf, code - buf);
1266 common_tramp_size = code - buf;
1267 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1269 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1273 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1275 /* Load argument from second GOT slot */
1276 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1277 /* Load generic trampoline address from first GOT slot */
1278 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1279 fprintf (acfg->fp, "br x16\n");
1280 *tramp_size = 7 * 4;
1284 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1286 emit_unset_mode (acfg);
1287 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1288 fprintf (acfg->fp, "b %s\n", call_target);
1292 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1294 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1296 /* Load argument from first GOT slot */
1297 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1298 /* Load generic trampoline address from second GOT slot */
1299 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1300 fprintf (acfg->fp, "br x16\n");
1301 *tramp_size = 7 * 4;
1305 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1308 guint8 *code, *labels [16];
1310 /* Load parameter from GOT slot into ip1 */
1311 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1315 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1316 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1318 arm_bcc (code, ARMCOND_EQ, 0);
1320 /* End-of-loop check */
1322 arm_cbzx (code, ARMREG_IP0, 0);
1325 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1326 arm_b (code, labels [0]);
1329 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1330 /* Load vtable slot addr */
1331 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1332 /* Load vtable slot */
1333 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1334 arm_brx (code, ARMREG_IP0);
1337 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1338 /* Load fail addr */
1339 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1340 arm_brx (code, ARMREG_IP0);
1342 emit_code_bytes (acfg, buf, code - buf);
1344 *tramp_size = code - buf + (3 * 4);
1348 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1350 /* Similar to the specific trampolines, but the address is in the second slot */
1351 /* Load argument from first GOT slot */
1352 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1353 /* Load generic trampoline address from second GOT slot */
1354 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1355 fprintf (acfg->fp, "br x16\n");
1356 *tramp_size = 7 * 4;
1362 #ifdef MONO_ARCH_AOT_SUPPORTED
1364 * arch_emit_direct_call:
1366 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1370 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1372 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1373 /* Need to make sure this is exactly 5 bytes long */
1374 emit_unset_mode (acfg);
1375 fprintf (acfg->fp, "call %s\n", target);
1377 #elif defined(TARGET_ARM)
1378 emit_unset_mode (acfg);
1380 fprintf (acfg->fp, "blx %s\n", target);
1382 fprintf (acfg->fp, "bl %s\n", target);
1384 #elif defined(TARGET_ARM64)
1385 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1386 #elif defined(TARGET_POWERPC)
1387 emit_unset_mode (acfg);
1388 fprintf (acfg->fp, "bl %s\n", target);
1391 g_assert_not_reached ();
1398 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1400 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1401 * in in the 2. slot of every GOT, and require every method to place the GOT
1402 * address in r30, even when it doesn't access the GOT otherwise. This way,
1403 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1408 * PPC64 uses function descriptors which greatly complicate all code, since
1409 * these are used very inconsistently in the runtime. Some functions like
1410 * mono_compile_method () return ftn descriptors, while others like the
1411 * trampoline creation functions do not.
1412 * We assume that all GOT slots contain function descriptors, and create
1413 * descriptors in aot-runtime.c when needed.
1414 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1415 * from function descriptors, we could do the same, but it would require
1416 * rewriting all the ppc/aot code to handle function descriptors properly.
1417 * So instead, we use the same approach as on PPC32.
1418 * This is a horrible mess, but fixing it would probably lead to an even bigger
1424 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1427 #ifdef MONO_ARCH_AOT_SUPPORTED
1429 * arch_emit_got_offset:
1431 * The memory pointed to by CODE should hold native code for computing the GOT
1432 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1433 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1436 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1438 #if defined(TARGET_POWERPC64)
1439 emit_unset_mode (acfg);
1441 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1442 * unsupported relocations. So we store the got address into the .Lgot_addr
1443 * symbol which is in the text segment, compute its address, and load it.
1445 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1446 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1447 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1448 fprintf (acfg->fp, "add 30, 30, 0\n");
1449 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1450 acfg->label_generator ++;
1452 #elif defined(TARGET_POWERPC)
1453 emit_unset_mode (acfg);
1454 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1455 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1456 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1457 acfg->label_generator ++;
1460 guint32 offset = mono_arch_get_patch_offset (code);
1461 emit_bytes (acfg, code, offset);
1462 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1464 *code_size = offset + 4;
1469 * arch_emit_got_access:
1471 * The memory pointed to by CODE should hold native code for loading a GOT
1472 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1473 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1476 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1479 /* mov reg, got+offset(%rip) */
1481 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1485 /* Decode reg, see amd64_mov_reg_membase () */
1486 rex_r = code [0] & AMD64_REX_R;
1487 g_assert (code [0] == 0x49 + rex_r);
1488 g_assert (code [1] == 0x8b);
1489 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1491 emit_unset_mode (acfg);
1492 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1495 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1496 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1497 *code_size = mono_arch_get_patch_offset (code) + 4;
1499 #elif defined(TARGET_X86)
1500 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1501 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1502 *code_size = mono_arch_get_patch_offset (code) + 4;
1503 #elif defined(TARGET_ARM)
1504 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1505 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1506 *code_size = mono_arch_get_patch_offset (code) + 4;
1507 #elif defined(TARGET_ARM64)
1508 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1509 arm64_emit_got_access (acfg, code, got_slot, code_size);
1510 #elif defined(TARGET_POWERPC)
1514 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1516 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1517 g_assert (code - buf == 8);
1518 emit_bytes (acfg, buf, code - buf);
1519 *code_size = code - buf;
1522 g_assert_not_reached ();
1528 #ifdef MONO_ARCH_AOT_SUPPORTED
1530 * arch_emit_objc_selector_ref:
1532 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1535 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1537 #if defined(TARGET_ARM)
1538 char symbol1 [MAX_SYMBOL_SIZE];
1539 char symbol2 [MAX_SYMBOL_SIZE];
1540 int lindex = acfg->objc_selector_index_2 ++;
1542 /* Emit ldr.imm/b */
1543 emit_bytes (acfg, code, 8);
1545 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1546 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1548 emit_label (acfg, symbol1);
1549 mono_img_writer_emit_unset_mode (acfg->w);
1550 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1553 #elif defined(TARGET_ARM64)
1554 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1556 g_assert_not_reached ();
1562 * arch_emit_plt_entry:
1564 * Emit code for the PLT entry.
1565 * The plt entry should look like this:
1566 * <indirect jump to GOT_SYMBOL + OFFSET>
1567 * <INFO_OFFSET embedded into the instruction stream>
1570 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1572 #if defined(TARGET_X86)
1573 /* jmp *<offset>(%ebx) */
1574 emit_byte (acfg, 0xff);
1575 emit_byte (acfg, 0xa3);
1576 emit_int32 (acfg, offset);
1577 /* Used by mono_aot_get_plt_info_offset */
1578 emit_int32 (acfg, info_offset);
1579 #elif defined(TARGET_AMD64)
1580 emit_unset_mode (acfg);
1581 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1582 /* Used by mono_aot_get_plt_info_offset */
1583 emit_int32 (acfg, info_offset);
1584 acfg->stats.plt_size += 10;
1585 #elif defined(TARGET_ARM)
1590 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1591 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1592 emit_bytes (acfg, buf, code - buf);
1593 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1594 /* Used by mono_aot_get_plt_info_offset */
1595 emit_int32 (acfg, info_offset);
1596 #elif defined(TARGET_ARM64)
1597 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1598 #elif defined(TARGET_POWERPC)
1599 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1600 emit_unset_mode (acfg);
1601 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1602 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1603 fprintf (acfg->fp, "add 11, 11, 30\n");
1604 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1605 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1606 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1607 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1609 fprintf (acfg->fp, "mtctr 11\n");
1610 fprintf (acfg->fp, "bctr\n");
1611 emit_int32 (acfg, info_offset);
1613 g_assert_not_reached ();
1618 * arch_emit_llvm_plt_entry:
1620 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1621 * This is only needed on arm to handle thumb interop.
1624 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1626 #if defined(TARGET_ARM)
1627 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1628 /* The caller already transitioned to thumb */
1629 /* The code below should be 12 bytes long */
1630 /* clang has trouble encoding these instructions, so emit the binary */
1632 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1633 /* thumb can't encode ld pc, [pc, ip] */
1634 fprintf (acfg->fp, "add ip, pc, ip\n");
1635 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1636 fprintf (acfg->fp, "bx ip\n");
1638 emit_set_thumb_mode (acfg);
1639 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1640 fprintf (acfg->fp, ".2byte 0x44fc\n");
1641 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1642 fprintf (acfg->fp, ".2byte 0x4760\n");
1643 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1644 emit_int32 (acfg, info_offset);
1645 emit_unset_mode (acfg);
1646 emit_set_arm_mode (acfg);
1648 g_assert_not_reached ();
1652 /* Save unwind_info in the module and emit the offset to the information at symbol */
1653 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1655 guint32 uw_offset, encoded_len;
1658 emit_section_change (acfg, RODATA_SECT, 0);
1659 emit_global (acfg, symbol, FALSE);
1660 emit_label (acfg, symbol);
1662 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1663 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1665 emit_int32 (acfg, uw_offset);
1669 * arch_emit_specific_trampoline_pages:
1671 * Emits a page full of trampolines: each trampoline uses its own address to
1672 * lookup both the generic trampoline code and the data argument.
1673 * This page can be remapped in process multiple times so we can get an
1674 * unlimited number of trampolines.
1675 * Specifically this implementation uses the following trick: two memory pages
1676 * are allocated, with the first containing the data and the second containing the trampolines.
1677 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1678 * implementation does all the lifting.
1679 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1680 * on the arm 32 bit system.
1683 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1685 #if defined(TARGET_ARM)
1688 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1690 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1691 GSList *unwind_ops = NULL;
1692 #define COMMON_TRAMP_SIZE 16
1693 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1694 int imm8, rot_amount;
1697 if (!acfg->aot_opts.use_trampolines_page)
1700 acfg->tramp_page_size = pagesize;
1702 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1703 emit_alignment (acfg, pagesize);
1704 emit_global (acfg, symbol, TRUE);
1705 emit_label (acfg, symbol);
1707 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1709 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1710 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1711 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1712 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1714 g_assert (code - buf == COMMON_TRAMP_SIZE);
1717 emit_bytes (acfg, buf, code - buf);
1719 for (i = 0; i < count; ++i) {
1721 ARM_PUSH (code, 0x5fff);
1723 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1724 g_assert (code - buf == 8);
1725 emit_bytes (acfg, buf, code - buf);
1728 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1729 * the instruction pointer address, so the generic trampoline at the start of the page
1730 * subtracts 4096 to get to the data page and loads the values
1731 * We again fit the generic trampiline in 16 bytes.
1733 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1734 emit_global (acfg, symbol, TRUE);
1735 emit_label (acfg, symbol);
1737 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1738 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1739 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1740 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1742 g_assert (code - buf == COMMON_TRAMP_SIZE);
1745 emit_bytes (acfg, buf, code - buf);
1747 for (i = 0; i < count; ++i) {
1749 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1751 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1752 g_assert (code - buf == 8);
1753 emit_bytes (acfg, buf, code - buf);
1757 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1759 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1760 emit_global (acfg, symbol, TRUE);
1761 emit_label (acfg, symbol);
1763 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1764 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1765 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1766 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1767 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1768 g_assert (code - buf == COMMON_TRAMP_SIZE);
1770 emit_bytes (acfg, buf, code - buf);
1772 for (i = 0; i < count; ++i) {
1774 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1776 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1777 g_assert (code - buf == 8);
1778 emit_bytes (acfg, buf, code - buf);
1781 /* now the imt trampolines: each specific trampolines puts in the ip register
1782 * the instruction pointer address, so the generic trampoline at the start of the page
1783 * subtracts 4096 to get to the data page and loads the values
1785 #define IMT_TRAMP_SIZE 72
1786 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1787 emit_global (acfg, symbol, TRUE);
1788 emit_label (acfg, symbol);
1790 /* Need at least two free registers, plus a slot for storing the pc */
1791 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1793 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1794 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1795 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1797 /* The IMT method is in v5, r0 has the imt array address */
1800 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1801 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1802 imt_found_check = code;
1803 ARM_B_COND (code, ARMCOND_EQ, 0);
1805 /* End-of-loop check */
1806 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1807 loop_end_check = code;
1808 ARM_B_COND (code, ARMCOND_EQ, 0);
1811 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1812 loop_branch_back = code;
1814 arm_patch (loop_branch_back, loop_start);
1817 arm_patch (imt_found_check, code);
1818 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1819 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1820 /* Save it to the third stack slot */
1821 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1822 /* Restore the registers and branch */
1823 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1826 arm_patch (loop_end_check, code);
1827 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1828 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1829 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1833 g_assert (code - buf == IMT_TRAMP_SIZE);
1834 emit_bytes (acfg, buf, code - buf);
1836 for (i = 0; i < count; ++i) {
1838 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1840 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1841 g_assert (code - buf == 8);
1842 emit_bytes (acfg, buf, code - buf);
1845 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1846 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1847 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1848 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1850 /* Unwind info for specifc trampolines */
1851 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1852 /* We unwind to the original caller, from the stack, since lr is clobbered */
1853 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1854 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1855 save_unwind_info (acfg, symbol, unwind_ops);
1856 mono_free_unwind_info (unwind_ops);
1858 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1859 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1860 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1861 save_unwind_info (acfg, symbol, unwind_ops);
1862 mono_free_unwind_info (unwind_ops);
1864 /* Unwind info for rgctx trampolines */
1865 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1866 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1867 save_unwind_info (acfg, symbol, unwind_ops);
1869 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1870 save_unwind_info (acfg, symbol, unwind_ops);
1871 mono_free_unwind_info (unwind_ops);
1873 /* Unwind info for gsharedvt trampolines */
1874 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1875 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1876 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1877 save_unwind_info (acfg, symbol, unwind_ops);
1878 mono_free_unwind_info (unwind_ops);
1880 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1881 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1882 save_unwind_info (acfg, symbol, unwind_ops);
1883 mono_free_unwind_info (unwind_ops);
1885 /* Unwind info for imt trampolines */
1886 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1887 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1888 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1889 save_unwind_info (acfg, symbol, unwind_ops);
1890 mono_free_unwind_info (unwind_ops);
1892 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1893 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1894 save_unwind_info (acfg, symbol, unwind_ops);
1895 mono_free_unwind_info (unwind_ops);
1896 #elif defined(TARGET_ARM64)
1897 arm64_emit_specific_trampoline_pages (acfg);
1902 * arch_emit_specific_trampoline:
1904 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1905 * two GOT slots which contain the generic trampoline address and the trampoline
1906 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1909 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1912 * The trampolines created here are variations of the specific
1913 * trampolines created in mono_arch_create_specific_trampoline (). The
1915 * - the generic trampoline address is taken from a got slot.
1916 * - the offset of the got slot where the trampoline argument is stored
1917 * is embedded in the instruction stream, and the generic trampoline
1918 * can load the argument by loading the offset, adding it to the
1919 * address of the trampoline to get the address of the got slot, and
1920 * loading the argument from there.
1921 * - all the trampolines should be of the same length.
1923 #if defined(TARGET_AMD64)
1924 /* This should be exactly 8 bytes long */
1926 /* call *<offset>(%rip) */
1928 emit_unset_mode (acfg);
1929 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1930 emit_zero_bytes (acfg, 2);
1932 emit_byte (acfg, '\x41');
1933 emit_byte (acfg, '\xff');
1934 emit_byte (acfg, '\x15');
1935 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1936 emit_zero_bytes (acfg, 1);
1938 #elif defined(TARGET_ARM)
1942 /* This should be exactly 20 bytes long */
1945 ARM_PUSH (code, 0x5fff);
1946 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1947 /* Load the value from the GOT */
1948 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1950 ARM_BLX_REG (code, ARMREG_R1);
1952 g_assert (code - buf == 16);
1955 emit_bytes (acfg, buf, code - buf);
1957 * Only one offset is needed, since the second one would be equal to the
1960 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1961 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1962 #elif defined(TARGET_ARM64)
1963 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1964 #elif defined(TARGET_POWERPC)
1972 * PPC has no ip relative addressing, so we need to compute the address
1973 * of the mscorlib got. That is slow and complex, so instead, we store it
1974 * in the second got slot of every aot image. The caller already computed
1975 * the address of its got and placed it into r30.
1977 emit_unset_mode (acfg);
1978 /* Load mscorlib got address */
1979 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1980 /* Load generic trampoline address */
1981 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1982 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1983 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1984 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1985 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1987 fprintf (acfg->fp, "mtctr 11\n");
1988 /* Load trampoline argument */
1989 /* On ppc, we pass it normally to the generic trampoline */
1990 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1991 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1992 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1993 /* Branch to generic trampoline */
1994 fprintf (acfg->fp, "bctr\n");
1996 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1997 *tramp_size = 10 * 4;
1999 *tramp_size = 9 * 4;
2001 #elif defined(TARGET_X86)
2005 /* Similar to the PPC code above */
2007 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2010 /* Load mscorlib got address */
2011 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2012 /* Push trampoline argument */
2013 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2014 /* Load generic trampoline address */
2015 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2016 /* Branch to generic trampoline */
2017 x86_jump_reg (code, X86_ECX);
2019 emit_bytes (acfg, buf, code - buf);
2022 g_assert (code - buf == *tramp_size);
2024 g_assert_not_reached ();
2029 * arch_emit_unbox_trampoline:
2031 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2032 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2035 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2037 #if defined(TARGET_AMD64)
2042 this_reg = mono_arch_get_this_arg_reg (NULL);
2044 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2046 emit_bytes (acfg, buf, code - buf);
2049 emit_unset_mode (acfg);
2050 fprintf (acfg->fp, "jmp %s\n", call_target);
2052 emit_byte (acfg, '\xe9');
2053 emit_symbol_diff (acfg, call_target, ".", -4);
2055 #elif defined(TARGET_X86)
2062 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2064 emit_bytes (acfg, buf, code - buf);
2067 emit_byte (acfg, '\xe9');
2068 emit_symbol_diff (acfg, call_target, ".", -4);
2069 #elif defined(TARGET_ARM)
2073 if (acfg->thumb_mixed && cfg->compile_llvm) {
2074 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2075 fprintf (acfg->fp, "b %s\n", call_target);
2076 fprintf (acfg->fp, ".arm\n");
2077 fprintf (acfg->fp, ".align 2\n");
2083 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2085 emit_bytes (acfg, buf, code - buf);
2086 /* jump to method */
2087 if (acfg->thumb_mixed && cfg->compile_llvm)
2088 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2090 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2091 #elif defined(TARGET_ARM64)
2092 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2093 #elif defined(TARGET_POWERPC)
2096 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2097 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2099 g_assert_not_reached ();
2104 * arch_emit_static_rgctx_trampoline:
2106 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2107 * two GOT slots which contain the rgctx argument, and the method to jump to.
2108 * TRAMP_SIZE is set to the size of the emitted trampoline.
2109 * These kinds of trampolines cannot be enumerated statically, since there could
2110 * be one trampoline per method instantiation, so we emit the same code for all
2111 * trampolines, and parameterize them using two GOT slots.
2114 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2116 #if defined(TARGET_AMD64)
2117 /* This should be exactly 13 bytes long */
2121 emit_unset_mode (acfg);
2122 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2123 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2125 /* mov <OFFSET>(%rip), %r10 */
2126 emit_byte (acfg, '\x4d');
2127 emit_byte (acfg, '\x8b');
2128 emit_byte (acfg, '\x15');
2129 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2131 /* jmp *<offset>(%rip) */
2132 emit_byte (acfg, '\xff');
2133 emit_byte (acfg, '\x25');
2134 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2136 #elif defined(TARGET_ARM)
2140 /* This should be exactly 24 bytes long */
2143 /* Load rgctx value */
2144 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2145 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2146 /* Load branch addr + branch */
2147 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2148 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2150 g_assert (code - buf == 16);
2153 emit_bytes (acfg, buf, code - buf);
2154 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2155 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2156 #elif defined(TARGET_ARM64)
2157 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2158 #elif defined(TARGET_POWERPC)
2166 * PPC has no ip relative addressing, so we need to compute the address
2167 * of the mscorlib got. That is slow and complex, so instead, we store it
2168 * in the second got slot of every aot image. The caller already computed
2169 * the address of its got and placed it into r30.
2171 emit_unset_mode (acfg);
2172 /* Load mscorlib got address */
2173 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2175 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2176 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2177 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2178 /* Load target address */
2179 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2180 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2181 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2182 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2183 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2184 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2186 fprintf (acfg->fp, "mtctr 11\n");
2187 /* Branch to the target address */
2188 fprintf (acfg->fp, "bctr\n");
2190 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2191 *tramp_size = 11 * 4;
2193 *tramp_size = 9 * 4;
2196 #elif defined(TARGET_X86)
2200 /* Similar to the PPC code above */
2202 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2205 /* Load mscorlib got address */
2206 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2208 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2209 /* Branch to the target address */
2210 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2212 emit_bytes (acfg, buf, code - buf);
2215 g_assert (code - buf == *tramp_size);
2217 g_assert_not_reached ();
2222 * arch_emit_imt_trampoline:
2224 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2225 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2226 * key is the IMT key, and ptr holds the address of a memory location holding
2227 * the address to branch to if the IMT arg matches the key. The array is
2228 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2230 * TRAMP_SIZE is set to the size of the emitted trampoline.
2233 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2235 #if defined(TARGET_AMD64)
2237 guint8 *labels [16];
2239 guint8 *mov_buf_ptr = mov_buf;
2241 const int kSizeOfMove = 7;
2243 code = buf = (guint8 *)g_malloc (256);
2245 /* FIXME: Optimize this, i.e. use binary search etc. */
2246 /* Maybe move the body into a separate function (slower, but much smaller) */
2248 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2251 emit_unset_mode (acfg);
2252 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2256 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2258 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2261 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2263 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2266 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2267 amd64_jump_code (code, labels [0]);
2270 mono_amd64_patch (labels [2], code);
2271 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2272 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2275 mono_amd64_patch (labels [1], code);
2276 /* Load fail tramp */
2277 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2278 /* Check if there is a fail tramp */
2279 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2281 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2282 /* Jump to fail tramp */
2283 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2286 mono_amd64_patch (labels [3], code);
2287 x86_breakpoint (code);
2290 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2291 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2292 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2293 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2294 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2295 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2297 emit_bytes (acfg, buf, code - buf);
2299 *tramp_size = code - buf + kSizeOfMove;
2303 #elif defined(TARGET_X86)
2305 guint8 *labels [16];
2307 code = buf = g_malloc (256);
2309 /* Allocate a temporary stack slot */
2310 x86_push_reg (code, X86_EAX);
2312 x86_push_reg (code, X86_EAX);
2314 /* Load mscorlib got address */
2315 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2317 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2320 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2322 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2325 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2327 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2330 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2331 x86_jump_code (code, labels [0]);
2334 mono_x86_patch (labels [2], code);
2335 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2336 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2337 /* Save the target address to the temporary stack location */
2338 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2340 x86_pop_reg (code, X86_EAX);
2341 /* Jump to the target address */
2345 mono_x86_patch (labels [1], code);
2346 /* Load fail tramp */
2347 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2348 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2350 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2351 /* Jump to fail tramp */
2352 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2353 x86_pop_reg (code, X86_EAX);
2357 mono_x86_patch (labels [3], code);
2358 x86_breakpoint (code);
2360 emit_bytes (acfg, buf, code - buf);
2362 *tramp_size = code - buf;
2366 #elif defined(TARGET_ARM)
2368 guint8 *code, *code2, *labels [16];
2372 /* The IMT method is in v5 */
2374 /* Need at least two free registers, plus a slot for storing the pc */
2375 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2377 /* Load the parameter from the GOT */
2378 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2379 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2382 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2383 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2385 ARM_B_COND (code, ARMCOND_EQ, 0);
2387 /* End-of-loop check */
2388 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2390 ARM_B_COND (code, ARMCOND_EQ, 0);
2393 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2396 arm_patch (labels [4], labels [1]);
2399 arm_patch (labels [2], code);
2400 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2401 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2402 /* Save it to the third stack slot */
2403 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2404 /* Restore the registers and branch */
2405 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2408 arm_patch (labels [3], code);
2409 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2410 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2411 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2415 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2417 emit_bytes (acfg, buf, code - buf);
2418 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2420 *tramp_size = code - buf + 4;
2421 #elif defined(TARGET_ARM64)
2422 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2423 #elif defined(TARGET_POWERPC)
2425 guint8 *code, *labels [16];
2429 /* Load the mscorlib got address */
2430 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2431 /* Load the parameter from the GOT */
2432 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2433 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2435 /* Load and check key */
2437 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2438 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2440 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2442 /* End-of-loop check */
2443 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2445 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2448 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2451 mono_ppc_patch (labels [4], labels [1]);
2454 mono_ppc_patch (labels [2], code);
2455 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2456 /* r12 now contains the value of the vtable slot */
2457 /* this is not a function descriptor on ppc64 */
2458 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2459 ppc_mtctr (code, ppc_r12);
2460 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2463 mono_ppc_patch (labels [3], code);
2467 *tramp_size = code - buf;
2469 emit_bytes (acfg, buf, code - buf);
2471 g_assert_not_reached ();
2476 #if defined (TARGET_AMD64)
2479 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2482 g_assert (acfg->fp);
2483 emit_unset_mode (acfg);
2485 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2492 * arch_emit_gsharedvt_arg_trampoline:
2494 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2495 * two GOT slots which contain the argument, and the code to jump to.
2496 * TRAMP_SIZE is set to the size of the emitted trampoline.
2497 * These kinds of trampolines cannot be enumerated statically, since there could
2498 * be one trampoline per method instantiation, so we emit the same code for all
2499 * trampolines, and parameterize them using two GOT slots.
2502 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2504 #if defined(TARGET_X86)
2508 /* Similar to the PPC code above */
2510 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2513 /* Load mscorlib got address */
2514 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2516 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2517 /* Branch to the target address */
2518 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2520 emit_bytes (acfg, buf, code - buf);
2523 g_assert (code - buf == *tramp_size);
2524 #elif defined(TARGET_ARM)
2528 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2529 /* Similar to arch_emit_specific_trampoline () */
2532 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2533 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2534 /* Load the arg value from the GOT */
2535 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2536 /* Load the addr from the GOT */
2537 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2539 ARM_BX (code, ARMREG_R1);
2541 g_assert (code - buf == 20);
2544 emit_bytes (acfg, buf, code - buf);
2545 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2546 #elif defined(TARGET_ARM64)
2547 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2548 #elif defined (TARGET_AMD64)
2550 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2551 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2552 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2553 fprintf (acfg->fp, "jmp *%%r11\n");
2557 g_assert_not_reached ();
2561 /* END OF ARCH SPECIFIC CODE */
2564 mono_get_field_token (MonoClassField *field)
2566 MonoClass *klass = field->parent;
2569 int fcount = mono_class_get_field_count (klass);
2570 for (i = 0; i < fcount; ++i) {
2571 if (field == &klass->fields [i])
2572 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2575 g_assert_not_reached ();
2580 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2584 //printf ("ENCODE: %d 0x%x.\n", value, value);
2587 * Same encoding as the one used in the metadata, extended to handle values
2588 * greater than 0x1fffffff.
2590 if ((value >= 0) && (value <= 127))
2592 else if ((value >= 0) && (value <= 16383)) {
2593 p [0] = 0x80 | (value >> 8);
2594 p [1] = value & 0xff;
2596 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2597 p [0] = (value >> 24) | 0xc0;
2598 p [1] = (value >> 16) & 0xff;
2599 p [2] = (value >> 8) & 0xff;
2600 p [3] = value & 0xff;
2605 p [1] = (value >> 24) & 0xff;
2606 p [2] = (value >> 16) & 0xff;
2607 p [3] = (value >> 8) & 0xff;
2608 p [4] = value & 0xff;
2616 stream_init (MonoDynamicStream *sh)
2619 sh->alloc_size = 4096;
2620 sh->data = (char *)g_malloc (4096);
2622 /* So offsets are > 0 */
2628 make_room_in_stream (MonoDynamicStream *stream, int size)
2630 if (size <= stream->alloc_size)
2633 while (stream->alloc_size <= size) {
2634 if (stream->alloc_size < 4096)
2635 stream->alloc_size = 4096;
2637 stream->alloc_size *= 2;
2640 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2644 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2648 make_room_in_stream (stream, stream->index + len);
2649 memcpy (stream->data + stream->index, data, len);
2650 idx = stream->index;
2651 stream->index += len;
2658 * Add data to the binary blob inside the aot image. Returns the offset inside the
2659 * blob where the data was stored.
2662 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2664 g_assert (!acfg->blob_closed);
2666 if (acfg->blob.alloc_size == 0)
2667 stream_init (&acfg->blob);
2669 return add_stream_data (&acfg->blob, (char*)data, data_len);
2673 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2678 if (acfg->blob.alloc_size == 0)
2679 stream_init (&acfg->blob);
2681 count = acfg->blob.index % align;
2683 /* we assume the stream data will be aligned */
2685 add_stream_data (&acfg->blob, buf, 4 - count);
2687 return add_stream_data (&acfg->blob, (char*)data, data_len);
2690 /* Emit a table of data into the aot image */
2692 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2694 if (acfg->data_outfile) {
2695 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2696 fwrite (data,1, size, acfg->data_outfile);
2697 acfg->datafile_offset += size;
2698 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2699 int align = 8 - size % 8;
2700 acfg->datafile_offset += align;
2701 guint8 align_buf [16];
2702 memset (&align_buf, 0, sizeof (align_buf));
2703 fwrite (align_buf, align, 1, acfg->data_outfile);
2704 } else if (acfg->llvm) {
2705 mono_llvm_emit_aot_data (symbol, data, size);
2707 emit_section_change (acfg, RODATA_SECT, 0);
2708 emit_alignment (acfg, 8);
2709 emit_label (acfg, symbol);
2710 emit_bytes (acfg, data, size);
2715 * emit_offset_table:
2717 * Emit a table of increasing offsets in a compact form using differential encoding.
2718 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2719 * group size, the more compact the table becomes, but the slower it becomes to compute
2720 * a given entry. Returns the size of the table.
2723 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2725 gint32 current_offset;
2726 int i, buf_size, ngroups, index_entry_size;
2728 guint8 *data_p, *data_buf;
2729 guint32 *index_offsets;
2731 ngroups = (noffsets + (group_size - 1)) / group_size;
2733 index_offsets = g_new0 (guint32, ngroups);
2735 buf_size = noffsets * 4;
2736 p = buf = (guint8 *)g_malloc0 (buf_size);
2739 for (i = 0; i < noffsets; ++i) {
2740 //printf ("D: %d -> %d\n", i, offsets [i]);
2741 if ((i % group_size) == 0) {
2742 index_offsets [i / group_size] = p - buf;
2743 /* Emit the full value for these entries */
2744 encode_value (offsets [i], p, &p);
2746 /* The offsets are allowed to be non-increasing */
2747 //g_assert (offsets [i] >= current_offset);
2748 encode_value (offsets [i] - current_offset, p, &p);
2750 current_offset = offsets [i];
2755 if (ngroups && index_offsets [ngroups - 1] < 65000)
2756 index_entry_size = 2;
2758 index_entry_size = 4;
2760 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2761 p = buf = (guint8 *)g_malloc0 (buf_size);
2763 /* Emit the header */
2764 encode_int (noffsets, p, &p);
2765 encode_int (group_size, p, &p);
2766 encode_int (ngroups, p, &p);
2767 encode_int (index_entry_size, p, &p);
2769 /* Emit the index */
2770 for (i = 0; i < ngroups; ++i) {
2771 if (index_entry_size == 2)
2772 encode_int16 (index_offsets [i], p, &p);
2774 encode_int (index_offsets [i], p, &p);
2777 memcpy (p, data_buf, data_p - data_buf);
2778 p += data_p - data_buf;
2780 g_assert (p - buf <= buf_size);
2782 emit_aot_data (acfg, table, symbol, buf, p - buf);
2787 return (int)(p - buf);
2791 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2795 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2799 index = g_hash_table_size (cfg->image_hash);
2800 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2801 g_ptr_array_add (cfg->image_table, image);
2807 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2810 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2812 /* FIXME: Search referenced images as well */
2813 if (!acfg->typespec_classes) {
2814 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2815 for (i = 0; i < len; i++) {
2817 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2818 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2819 if (!is_ok (&error)) {
2820 mono_error_cleanup (&error);
2823 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2826 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2830 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2833 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2836 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2839 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2842 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2847 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2851 if (mono_class_is_ginst (klass)) {
2853 g_assert (klass->type_token);
2855 /* Find a typespec for a class if possible */
2856 token = find_typespec_for_class (acfg, klass);
2858 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2859 encode_value (token, p, &p);
2861 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2862 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2863 static int count = 0;
2866 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2867 encode_klass_ref (acfg, gclass, p, &p);
2868 encode_ginst (acfg, inst, p, &p);
2872 } else if (klass->type_token) {
2873 int iindex = get_image_index (acfg, klass->image);
2875 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2877 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2878 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2880 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2881 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2882 encode_value (get_image_index (acfg, klass->image), p, &p);
2884 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2885 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2886 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2888 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2890 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2891 if (par->gshared_constraint) {
2892 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2893 encode_type (acfg, par->gshared_constraint, p, &p);
2894 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2896 encode_value (klass->byval_arg.type, p, &p);
2897 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2899 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2901 if (!container->is_anonymous) {
2902 encode_value (container->is_method, p, &p);
2903 if (container->is_method)
2904 encode_method_ref (acfg, container->owner.method, p, &p);
2906 encode_klass_ref (acfg, container->owner.klass, p, &p);
2909 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2910 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2911 encode_type (acfg, &klass->byval_arg, p, &p);
2914 g_assert (klass->rank > 0);
2915 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2916 encode_value (klass->rank, p, &p);
2917 encode_klass_ref (acfg, klass->element_class, p, &p);
2925 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2926 * standard metadata encoding.
2929 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2931 gboolean shared = FALSE;
2934 * The encoding of generic instances is large so emit them only once.
2936 if (mono_class_is_ginst (klass)) {
2938 g_assert (klass->type_token);
2940 /* Find a typespec for a class if possible */
2941 token = find_typespec_for_class (acfg, klass);
2944 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2949 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2953 buf2 = (guint8 *)g_malloc (1024);
2956 encode_klass_ref_inner (acfg, klass, p, &p);
2957 g_assert (p - buf2 < 1024);
2959 offset = add_to_blob (acfg, buf2, p - buf2);
2962 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2968 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2969 encode_value (offset, p, &p);
2974 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2978 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2980 guint32 token = mono_get_field_token (field);
2983 encode_klass_ref (cfg, field->parent, p, &p);
2984 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2985 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2990 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2995 encode_value (inst->type_argc, p, &p);
2996 for (i = 0; i < inst->type_argc; ++i)
2997 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3002 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3005 MonoGenericInst *inst;
3007 inst = context->class_inst;
3009 g_assert (inst->type_argc);
3010 encode_ginst (acfg, inst, p, &p);
3012 encode_value (0, p, &p);
3014 inst = context->method_inst;
3016 g_assert (inst->type_argc);
3017 encode_ginst (acfg, inst, p, &p);
3019 encode_value (0, p, &p);
3025 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3029 g_assert (t->num_mods == 0);
3030 /* t->attrs can be ignored */
3031 //g_assert (t->attrs == 0);
3034 *p = MONO_TYPE_PINNED;
3038 *p = MONO_TYPE_BYREF;
3046 case MONO_TYPE_VOID:
3047 case MONO_TYPE_BOOLEAN:
3048 case MONO_TYPE_CHAR:
3061 case MONO_TYPE_STRING:
3062 case MONO_TYPE_OBJECT:
3063 case MONO_TYPE_TYPEDBYREF:
3065 case MONO_TYPE_VALUETYPE:
3066 case MONO_TYPE_CLASS:
3067 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3069 case MONO_TYPE_SZARRAY:
3070 encode_klass_ref (acfg, t->data.klass, p, &p);
3073 encode_type (acfg, t->data.type, p, &p);
3075 case MONO_TYPE_GENERICINST: {
3076 MonoClass *gclass = t->data.generic_class->container_class;
3077 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3079 encode_klass_ref (acfg, gclass, p, &p);
3080 encode_ginst (acfg, inst, p, &p);
3083 case MONO_TYPE_ARRAY: {
3084 MonoArrayType *array = t->data.array;
3087 encode_klass_ref (acfg, array->eklass, p, &p);
3088 encode_value (array->rank, p, &p);
3089 encode_value (array->numsizes, p, &p);
3090 for (i = 0; i < array->numsizes; ++i)
3091 encode_value (array->sizes [i], p, &p);
3092 encode_value (array->numlobounds, p, &p);
3093 for (i = 0; i < array->numlobounds; ++i)
3094 encode_value (array->lobounds [i], p, &p);
3098 case MONO_TYPE_MVAR:
3099 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3102 g_assert_not_reached ();
3109 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3115 /* Similar to the metadata encoding */
3116 if (sig->generic_param_count)
3120 if (sig->explicit_this)
3122 flags |= (sig->call_convention & 0x0F);
3126 if (sig->generic_param_count)
3127 encode_value (sig->generic_param_count, p, &p);
3128 encode_value (sig->param_count, p, &p);
3130 encode_type (acfg, sig->ret, p, &p);
3131 for (i = 0; i < sig->param_count; ++i) {
3132 if (sig->sentinelpos == i) {
3133 *p = MONO_TYPE_SENTINEL;
3136 encode_type (acfg, sig->params [i], p, &p);
3142 #define MAX_IMAGE_INDEX 250
3145 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3147 guint32 image_index = get_image_index (acfg, method->klass->image);
3148 guint32 token = method->token;
3149 MonoJumpInfoToken *ji;
3153 * The encoding for most methods is as follows:
3154 * - image index encoded as a leb128
3155 * - token index encoded as a leb128
3156 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3157 * types of method encodings.
3160 /* Mark methods which can't use aot trampolines because they need the further
3161 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3163 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3164 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3165 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3167 if (method->wrapper_type) {
3168 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3170 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3172 encode_value (method->wrapper_type, p, &p);
3174 switch (method->wrapper_type) {
3175 case MONO_WRAPPER_REMOTING_INVOKE:
3176 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3177 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3180 m = mono_marshal_method_from_wrapper (method);
3182 encode_method_ref (acfg, m, p, &p);
3185 case MONO_WRAPPER_PROXY_ISINST:
3186 case MONO_WRAPPER_LDFLD:
3187 case MONO_WRAPPER_LDFLDA:
3188 case MONO_WRAPPER_STFLD: {
3190 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3193 case MONO_WRAPPER_ALLOC: {
3194 /* The GC name is saved once in MonoAotFileInfo */
3195 g_assert (info->d.alloc.alloc_type != -1);
3196 encode_value (info->d.alloc.alloc_type, p, &p);
3199 case MONO_WRAPPER_WRITE_BARRIER: {
3203 case MONO_WRAPPER_STELEMREF: {
3205 encode_value (info->subtype, p, &p);
3206 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3207 encode_value (info->d.virtual_stelemref.kind, p, &p);
3210 case MONO_WRAPPER_UNKNOWN: {
3212 encode_value (info->subtype, p, &p);
3213 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3214 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3215 encode_klass_ref (acfg, method->klass, p, &p);
3216 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3217 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3218 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3219 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3220 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3221 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3222 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3223 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3226 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3228 encode_value (info->subtype, p, &p);
3229 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3230 strcpy ((char*)p, method->name);
3231 p += strlen (method->name) + 1;
3232 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3233 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3235 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3236 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3240 case MONO_WRAPPER_SYNCHRONIZED: {
3243 m = mono_marshal_method_from_wrapper (method);
3245 g_assert (m != method);
3246 encode_method_ref (acfg, m, p, &p);
3249 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3251 encode_value (info->subtype, p, &p);
3253 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3254 encode_value (info->d.element_addr.rank, p, &p);
3255 encode_value (info->d.element_addr.elem_size, p, &p);
3256 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3257 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3259 g_assert_not_reached ();
3263 case MONO_WRAPPER_CASTCLASS: {
3265 encode_value (info->subtype, p, &p);
3268 case MONO_WRAPPER_RUNTIME_INVOKE: {
3270 encode_value (info->subtype, p, &p);
3271 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3272 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3273 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3274 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3277 case MONO_WRAPPER_DELEGATE_INVOKE:
3278 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3279 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3280 if (method->is_inflated) {
3281 /* These wrappers are identified by their class */
3282 encode_value (1, p, &p);
3283 encode_klass_ref (acfg, method->klass, p, &p);
3285 MonoMethodSignature *sig = mono_method_signature (method);
3286 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3288 encode_value (0, p, &p);
3289 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3290 encode_value (info ? info->subtype : 0, p, &p);
3291 encode_signature (acfg, sig, p, &p);
3295 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3297 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3298 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3302 g_assert_not_reached ();
3304 } else if (mono_method_signature (method)->is_inflated) {
3306 * This is a generic method, find the original token which referenced it and
3308 * Obtain the token from information recorded by the JIT.
3310 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3312 image_index = get_image_index (acfg, ji->image);
3313 g_assert (image_index < MAX_IMAGE_INDEX);
3316 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3317 encode_value (image_index, p, &p);
3318 encode_value (token, p, &p);
3320 MonoMethod *declaring;
3321 MonoGenericContext *context = mono_method_get_context (method);
3323 g_assert (method->is_inflated);
3324 declaring = ((MonoMethodInflated*)method)->declaring;
3327 * This might be a non-generic method of a generic instance, which
3328 * doesn't have a token since the reference is generated by the JIT
3329 * like Nullable:Box/Unbox, or by generic sharing.
3331 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3332 /* Encode the klass */
3333 encode_klass_ref (acfg, method->klass, p, &p);
3334 /* Encode the method */
3335 image_index = get_image_index (acfg, method->klass->image);
3336 g_assert (image_index < MAX_IMAGE_INDEX);
3337 g_assert (declaring->token);
3338 token = declaring->token;
3339 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3340 encode_value (image_index, p, &p);
3341 encode_value (token, p, &p);
3342 encode_generic_context (acfg, context, p, &p);
3344 } else if (token == 0) {
3345 /* This might be a method of a constructed type like int[,].Set */
3346 /* Obtain the token from information recorded by the JIT */
3347 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3349 image_index = get_image_index (acfg, ji->image);
3350 g_assert (image_index < MAX_IMAGE_INDEX);
3353 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3354 encode_value (image_index, p, &p);
3355 encode_value (token, p, &p);
3358 g_assert (method->klass->rank);
3360 /* Encode directly */
3361 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3362 encode_klass_ref (acfg, method->klass, p, &p);
3363 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3364 encode_value (0, p, &p);
3365 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3366 encode_value (1, p, &p);
3367 else if (!strcmp (method->name, "Get"))
3368 encode_value (2, p, &p);
3369 else if (!strcmp (method->name, "Address"))
3370 encode_value (3, p, &p);
3371 else if (!strcmp (method->name, "Set"))
3372 encode_value (4, p, &p);
3374 g_assert_not_reached ();
3377 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3379 if (image_index >= MONO_AOT_METHODREF_MIN) {
3380 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3381 encode_value (image_index, p, &p);
3382 encode_value (mono_metadata_token_index (token), p, &p);
3384 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3391 compare_patches (gconstpointer a, gconstpointer b)
3395 i = (*(MonoJumpInfo**)a)->ip.i;
3396 j = (*(MonoJumpInfo**)b)->ip.i;
3407 static G_GNUC_UNUSED char*
3408 patch_to_string (MonoJumpInfo *patch_info)
3412 str = g_string_new ("");
3414 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3416 switch (patch_info->type) {
3417 case MONO_PATCH_INFO_VTABLE:
3418 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3423 g_string_append_printf (str, ")");
3424 return g_string_free (str, FALSE);
3430 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3433 static inline gboolean
3434 is_plt_patch (MonoJumpInfo *patch_info)
3436 switch (patch_info->type) {
3437 case MONO_PATCH_INFO_METHOD:
3438 case MONO_PATCH_INFO_INTERNAL_METHOD:
3439 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3440 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3441 case MONO_PATCH_INFO_RGCTX_FETCH:
3451 * Return the symbol identifying the plt entry PLT_OFFSET.
3454 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3458 * The Apple linker reorganizes object files, so it doesn't like branches to local
3459 * labels, since those have no relocations.
3461 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3463 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3470 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3472 static MonoPltEntry*
3473 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3476 gboolean synchronized = FALSE;
3477 static int synchronized_symbol_idx;
3479 if (!is_plt_patch (patch_info))
3482 if (!acfg->patch_to_plt_entry [patch_info->type])
3483 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3484 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3486 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3488 * Allocate a separate PLT slot for each such patch, since some plt
3489 * entries will refer to the method itself, and some will refer to the
3493 synchronized = TRUE;
3497 MonoJumpInfo *new_ji;
3499 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3501 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3502 res->plt_offset = acfg->plt_offset;
3504 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3505 if (acfg->aot_opts.write_symbols)
3506 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3508 /* Avoid duplicate symbols because we don't cache */
3509 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3511 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3512 synchronized_symbol_idx ++;
3515 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3517 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3519 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3521 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3523 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3524 //mono_print_ji (patch_info); printf ("\n");
3525 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3527 acfg->plt_offset ++;
3536 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3537 * JI could be found if it exists, otherwise allocates a new one.
3540 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3543 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3545 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3547 return got_offset - 1;
3550 got_offset = acfg->llvm_got_offset;
3551 acfg->llvm_got_offset ++;
3553 got_offset = acfg->got_offset;
3554 acfg->got_offset ++;
3557 acfg->stats.got_slots ++;
3558 acfg->stats.got_slot_types [ji->type] ++;
3560 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3561 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3562 g_ptr_array_add (info->got_patches, ji);
3567 /* Add a method to the list of methods which need to be emitted */
3569 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3572 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3573 g_ptr_array_add (acfg->methods, method);
3574 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3575 acfg->nmethods = acfg->methods->len + 1;
3578 if (method->wrapper_type || extra)
3579 g_ptr_array_add (acfg->extra_methods, method);
3583 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3585 /* One instantiation with valuetypes is generated for each async method */
3586 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3593 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3595 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3603 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3607 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3611 index = acfg->method_index;
3612 add_method_with_index (acfg, method, index, extra);
3614 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3616 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3618 acfg->method_index ++;
3624 add_method (MonoAotCompile *acfg, MonoMethod *method)
3626 return add_method_full (acfg, method, FALSE, 0);
3630 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3632 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3633 method = mini_get_shared_method (method);
3634 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3635 /* Use the gsharedvt version */
3636 method = mini_get_shared_method_full (method, TRUE, TRUE);
3638 if (acfg->aot_opts.log_generics)
3639 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3641 add_method_full (acfg, method, TRUE, depth);
3645 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3647 add_extra_method_with_depth (acfg, method, 0);
3651 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3653 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3654 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3655 MonoMethod *wrapper;
3661 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3662 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3665 add_method (acfg, wrapper);
3669 get_runtime_invoke_sig (MonoMethodSignature *sig)
3671 MonoMethodBuilder *mb;
3674 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3675 m = mono_mb_create_method (mb, sig, 16);
3676 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3682 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3684 return mono_marshal_get_runtime_invoke (method, virtual_);
3688 can_marshal_struct (MonoClass *klass)
3690 MonoClassField *field;
3691 gboolean can_marshal = TRUE;
3692 gpointer iter = NULL;
3693 MonoMarshalType *info;
3696 if (mono_class_is_auto_layout (klass))
3699 info = mono_marshal_load_type_info (klass);
3701 /* Only allow a few field types to avoid asserts in the marshalling code */
3702 while ((field = mono_class_get_fields (klass, &iter))) {
3703 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3706 switch (field->type->type) {
3711 case MONO_TYPE_BOOLEAN:
3714 case MONO_TYPE_CHAR:
3722 case MONO_TYPE_STRING:
3724 case MONO_TYPE_VALUETYPE:
3725 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3726 can_marshal = FALSE;
3728 case MONO_TYPE_SZARRAY: {
3729 gboolean has_mspec = FALSE;
3732 for (i = 0; i < info->num_fields; ++i) {
3733 if (info->fields [i].field == field && info->fields [i].mspec)
3738 can_marshal = FALSE;
3742 can_marshal = FALSE;
3748 /* Its hard to compute whenever these can be marshalled or not */
3749 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3756 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3758 /* Create a vtype instantiation */
3759 MonoGenericContext shared_context;
3761 MonoGenericInst *inst;
3762 MonoGenericContainer *container;
3763 MonoClass **constraints;
3766 memset (ctx, 0, sizeof (MonoGenericContext));
3768 if (mono_class_is_gtd (method->klass)) {
3769 shared_context = mono_class_get_generic_container (method->klass)->context;
3770 inst = shared_context.class_inst;
3772 args = g_new0 (MonoType*, inst->type_argc);
3773 for (i = 0; i < inst->type_argc; ++i) {
3774 args [i] = &mono_defaults.int_class->byval_arg;
3776 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3778 if (method->is_generic) {
3779 container = mono_method_get_generic_container (method);
3780 shared_context = container->context;
3781 inst = shared_context.method_inst;
3783 args = g_new0 (MonoType*, inst->type_argc);
3784 for (i = 0; i < container->type_argc; ++i) {
3785 MonoGenericParamInfo *info = &container->type_params [i].info;
3786 gboolean ref_only = FALSE;
3788 if (info && info->constraints) {
3789 constraints = info->constraints;
3791 while (*constraints) {
3792 MonoClass *cklass = *constraints;
3793 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3794 /* Inflaring the method with our vtype would not be valid */
3801 args [i] = &mono_defaults.object_class->byval_arg;
3803 args [i] = &mono_defaults.int_class->byval_arg;
3805 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3810 add_wrappers (MonoAotCompile *acfg)
3812 MonoMethod *method, *m;
3814 MonoMethodSignature *sig, *csig;
3818 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3819 * so there is only one wrapper of a given type, or inlining their contents into their
3822 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3825 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3826 gboolean skip = FALSE;
3828 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3829 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3831 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3832 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3833 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3836 /* Skip methods which can not be handled by get_runtime_invoke () */
3837 sig = mono_method_signature (method);
3840 if ((sig->ret->type == MONO_TYPE_PTR) ||
3841 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3843 if (mono_class_is_open_constructed_type (sig->ret))
3846 for (j = 0; j < sig->param_count; j++) {
3847 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3849 if (mono_class_is_open_constructed_type (sig->params [j]))
3853 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3854 if (!mono_class_is_contextbound (method->klass)) {
3855 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3856 gboolean has_nullable = FALSE;
3858 for (j = 0; j < sig->param_count; j++) {
3859 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3860 has_nullable = TRUE;
3863 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3864 /* Supported by the dynamic runtime-invoke wrapper */
3868 mono_arch_dyn_call_free (info);
3872 if (acfg->aot_opts.llvm_only)
3873 /* Supported by the gsharedvt based runtime-invoke wrapper */
3877 //printf ("%s\n", mono_method_full_name (method, TRUE));
3878 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3882 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3885 /* Runtime invoke wrappers */
3887 /* void runtime-invoke () [.cctor] */
3888 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3889 csig->ret = &mono_defaults.void_class->byval_arg;
3890 add_method (acfg, get_runtime_invoke_sig (csig));
3892 /* void runtime-invoke () [Finalize] */
3893 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3895 csig->ret = &mono_defaults.void_class->byval_arg;
3896 add_method (acfg, get_runtime_invoke_sig (csig));
3898 /* void runtime-invoke (string) [exception ctor] */
3899 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3901 csig->ret = &mono_defaults.void_class->byval_arg;
3902 csig->params [0] = &mono_defaults.string_class->byval_arg;
3903 add_method (acfg, get_runtime_invoke_sig (csig));
3905 /* void runtime-invoke (string, string) [exception ctor] */
3906 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3908 csig->ret = &mono_defaults.void_class->byval_arg;
3909 csig->params [0] = &mono_defaults.string_class->byval_arg;
3910 csig->params [1] = &mono_defaults.string_class->byval_arg;
3911 add_method (acfg, get_runtime_invoke_sig (csig));
3913 /* string runtime-invoke () [Exception.ToString ()] */
3914 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3916 csig->ret = &mono_defaults.string_class->byval_arg;
3917 add_method (acfg, get_runtime_invoke_sig (csig));
3919 /* void runtime-invoke (string, Exception) [exception ctor] */
3920 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3922 csig->ret = &mono_defaults.void_class->byval_arg;
3923 csig->params [0] = &mono_defaults.string_class->byval_arg;
3924 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3925 add_method (acfg, get_runtime_invoke_sig (csig));
3927 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3928 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3930 csig->ret = &(mono_class_load_from_name (
3931 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3932 csig->params [0] = &mono_defaults.string_class->byval_arg;
3933 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3934 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3935 add_method (acfg, get_runtime_invoke_sig (csig));
3937 /* runtime-invoke used by finalizers */
3938 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3940 /* This is used by mono_runtime_capture_context () */
3941 method = mono_get_context_capture_method ();
3943 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3945 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3946 if (!acfg->aot_opts.llvm_only)
3947 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3950 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3951 if (acfg->aot_opts.llvm_only) {
3954 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3955 for (variants = 0; variants < 4; ++variants) {
3956 for (i = 0; i < 16; ++i) {
3957 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3958 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3966 add_method (acfg, mono_marshal_get_stelemref ());
3968 /* Managed Allocators */
3969 nallocators = mono_gc_get_managed_allocator_types ();
3970 for (i = 0; i < nallocators; ++i) {
3971 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3972 add_method (acfg, m);
3973 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3974 add_method (acfg, m);
3977 /* write barriers */
3978 if (mono_gc_is_moving ()) {
3979 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3980 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3983 /* Stelemref wrappers */
3985 MonoMethod **wrappers;
3988 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3989 for (i = 0; i < nwrappers; ++i)
3990 add_method (acfg, wrappers [i]);
3994 /* castclass_with_check wrapper */
3995 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3996 /* isinst_with_check wrapper */
3997 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3999 /* JIT icall wrappers */
4000 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4001 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4005 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4006 * we use the original method instead at runtime.
4007 * Since full-aot doesn't support remoting, this is not a problem.
4010 /* remoting-invoke wrappers */
4011 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4013 MonoMethodSignature *sig;
4015 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4016 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4017 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4019 sig = mono_method_signature (method);
4021 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4022 m = mono_marshal_get_remoting_invoke_with_check (method);
4024 add_method (acfg, m);
4029 /* delegate-invoke wrappers */
4030 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4033 MonoCustomAttrInfo *cattr;
4035 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4036 klass = mono_class_get_checked (acfg->image, token, &error);
4039 mono_error_cleanup (&error);
4043 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4046 if (!mono_class_is_gtd (klass)) {
4047 method = mono_get_delegate_invoke (klass);
4049 m = mono_marshal_get_delegate_invoke (method, NULL);
4051 add_method (acfg, m);
4053 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4055 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4057 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4059 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4061 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4062 if (!is_ok (&error)) {
4063 mono_error_cleanup (&error);
4070 for (j = 0; j < cattr->num_attrs; ++j)
4071 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4073 if (j < cattr->num_attrs) {
4075 MonoMethod *wrapper;
4076 MonoMethod *del_invoke;
4078 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4079 invoke = mono_get_delegate_invoke (klass);
4080 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4081 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4082 add_method (acfg, wrapper);
4083 add_method (acfg, del_invoke);
4086 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4088 MonoGenericContext ctx;
4089 MonoMethod *inst, *gshared;
4092 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4095 method = mono_get_delegate_invoke (klass);
4096 create_gsharedvt_inst (acfg, method, &ctx);
4098 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4099 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4101 m = mono_marshal_get_delegate_invoke (inst, NULL);
4102 g_assert (m->is_inflated);
4104 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4105 add_extra_method (acfg, gshared);
4108 method = mono_get_delegate_begin_invoke (klass);
4110 create_gsharedvt_inst (acfg, method, &ctx);
4112 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4113 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4115 m = mono_marshal_get_delegate_begin_invoke (inst);
4116 g_assert (m->is_inflated);
4118 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4119 add_extra_method (acfg, gshared);
4123 method = mono_get_delegate_end_invoke (klass);
4125 create_gsharedvt_inst (acfg, method, &ctx);
4127 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4128 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4130 m = mono_marshal_get_delegate_end_invoke (inst);
4131 g_assert (m->is_inflated);
4133 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4134 add_extra_method (acfg, gshared);
4139 /* array access wrappers */
4140 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4144 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4145 klass = mono_class_get_checked (acfg->image, token, &error);
4148 mono_error_cleanup (&error);
4152 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4153 MonoMethod *m, *wrapper;
4155 /* Add runtime-invoke wrappers too */
4157 m = mono_class_get_method_from_name (klass, "Get", -1);
4159 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4160 add_extra_method (acfg, wrapper);
4161 if (!acfg->aot_opts.llvm_only)
4162 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4164 m = mono_class_get_method_from_name (klass, "Set", -1);
4166 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4167 add_extra_method (acfg, wrapper);
4168 if (!acfg->aot_opts.llvm_only)
4169 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4173 /* Synchronized wrappers */
4174 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4176 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4177 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4178 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4180 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4181 if (method->is_generic) {
4183 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4185 MonoGenericContext ctx;
4186 MonoMethod *inst, *gshared, *m;
4189 * Create a generic wrapper for a generic instance, and AOT that.
4191 create_gsharedvt_inst (acfg, method, &ctx);
4192 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4193 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4194 m = mono_marshal_get_synchronized_wrapper (inst);
4195 g_assert (m->is_inflated);
4196 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4197 add_method (acfg, gshared);
4199 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4204 /* pinvoke wrappers */
4205 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4208 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4210 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4211 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4213 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4214 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4215 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4218 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4219 if (acfg->aot_opts.llvm_only) {
4220 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4221 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4226 /* native-to-managed wrappers */
4227 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4230 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4231 MonoCustomAttrInfo *cattr;
4234 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4235 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4238 * Only generate native-to-managed wrappers for methods which have an
4239 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4240 * name to avoid defining a new assembly to contain it.
4242 cattr = mono_custom_attrs_from_method_checked (method, &error);
4243 if (!is_ok (&error)) {
4244 char *name = mono_method_get_full_name (method);
4245 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4250 for (j = 0; j < cattr->num_attrs; ++j)
4251 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4253 if (j < cattr->num_attrs) {
4254 MonoCustomAttrEntry *e = &cattr->attrs [j];
4255 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4256 const char *p = (const char*)e->data;
4258 int slen, num_named, named_type;
4262 char *export_name = NULL;
4263 MonoMethod *wrapper;
4265 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4266 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4267 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4268 mono_method_full_name (method, TRUE));
4272 g_assert (sig->param_count == 1);
4273 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4276 * Decode the cattr manually since we can't create objects
4277 * during aot compilation.
4283 /* From load_cattr_value () in reflection.c */
4284 slen = mono_metadata_decode_value (p, &p);
4285 n = (char *)g_memdup (p, slen + 1);
4287 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4289 mono_error_assert_ok (&error);
4292 klass = mono_class_from_mono_type (t);
4293 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4297 num_named = read16 (p);
4300 g_assert (num_named < 2);
4301 if (num_named == 1) {
4305 /* parse ExportSymbol attribute */
4307 named_type = *named;
4309 /* data_type = *named; */
4312 name_len = mono_metadata_decode_blob_size (named, &named);
4313 name = (char *)g_malloc (name_len + 1);
4314 memcpy (name, named, name_len);
4315 name [name_len] = 0;
4318 g_assert (named_type == 0x54);
4319 g_assert (!strcmp (name, "ExportSymbol"));
4321 /* load_cattr_value (), string case */
4322 g_assert (*named != (char)0xff);
4323 slen = mono_metadata_decode_value (named, &named);
4324 export_name = (char *)g_malloc (slen + 1);
4325 memcpy (export_name, named, slen);
4326 export_name [slen] = 0;
4330 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4331 add_method (acfg, wrapper);
4333 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4338 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4339 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4340 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4344 /* StructureToPtr/PtrToStructure wrappers */
4345 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4349 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4350 klass = mono_class_get_checked (acfg->image, token, &error);
4353 mono_error_cleanup (&error);
4357 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4358 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4359 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4360 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4366 has_type_vars (MonoClass *klass)
4368 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4371 return has_type_vars (klass->element_class);
4372 if (mono_class_is_ginst (klass)) {
4373 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4374 if (context->class_inst) {
4377 for (i = 0; i < context->class_inst->type_argc; ++i)
4378 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4382 if (mono_class_is_gtd (klass))
4388 is_vt_inst (MonoGenericInst *inst)
4392 for (i = 0; i < inst->type_argc; ++i) {
4393 MonoType *t = inst->type_argv [i];
4394 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4401 method_has_type_vars (MonoMethod *method)
4403 if (has_type_vars (method->klass))
4406 if (method->is_inflated) {
4407 MonoGenericContext *context = mono_method_get_context (method);
4408 if (context->method_inst) {
4411 for (i = 0; i < context->method_inst->type_argc; ++i)
4412 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4420 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4422 return opts->mode == MONO_AOT_MODE_FULL;
4426 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4428 return opts->mode == MONO_AOT_MODE_HYBRID;
4431 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4434 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4436 /* This might lead to a huge code blowup so only do it if neccesary */
4437 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4440 add_generic_class_with_depth (acfg, klass, 0, ref);
4444 check_type_depth (MonoType *t, int depth)
4452 case MONO_TYPE_GENERICINST: {
4453 MonoGenericClass *gklass = t->data.generic_class;
4454 MonoGenericInst *ginst = gklass->context.class_inst;
4457 for (i = 0; i < ginst->type_argc; ++i) {
4458 if (check_type_depth (ginst->type_argv [i], depth + 1))
4472 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4475 * add_generic_class:
4477 * Add all methods of a generic class.
4480 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4483 MonoClassField *field;
4485 gboolean use_gsharedvt = FALSE;
4487 if (!acfg->ginst_hash)
4488 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4490 mono_class_init (klass);
4492 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4495 if (has_type_vars (klass))
4498 if (!mono_class_is_ginst (klass) && !klass->rank)
4501 if (mono_class_has_failure (klass))
4504 if (!acfg->ginst_hash)
4505 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4507 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4510 if (check_type_depth (&klass->byval_arg, 0))
4513 if (acfg->aot_opts.log_generics)
4514 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4516 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4519 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4520 * Enable this only for some classes since gsharedvt might not support all methods.
4522 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst && is_vt_inst (mono_class_get_generic_class (klass)->context.class_inst) &&
4523 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4524 use_gsharedvt = TRUE;
4527 while ((method = mono_class_get_methods (klass, &iter))) {
4528 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4530 * This is partial sharing, and we can't handle it yet
4535 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4537 add_types_from_method_header (acfg, method);
4541 if (method->is_generic)
4546 * FIXME: Instances which are referenced by these methods are not added,
4547 * for example Array.Resize<int> for List<int>.Add ().
4549 add_extra_method_with_depth (acfg, method, depth + 1);
4553 while ((field = mono_class_get_fields (klass, &iter))) {
4554 if (field->type->type == MONO_TYPE_GENERICINST)
4555 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4558 if (klass->delegate) {
4559 method = mono_get_delegate_invoke (klass);
4561 method = mono_marshal_get_delegate_invoke (method, NULL);
4563 if (acfg->aot_opts.log_generics)
4564 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4566 add_method (acfg, method);
4569 /* Add superclasses */
4571 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4574 * For ICollection<T>, add instances of the helper methods
4575 * in Array, since a T[] could be cast to ICollection<T>.
4577 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4578 (!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"))) {
4579 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4580 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4584 if (!strcmp (klass->name, "IEnumerator`1"))
4585 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4587 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4589 /* Add the T[]/InternalEnumerator class */
4590 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4595 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4596 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4600 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4601 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4602 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4606 while ((method = mono_class_get_methods (array_class, &iter))) {
4607 if (strstr (method->name, name_prefix)) {
4608 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4610 add_extra_method_with_depth (acfg, m, depth);
4614 g_free (name_prefix);
4617 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4618 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4620 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4621 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4622 MonoGenericContext ctx;
4623 MonoType *args [16];
4625 memset (&ctx, 0, sizeof (ctx));
4627 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4629 args [0] = &tclass->byval_arg;
4630 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4632 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4633 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4635 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4636 MonoClass *gcomparer_inst;
4637 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4638 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4639 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4641 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4645 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4646 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4648 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4649 MonoClass *iface, *gcomparer, *iface_inst;
4650 MonoGenericContext ctx;
4651 MonoType *args [16];
4653 memset (&ctx, 0, sizeof (ctx));
4655 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4657 args [0] = &tclass->byval_arg;
4658 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4660 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4661 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4663 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4664 MonoClass *gcomparer_inst;
4667 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4668 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4669 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4670 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4674 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4675 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4676 MonoClass *enum_comparer;
4677 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4678 MonoGenericContext ctx;
4679 MonoType *args [16];
4681 if (mono_class_is_enum (tclass)) {
4682 MonoClass *enum_comparer_inst;
4685 memset (&ctx, 0, sizeof (ctx));
4686 args [0] = &tclass->byval_arg;
4687 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4689 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4690 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4691 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4692 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4696 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4697 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4698 MonoClass *comparer;
4699 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4700 MonoGenericContext ctx;
4701 MonoType *args [16];
4703 if (mono_class_is_enum (tclass)) {
4704 MonoClass *comparer_inst;
4707 memset (&ctx, 0, sizeof (ctx));
4708 args [0] = &tclass->byval_arg;
4709 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4711 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4712 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4713 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4714 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4720 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4723 MonoGenericContext ctx;
4724 MonoType *args [16];
4726 if (acfg->aot_opts.no_instances)
4729 memset (&ctx, 0, sizeof (ctx));
4731 for (i = 0; i < ninsts; ++i) {
4733 MonoClass *generic_inst;
4734 args [0] = insts [i];
4735 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4736 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4737 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4738 add_generic_class (acfg, generic_inst, force, "");
4743 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4746 MonoMethodHeader *header;
4747 MonoMethodSignature *sig;
4750 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4752 sig = mono_method_signature (method);
4755 for (j = 0; j < sig->param_count; ++j)
4756 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4757 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4760 header = mono_method_get_header_checked (method, &error);
4763 for (j = 0; j < header->num_locals; ++j)
4764 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4765 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4766 mono_metadata_free_mh (header);
4768 mono_error_cleanup (&error); /* FIXME report the error */
4774 * add_generic_instances:
4776 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4779 add_generic_instances (MonoAotCompile *acfg)
4784 MonoGenericContext *context;
4786 if (acfg->aot_opts.no_instances)
4789 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4791 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4792 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4795 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4796 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4797 mono_error_cleanup (&error);
4801 if (method->klass->image != acfg->image)
4804 context = mono_method_get_context (method);
4806 if (context && ((context->class_inst && context->class_inst->is_open)))
4810 * For open methods, create an instantiation which can be passed to the JIT.
4811 * FIXME: Handle class_inst as well.
4813 if (context && context->method_inst && context->method_inst->is_open) {
4815 MonoGenericContext shared_context;
4816 MonoGenericInst *inst;
4817 MonoType **type_argv;
4819 MonoMethod *declaring_method;
4820 gboolean supported = TRUE;
4822 /* Check that the context doesn't contain open constructed types */
4823 if (context->class_inst) {
4824 inst = context->class_inst;
4825 for (i = 0; i < inst->type_argc; ++i) {
4826 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)
4828 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4832 if (context->method_inst) {
4833 inst = context->method_inst;
4834 for (i = 0; i < inst->type_argc; ++i) {
4835 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)
4837 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4845 memset (&shared_context, 0, sizeof (MonoGenericContext));
4847 inst = context->class_inst;
4849 type_argv = g_new0 (MonoType*, inst->type_argc);
4850 for (i = 0; i < inst->type_argc; ++i) {
4851 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)
4852 type_argv [i] = &mono_defaults.object_class->byval_arg;
4854 type_argv [i] = inst->type_argv [i];
4857 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4861 inst = context->method_inst;
4863 type_argv = g_new0 (MonoType*, inst->type_argc);
4864 for (i = 0; i < inst->type_argc; ++i) {
4865 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)
4866 type_argv [i] = &mono_defaults.object_class->byval_arg;
4868 type_argv [i] = inst->type_argv [i];
4871 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4875 if (method->is_generic || mono_class_is_gtd (method->klass))
4876 declaring_method = method;
4878 declaring_method = mono_method_get_declaring_generic_method (method);
4880 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4881 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4885 * If the method is fully sharable, it was already added in place of its
4886 * generic definition.
4888 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4892 * FIXME: Partially shared methods are not shared here, so we end up with
4893 * many identical methods.
4895 add_extra_method (acfg, method);
4898 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4902 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4904 klass = mono_class_get_checked (acfg->image, token, &error);
4905 if (!klass || klass->rank) {
4906 mono_error_cleanup (&error);
4910 add_generic_class (acfg, klass, FALSE, "typespec");
4913 /* Add types of args/locals */
4914 for (i = 0; i < acfg->methods->len; ++i) {
4915 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4916 add_types_from_method_header (acfg, method);
4919 if (acfg->image == mono_defaults.corlib) {
4921 MonoType *insts [256];
4924 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4925 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4926 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4927 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4928 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4929 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4930 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4931 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4932 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4933 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4934 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4937 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4938 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4940 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4941 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4943 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4945 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4947 MonoClass *enum_comparer;
4948 MonoType *insts [16];
4952 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4953 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4954 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4955 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4956 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4957 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4960 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4961 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4962 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4965 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4966 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4967 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4969 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4971 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4972 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4973 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4976 /* Add instances of the array generic interfaces for primitive types */
4977 /* This will add instances of the InternalArray_ helper methods in Array too */
4978 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4980 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4982 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4984 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4986 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4988 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4991 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4992 * used for all instances of GetGenericValueImpl by the AOT runtime.
4995 MonoGenericContext ctx;
4996 MonoType *args [16];
4997 MonoMethod *get_method;
4998 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5000 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5004 memset (&ctx, 0, sizeof (ctx));
5005 args [0] = &mono_defaults.object_class->byval_arg;
5006 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5007 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5008 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5012 /* Same for CompareExchange<T>/Exchange<T> */
5014 MonoGenericContext ctx;
5015 MonoType *args [16];
5017 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5018 gpointer iter = NULL;
5020 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5021 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5023 memset (&ctx, 0, sizeof (ctx));
5024 args [0] = &mono_defaults.object_class->byval_arg;
5025 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5026 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5027 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5032 /* Same for Volatile.Read/Write<T> */
5034 MonoGenericContext ctx;
5035 MonoType *args [16];
5037 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5038 gpointer iter = NULL;
5040 if (volatile_klass) {
5041 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5042 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5044 memset (&ctx, 0, sizeof (ctx));
5045 args [0] = &mono_defaults.object_class->byval_arg;
5046 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5047 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5048 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5054 /* object[] accessor wrappers. */
5055 for (i = 1; i < 4; ++i) {
5056 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5059 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5062 m = mono_marshal_get_array_accessor_wrapper (m);
5063 add_extra_method (acfg, m);
5065 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5068 m = mono_marshal_get_array_accessor_wrapper (m);
5069 add_extra_method (acfg, m);
5071 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5074 m = mono_marshal_get_array_accessor_wrapper (m);
5075 add_extra_method (acfg, m);
5081 * is_direct_callable:
5083 * Return whenever the method identified by JI is directly callable without
5084 * going through the PLT.
5087 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5089 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5090 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5092 gboolean direct_callable = TRUE;
5094 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5095 direct_callable = FALSE;
5096 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5097 // FIXME: Maybe call the wrapper directly ?
5098 direct_callable = FALSE;
5100 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5101 /* Disable this so all calls go through load_method (), see the
5102 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5103 * mono_debugger_agent_init ().
5105 direct_callable = FALSE;
5108 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5109 /* sgen does some initialization when the allocator method is created */
5110 direct_callable = FALSE;
5111 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5112 /* we don't know at compile time whether sgen is concurrent or not */
5113 direct_callable = FALSE;
5115 if (direct_callable)
5118 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5119 if (acfg->aot_opts.direct_pinvoke)
5121 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5122 if (acfg->aot_opts.direct_icalls)
5130 #ifdef MONO_ARCH_AOT_SUPPORTED
5132 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5134 MonoImage *image = method->klass->image;
5135 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5136 MonoTableInfo *tables = image->tables;
5137 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5138 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5139 guint32 im_cols [MONO_IMPLMAP_SIZE];
5142 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5146 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5149 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5151 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5154 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5156 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5162 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5169 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5171 if (a->native_offset == b->native_offset)
5172 return a->il_offset - b->il_offset;
5174 return a->native_offset - b->native_offset;
5178 * compute_line_numbers:
5180 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5183 static MonoDebugSourceLocation**
5184 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5186 MonoDebugMethodInfo *minfo;
5187 MonoDebugLineNumberEntry *ln_array;
5188 MonoDebugSourceLocation *loc;
5189 int i, prev_line, prev_il_offset;
5190 int *native_to_il_offset = NULL;
5191 MonoDebugSourceLocation **res;
5194 minfo = mono_debug_lookup_method (method);
5197 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5198 if (debug_info->code_size != code_size)
5201 g_assert (code_size);
5203 /* Compute the native->IL offset mapping */
5205 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5206 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5208 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5210 native_to_il_offset = g_new0 (int, code_size + 1);
5212 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5214 MonoDebugLineNumberEntry *lne = &ln_array [i];
5217 for (j = 0; j < lne->native_offset; ++j)
5218 native_to_il_offset [j] = -1;
5221 if (i < debug_info->num_line_numbers - 1) {
5222 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5224 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5225 native_to_il_offset [j] = lne->il_offset;
5227 for (j = lne->native_offset; j < code_size; ++j)
5228 native_to_il_offset [j] = lne->il_offset;
5233 /* Compute the native->line number mapping */
5234 res = g_new0 (MonoDebugSourceLocation*, code_size);
5235 prev_il_offset = -1;
5238 for (i = 0; i < code_size; ++i) {
5239 int il_offset = native_to_il_offset [i];
5241 if (il_offset == -1 || il_offset == prev_il_offset)
5243 prev_il_offset = il_offset;
5244 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5245 if (!(loc && loc->source_file))
5247 if (loc->row == prev_line) {
5248 mono_debug_symfile_free_location (loc);
5251 prev_line = loc->row;
5252 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5254 /* This will cover the prolog too */
5264 get_file_index (MonoAotCompile *acfg, const char *source_file)
5268 // FIXME: Free these
5269 if (!acfg->dwarf_ln_filenames)
5270 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5271 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5273 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5274 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5275 emit_unset_mode (acfg);
5276 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5288 * emit_and_reloc_code:
5290 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5291 * is true, calls are made through the GOT too. This is used for emitting trampolines
5292 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5293 * since trampolines are needed to make PTL work.
5296 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5298 int i, pindex, start_index;
5300 MonoJumpInfo *patch_info;
5301 MonoDebugSourceLocation **locs = NULL;
5302 gboolean skip, prologue_end = FALSE;
5303 #ifdef MONO_ARCH_AOT_SUPPORTED
5304 gboolean direct_call, external_call;
5306 const char *direct_call_target = 0;
5307 const char *direct_pinvoke;
5310 if (acfg->gas_line_numbers && method && debug_info) {
5311 locs = compute_line_numbers (method, code_len, debug_info);
5313 int findex = get_file_index (acfg, "<unknown>");
5314 emit_unset_mode (acfg);
5315 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5319 /* Collect and sort relocations */
5320 patches = g_ptr_array_new ();
5321 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5322 g_ptr_array_add (patches, patch_info);
5323 g_ptr_array_sort (patches, compare_patches);
5326 for (i = 0; i < code_len; i += INST_LEN) {
5328 for (pindex = start_index; pindex < patches->len; ++pindex) {
5329 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5330 if (patch_info->ip.i >= i)
5334 if (locs && locs [i]) {
5335 MonoDebugSourceLocation *loc = locs [i];
5337 const char *options;
5339 findex = get_file_index (acfg, loc->source_file);
5340 emit_unset_mode (acfg);
5342 options = " prologue_end";
5345 prologue_end = TRUE;
5346 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5347 mono_debug_symfile_free_location (loc);
5351 #ifdef MONO_ARCH_AOT_SUPPORTED
5352 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5353 start_index = pindex;
5355 switch (patch_info->type) {
5356 case MONO_PATCH_INFO_NONE:
5358 case MONO_PATCH_INFO_GOT_OFFSET: {
5361 arch_emit_got_offset (acfg, code + i, &code_size);
5362 i += code_size - INST_LEN;
5364 patch_info->type = MONO_PATCH_INFO_NONE;
5367 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5368 int code_size, index;
5369 char *selector = (char *)patch_info->data.target;
5371 if (!acfg->objc_selector_to_index)
5372 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5373 if (!acfg->objc_selectors)
5374 acfg->objc_selectors = g_ptr_array_new ();
5375 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5379 index = acfg->objc_selector_index;
5380 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5381 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5382 acfg->objc_selector_index ++;
5385 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5386 i += code_size - INST_LEN;
5388 patch_info->type = MONO_PATCH_INFO_NONE;
5393 * If this patch is a call, try emitting a direct call instead of
5394 * through a PLT entry. This is possible if the called method is in
5395 * the same assembly and requires no initialization.
5397 direct_call = FALSE;
5398 external_call = FALSE;
5399 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5400 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5401 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5402 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5404 direct_call_target = callee_cfg->asm_symbol;
5405 patch_info->type = MONO_PATCH_INFO_NONE;
5406 acfg->stats.direct_calls ++;
5409 acfg->stats.all_calls ++;
5410 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5411 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5412 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5413 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5415 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5416 if (direct_pinvoke) {
5418 g_assert (strlen (direct_pinvoke) < 1000);
5419 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5422 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5423 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5424 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5425 /* Call to a C function implementing a jit icall */
5427 external_call = TRUE;
5428 g_assert (strlen (sym) < 1000);
5429 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5431 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5432 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5433 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5434 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5435 /* Call to a jit icall without a wrapper */
5437 external_call = TRUE;
5438 g_assert (strlen (sym) < 1000);
5439 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5444 patch_info->type = MONO_PATCH_INFO_NONE;
5445 acfg->stats.direct_calls ++;
5448 if (!got_only && !direct_call) {
5449 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5451 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5453 direct_call_target = plt_entry->symbol;
5455 /* Nullify the patch */
5456 patch_info->type = MONO_PATCH_INFO_NONE;
5457 plt_entry->jit_used = TRUE;
5464 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5465 i += call_size - INST_LEN;
5469 got_slot = get_got_offset (acfg, FALSE, patch_info);
5471 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5472 i += code_size - INST_LEN;
5478 #endif /* MONO_ARCH_AOT_SUPPORTED */
5481 /* Find next patch */
5483 for (pindex = start_index; pindex < patches->len; ++pindex) {
5484 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5485 if (patch_info->ip.i >= i)
5489 /* Try to emit multiple bytes at once */
5490 if (pindex < patches->len && patch_info->ip.i > i) {
5493 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5494 if (locs && locs [limit])
5498 emit_code_bytes (acfg, code + i, limit - i);
5499 i = limit - INST_LEN;
5501 emit_code_bytes (acfg, code + i, INST_LEN);
5506 g_ptr_array_free (patches, TRUE);
5513 * Return a modified version of S which only includes characters permissible in symbols.
5516 sanitize_symbol (MonoAotCompile *acfg, char *s)
5518 gboolean process = FALSE;
5527 for (i = 0; i < len; ++i)
5528 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5533 gs = g_string_sized_new (len);
5534 for (i = 0; i < len; ++i) {
5536 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5537 g_string_append_c (gs, c);
5538 } else if (c > 0x7f) {
5539 /* multi-byte utf8 */
5540 g_string_append_printf (gs, "_0x%x", c);
5543 while (c >> 6 == 0x2) {
5544 g_string_append_printf (gs, "%x", c);
5548 g_string_append_printf (gs, "_");
5551 g_string_append_c (gs, '_');
5555 res = mono_mempool_strdup (acfg->mempool, gs->str);
5556 g_string_free (gs, TRUE);
5561 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5563 char *name1, *name2, *cached;
5564 int i, j, len, count;
5565 MonoMethod *cached_method;
5567 name1 = mono_method_full_name (method, TRUE);
5570 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5571 if ((!prefix || !*prefix) && name1 [0] == 'L')
5575 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5576 char adjustedPrefix [MAX_SYMBOL_SIZE];
5577 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5580 len = strlen (name1);
5581 name2 = (char *)malloc (strlen (prefix) + len + 16);
5582 memcpy (name2, prefix, strlen (prefix));
5583 j = strlen (prefix);
5584 for (i = 0; i < len; ++i) {
5585 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5587 } else if (isalnum (name1 [i])) {
5588 name2 [j ++] = name1 [i];
5589 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5591 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5594 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5604 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5605 if (!(cached_method && cached_method != method))
5607 sprintf (name2 + j, "_%d", count);
5611 cached = g_strdup (name2);
5612 g_hash_table_insert (cache, cached, method);
5618 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5623 char *debug_sym = NULL;
5624 char *symbol = NULL;
5625 int func_alignment = AOT_FUNC_ALIGNMENT;
5628 method = cfg->orig_method;
5629 code = cfg->native_code;
5631 method_index = get_method_index (acfg, method);
5632 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5634 /* Make the labels local */
5635 emit_section_change (acfg, ".text", 0);
5636 emit_alignment_code (acfg, func_alignment);
5638 if (acfg->global_symbols && acfg->need_no_dead_strip)
5639 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5641 emit_label (acfg, cfg->asm_symbol);
5643 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5645 * Write a C style symbol for every method, this has two uses:
5646 * - it works on platforms where the dwarf debugging info is not
5648 * - it allows the setting of breakpoints of aot-ed methods.
5650 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5651 cfg->asm_debug_symbol = g_strdup (debug_sym);
5653 if (acfg->need_no_dead_strip)
5654 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5655 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5656 emit_label (acfg, debug_sym);
5659 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5661 /* Emit a global symbol for the method */
5662 emit_global_inner (acfg, export_name, TRUE);
5663 emit_label (acfg, export_name);
5666 if (cfg->verbose_level > 0)
5667 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5669 acfg->stats.code_size += cfg->code_len;
5671 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5673 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 ()));
5677 if (acfg->aot_opts.write_symbols) {
5679 emit_symbol_size (acfg, debug_sym, ".");
5681 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5685 emit_label (acfg, symbol);
5692 * Encode PATCH_INFO into its disk representation.
5695 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5699 switch (patch_info->type) {
5700 case MONO_PATCH_INFO_NONE:
5702 case MONO_PATCH_INFO_IMAGE:
5703 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5705 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5706 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5707 case MONO_PATCH_INFO_GC_NURSERY_START:
5708 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5710 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5711 encode_value (patch_info->data.index, p, &p);
5713 case MONO_PATCH_INFO_METHOD_REL:
5714 encode_value ((gint)patch_info->data.offset, p, &p);
5716 case MONO_PATCH_INFO_SWITCH: {
5717 gpointer *table = (gpointer *)patch_info->data.table->table;
5720 encode_value (patch_info->data.table->table_size, p, &p);
5721 for (k = 0; k < patch_info->data.table->table_size; k++)
5722 encode_value ((int)(gssize)table [k], p, &p);
5725 case MONO_PATCH_INFO_METHODCONST:
5726 case MONO_PATCH_INFO_METHOD:
5727 case MONO_PATCH_INFO_METHOD_JUMP:
5728 case MONO_PATCH_INFO_ICALL_ADDR:
5729 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5730 case MONO_PATCH_INFO_METHOD_RGCTX:
5731 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5732 encode_method_ref (acfg, patch_info->data.method, p, &p);
5734 case MONO_PATCH_INFO_AOT_JIT_INFO:
5735 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5736 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5737 encode_value (patch_info->data.index, p, &p);
5739 case MONO_PATCH_INFO_INTERNAL_METHOD:
5740 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5741 guint32 len = strlen (patch_info->data.name);
5743 encode_value (len, p, &p);
5745 memcpy (p, patch_info->data.name, len);
5750 case MONO_PATCH_INFO_LDSTR: {
5751 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5752 guint32 token = patch_info->data.token->token;
5753 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5754 encode_value (image_index, p, &p);
5755 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5758 case MONO_PATCH_INFO_RVA:
5759 case MONO_PATCH_INFO_DECLSEC:
5760 case MONO_PATCH_INFO_LDTOKEN:
5761 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5762 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5763 encode_value (patch_info->data.token->token, p, &p);
5764 encode_value (patch_info->data.token->has_context, p, &p);
5765 if (patch_info->data.token->has_context)
5766 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5768 case MONO_PATCH_INFO_EXC_NAME: {
5769 MonoClass *ex_class;
5772 mono_class_load_from_name (mono_defaults.exception_class->image,
5773 "System", (const char *)patch_info->data.target);
5774 encode_klass_ref (acfg, ex_class, p, &p);
5777 case MONO_PATCH_INFO_R4:
5778 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5780 case MONO_PATCH_INFO_R8:
5781 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5782 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5784 case MONO_PATCH_INFO_VTABLE:
5785 case MONO_PATCH_INFO_CLASS:
5786 case MONO_PATCH_INFO_IID:
5787 case MONO_PATCH_INFO_ADJUSTED_IID:
5788 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5790 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5791 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5792 if (patch_info->data.del_tramp->method) {
5793 encode_value (1, p, &p);
5794 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5796 encode_value (0, p, &p);
5798 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5800 case MONO_PATCH_INFO_FIELD:
5801 case MONO_PATCH_INFO_SFLDA:
5802 encode_field_info (acfg, patch_info->data.field, p, &p);
5804 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5806 case MONO_PATCH_INFO_RGCTX_FETCH:
5807 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5808 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5813 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5814 * reference the same method, so encode the method only once.
5816 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5818 buf2 = (guint8 *)g_malloc (1024);
5821 encode_method_ref (acfg, entry->method, p2, &p2);
5822 g_assert (p2 - buf2 < 1024);
5824 offset = add_to_blob (acfg, buf2, p2 - buf2);
5827 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5832 encode_value (offset, p, &p);
5833 g_assert ((int)entry->info_type < 256);
5834 g_assert (entry->data->type < 256);
5835 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5836 encode_patch (acfg, entry->data, p, &p);
5839 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5840 case MONO_PATCH_INFO_AOT_MODULE:
5842 case MONO_PATCH_INFO_SIGNATURE:
5843 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5844 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5846 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5847 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5848 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5850 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5851 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5854 encode_method_ref (acfg, info->method, p, &p);
5855 encode_value (info->num_entries, p, &p);
5856 for (i = 0; i < info->num_entries; ++i) {
5857 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5859 encode_value (template_->info_type, p, &p);
5860 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5861 case MONO_PATCH_INFO_CLASS:
5862 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5864 case MONO_PATCH_INFO_FIELD:
5865 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5868 g_assert_not_reached ();
5874 case MONO_PATCH_INFO_LDSTR_LIT: {
5875 const char *s = (const char *)patch_info->data.target;
5876 int len = strlen (s);
5878 encode_value (len, p, &p);
5879 memcpy (p, s, len + 1);
5883 case MONO_PATCH_INFO_VIRT_METHOD:
5884 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5885 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5887 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5888 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5891 g_warning ("unable to handle jump info %d", patch_info->type);
5892 g_assert_not_reached ();
5899 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5902 guint32 pindex, offset;
5903 MonoJumpInfo *patch_info;
5905 encode_value (n_patches, p, &p);
5907 for (pindex = 0; pindex < patches->len; ++pindex) {
5908 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5910 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5914 offset = get_got_offset (acfg, llvm, patch_info);
5915 encode_value (offset, p, &p);
5922 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5925 int pindex, buf_size, n_patches;
5927 MonoJumpInfo *patch_info;
5928 guint32 method_index;
5930 guint32 first_got_offset;
5932 method = cfg->orig_method;
5934 method_index = get_method_index (acfg, method);
5936 /* Sort relocations */
5937 patches = g_ptr_array_new ();
5938 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5939 g_ptr_array_add (patches, patch_info);
5940 g_ptr_array_sort (patches, compare_patches);
5942 first_got_offset = acfg->cfgs [method_index]->got_offset;
5944 /**********************/
5945 /* Encode method info */
5946 /**********************/
5948 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5949 p = buf = (guint8 *)g_malloc (buf_size);
5951 if (mono_class_get_cctor (method->klass)) {
5952 encode_value (1, p, &p);
5953 encode_klass_ref (acfg, method->klass, p, &p);
5955 /* Not needed when loading the method */
5956 encode_value (0, p, &p);
5959 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5962 for (pindex = 0; pindex < patches->len; ++pindex) {
5963 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5965 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5966 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5967 patch_info->type = MONO_PATCH_INFO_NONE;
5972 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5973 /* Stored in a GOT slot initialized at module load time */
5974 patch_info->type = MONO_PATCH_INFO_NONE;
5978 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5979 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5980 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5981 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5982 /* Stored in a GOT slot initialized at module load time */
5983 patch_info->type = MONO_PATCH_INFO_NONE;
5987 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5988 /* Calls are made through the PLT */
5989 patch_info->type = MONO_PATCH_INFO_NONE;
5997 g_assert (cfg->has_got_slots);
5999 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6001 g_ptr_array_free (patches, TRUE);
6003 acfg->stats.info_size += p - buf;
6005 g_assert (p - buf < buf_size);
6007 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6012 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6014 guint32 cache_index;
6017 /* Reuse the unwind module to canonize and store unwind info entries */
6018 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6020 /* Use +/- 1 to distinguish 0s from missing entries */
6021 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6029 * It would be easier to use assembler symbols, but the caller needs an
6032 offset = acfg->unwind_info_offset;
6033 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6034 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6037 encode_value (encoded_len, p, &p);
6039 acfg->unwind_info_offset += encoded_len + (p - buf);
6045 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6048 guint32 debug_info_size, seq_points_size;
6050 MonoMethodHeader *header;
6051 guint8 *p, *buf, *debug_info;
6052 MonoJitInfo *jinfo = cfg->jit_info;
6054 gboolean use_unwind_ops = FALSE;
6055 MonoSeqPointInfo *seq_points;
6057 code = cfg->native_code;
6058 header = cfg->header;
6060 if (!acfg->aot_opts.nodebug) {
6061 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6064 debug_info_size = 0;
6067 seq_points = cfg->seq_point_info;
6068 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6070 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6072 p = buf = (guint8 *)g_malloc (buf_size);
6074 use_unwind_ops = cfg->unwind_ops != NULL;
6076 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);
6078 encode_value (flags, p, &p);
6080 if (use_unwind_ops) {
6081 guint32 encoded_len;
6083 guint32 unwind_desc;
6085 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6087 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6088 encode_value (unwind_desc, p, &p);
6092 encode_value (jinfo->unwind_info, p, &p);
6095 /*Encode the number of holes before the number of clauses to make decoding easier*/
6096 if (jinfo->has_try_block_holes) {
6097 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6098 encode_value (table->num_holes, p, &p);
6101 if (jinfo->has_arch_eh_info) {
6103 * In AOT mode, the code length is calculated from the address of the previous method,
6104 * which could include alignment padding, so calculating the start of the epilog as
6105 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6107 encode_value (jinfo->code_size, p, &p);
6110 /* Exception table */
6111 if (cfg->compile_llvm) {
6113 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6114 * since the information is only available to llc. Instead, we let llc save the data
6115 * into the LSDA, and read it from there at runtime.
6117 /* The assembly might be CIL stripped so emit the data ourselves */
6118 if (header->num_clauses)
6119 encode_value (header->num_clauses, p, &p);
6121 for (k = 0; k < header->num_clauses; ++k) {
6122 MonoExceptionClause *clause;
6124 clause = &header->clauses [k];
6126 encode_value (clause->flags, p, &p);
6127 if (clause->data.catch_class) {
6128 encode_value (1, p, &p);
6129 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6131 encode_value (0, p, &p);
6134 /* Emit the IL ranges too, since they might not be available at runtime */
6135 encode_value (clause->try_offset, p, &p);
6136 encode_value (clause->try_len, p, &p);
6137 encode_value (clause->handler_offset, p, &p);
6138 encode_value (clause->handler_len, p, &p);
6140 /* Emit a list of nesting clauses */
6141 for (i = 0; i < header->num_clauses; ++i) {
6143 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6145 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6147 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6148 encode_value (i, p, &p);
6150 encode_value (-1, p, &p);
6153 if (jinfo->num_clauses)
6154 encode_value (jinfo->num_clauses, p, &p);
6156 for (k = 0; k < jinfo->num_clauses; ++k) {
6157 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6159 encode_value (ei->flags, p, &p);
6160 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6161 /* Not used for catch clauses */
6162 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6163 encode_value (ei->exvar_offset, p, &p);
6165 encode_value (ei->exvar_offset, p, &p);
6168 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6169 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6171 if (ei->data.catch_class) {
6175 buf2 = (guint8 *)g_malloc (4096);
6177 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6179 g_assert (len < 4096);
6180 encode_value (len, p, &p);
6181 memcpy (p, buf2, len);
6185 encode_value (0, p, &p);
6189 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6190 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6191 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6195 if (jinfo->has_try_block_holes) {
6196 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6197 for (i = 0; i < table->num_holes; ++i) {
6198 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6199 encode_value (hole->clause, p, &p);
6200 encode_value (hole->length, p, &p);
6201 encode_value (hole->offset, p, &p);
6205 if (jinfo->has_arch_eh_info) {
6206 MonoArchEHJitInfo *eh_info;
6208 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6209 encode_value (eh_info->stack_size, p, &p);
6210 encode_value (eh_info->epilog_size, p, &p);
6213 if (jinfo->has_generic_jit_info) {
6214 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6215 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6219 encode_value (gi->nlocs, p, &p);
6221 for (i = 0; i < gi->nlocs; ++i) {
6222 MonoDwarfLocListEntry *entry = &gi->locations [i];
6224 encode_value (entry->is_reg ? 1 : 0, p, &p);
6225 encode_value (entry->reg, p, &p);
6227 encode_value (entry->offset, p, &p);
6229 g_assert (entry->from == 0);
6231 encode_value (entry->from, p, &p);
6232 encode_value (entry->to, p, &p);
6235 if (!cfg->compile_llvm) {
6236 encode_value (gi->has_this ? 1 : 0, p, &p);
6237 encode_value (gi->this_reg, p, &p);
6238 encode_value (gi->this_offset, p, &p);
6243 * Need to encode jinfo->method too, since it is not equal to 'method'
6244 * when using generic sharing.
6246 buf2 = (guint8 *)g_malloc (4096);
6248 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6250 g_assert (len < 4096);
6251 encode_value (len, p, &p);
6252 memcpy (p, buf2, len);
6256 if (gsctx && gsctx->is_gsharedvt) {
6257 encode_value (1, p, &p);
6259 encode_value (0, p, &p);
6263 if (seq_points_size)
6264 p += mono_seq_point_info_write (seq_points, p);
6266 g_assert (debug_info_size < buf_size);
6268 encode_value (debug_info_size, p, &p);
6269 if (debug_info_size) {
6270 memcpy (p, debug_info, debug_info_size);
6271 p += debug_info_size;
6272 g_free (debug_info);
6277 encode_value (cfg->gc_map_size, p, &p);
6278 /* The GC map requires 4 bytes of alignment */
6279 while ((gsize)p % 4)
6281 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6282 p += cfg->gc_map_size;
6285 acfg->stats.ex_info_size += p - buf;
6287 g_assert (p - buf < buf_size);
6290 /* The GC Map requires 4 byte alignment */
6291 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6296 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6299 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6301 int i, buf_size, res;
6302 gboolean no_special_static, cant_encode;
6303 gpointer iter = NULL;
6306 mono_error_cleanup (&error);
6310 p = buf = (guint8 *)g_malloc (buf_size);
6312 /* Mark as unusable */
6313 encode_value (-1, p, &p);
6315 res = add_to_blob (acfg, buf, p - buf);
6321 buf_size = 10240 + (klass->vtable_size * 16);
6322 p = buf = (guint8 *)g_malloc (buf_size);
6326 mono_class_init (klass);
6328 mono_class_get_nested_types (klass, &iter);
6329 g_assert (klass->nested_classes_inited);
6331 mono_class_setup_vtable (klass);
6334 * Emit all the information which is required for creating vtables so
6335 * the runtime does not need to create the MonoMethod structures which
6336 * take up a lot of space.
6339 no_special_static = !mono_class_has_special_static_fields (klass);
6341 /* Check whenever we have enough info to encode the vtable */
6342 cant_encode = FALSE;
6343 for (i = 0; i < klass->vtable_size; ++i) {
6344 MonoMethod *cm = klass->vtable [i];
6346 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6350 mono_class_has_finalizer (klass);
6351 if (mono_class_has_failure (klass))
6354 if (mono_class_is_gtd (klass) || cant_encode) {
6355 encode_value (-1, p, &p);
6357 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6358 encode_value (klass->vtable_size, p, &p);
6359 encode_value ((mono_class_is_gtd (klass) ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | (has_nested ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6360 if (klass->has_cctor)
6361 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6362 if (klass->has_finalize)
6363 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6365 encode_value (klass->instance_size, p, &p);
6366 encode_value (mono_class_data_size (klass), p, &p);
6367 encode_value (klass->packing_size, p, &p);
6368 encode_value (klass->min_align, p, &p);
6370 for (i = 0; i < klass->vtable_size; ++i) {
6371 MonoMethod *cm = klass->vtable [i];
6374 encode_method_ref (acfg, cm, p, &p);
6376 encode_value (0, p, &p);
6380 acfg->stats.class_info_size += p - buf;
6382 g_assert (p - buf < buf_size);
6383 res = add_to_blob (acfg, buf, p - buf);
6390 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6392 char *debug_sym = NULL;
6395 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6396 /* Need to add a prefix to create unique symbols */
6397 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6399 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6400 prefix = mangle_symbol_alloc ("plt_");
6402 prefix = g_strdup ("plt_");
6407 case MONO_PATCH_INFO_METHOD:
6408 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6410 case MONO_PATCH_INFO_INTERNAL_METHOD:
6411 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6413 case MONO_PATCH_INFO_RGCTX_FETCH:
6414 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6416 case MONO_PATCH_INFO_ICALL_ADDR:
6417 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6418 char *s = get_debug_sym (ji->data.method, "", cache);
6420 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6424 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6425 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6433 return sanitize_symbol (acfg, debug_sym);
6437 * Calls made from AOTed code are routed through a table of jumps similar to the
6438 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6439 * control to the AOT runtime through a trampoline.
6442 emit_plt (MonoAotCompile *acfg)
6446 if (acfg->aot_opts.llvm_only) {
6447 g_assert (acfg->plt_offset == 1);
6453 emit_section_change (acfg, ".text", 0);
6454 emit_alignment_code (acfg, 16);
6455 emit_info_symbol (acfg, "plt");
6456 emit_label (acfg, acfg->plt_symbol);
6458 for (i = 0; i < acfg->plt_offset; ++i) {
6459 char *debug_sym = NULL;
6460 MonoPltEntry *plt_entry = NULL;
6464 * The first plt entry is unused.
6468 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6470 debug_sym = plt_entry->debug_sym;
6472 if (acfg->thumb_mixed && !plt_entry->jit_used)
6473 /* Emit only a thumb version */
6476 /* Skip plt entries not actually called */
6477 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6480 if (acfg->llvm && !acfg->thumb_mixed) {
6481 emit_label (acfg, plt_entry->llvm_symbol);
6483 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6484 #if defined(TARGET_MACH)
6485 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6491 if (acfg->need_no_dead_strip) {
6492 emit_unset_mode (acfg);
6493 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6495 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6496 emit_label (acfg, debug_sym);
6499 emit_label (acfg, plt_entry->symbol);
6501 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6504 emit_symbol_size (acfg, debug_sym, ".");
6507 if (acfg->thumb_mixed) {
6508 /* Make sure the ARM symbols don't alias the thumb ones */
6509 emit_zero_bytes (acfg, 16);
6512 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6515 for (i = 0; i < acfg->plt_offset; ++i) {
6516 char *debug_sym = NULL;
6517 MonoPltEntry *plt_entry = NULL;
6522 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6524 /* Skip plt entries not actually called by LLVM code */
6525 if (!plt_entry->llvm_used)
6528 if (acfg->aot_opts.write_symbols) {
6529 if (plt_entry->debug_sym)
6530 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6534 #if defined(TARGET_MACH)
6535 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6536 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6538 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6539 emit_label (acfg, debug_sym);
6541 fprintf (acfg->fp, "\n.thumb_func\n");
6543 emit_label (acfg, plt_entry->llvm_symbol);
6546 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6548 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6551 emit_symbol_size (acfg, debug_sym, ".");
6557 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6559 emit_info_symbol (acfg, "plt_end");
6563 * emit_trampoline_full:
6565 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6566 * create_jit_info_for_trampoline ().
6568 static G_GNUC_UNUSED void
6569 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6571 char start_symbol [MAX_SYMBOL_SIZE];
6572 char end_symbol [MAX_SYMBOL_SIZE];
6573 char symbol [MAX_SYMBOL_SIZE];
6574 guint32 buf_size, info_offset;
6575 MonoJumpInfo *patch_info;
6588 code_size = info->code_size;
6590 unwind_ops = info->unwind_ops;
6594 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6596 emit_section_change (acfg, ".text", 0);
6597 emit_global (acfg, start_symbol, TRUE);
6598 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6599 emit_label (acfg, start_symbol);
6601 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6602 emit_label (acfg, symbol);
6605 * The code should access everything through the GOT, so we pass
6608 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6610 emit_symbol_size (acfg, start_symbol, ".");
6613 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6614 emit_label (acfg, end_symbol);
6619 /* Sort relocations */
6620 patches = g_ptr_array_new ();
6621 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6622 if (patch_info->type != MONO_PATCH_INFO_NONE)
6623 g_ptr_array_add (patches, patch_info);
6624 g_ptr_array_sort (patches, compare_patches);
6626 buf_size = patches->len * 128 + 128;
6627 buf = (guint8 *)g_malloc (buf_size);
6630 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6631 g_assert (p - buf < buf_size);
6632 g_ptr_array_free (patches, TRUE);
6634 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6636 info_offset = add_to_blob (acfg, buf, p - buf);
6638 emit_section_change (acfg, RODATA_SECT, 0);
6639 emit_global (acfg, symbol, FALSE);
6640 emit_label (acfg, symbol);
6642 emit_int32 (acfg, info_offset);
6646 guint32 encoded_len;
6650 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6652 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6653 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6656 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6657 emit_int32 (acfg, uw_offset);
6660 /* Emit debug info */
6662 char symbol2 [MAX_SYMBOL_SIZE];
6664 sprintf (symbol, "%s", name);
6665 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6668 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6674 static G_GNUC_UNUSED void
6675 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6677 emit_trampoline_full (acfg, got_offset, info, TRUE);
6681 emit_trampolines (MonoAotCompile *acfg)
6683 char symbol [MAX_SYMBOL_SIZE];
6684 char end_symbol [MAX_SYMBOL_SIZE];
6685 int i, tramp_got_offset;
6687 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6691 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6694 g_assert (acfg->image->assembly);
6696 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6697 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6698 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6699 MonoTrampInfo *info;
6702 * Emit the generic trampolines.
6704 * We could save some code by treating the generic trampolines as a wrapper
6705 * method, but that approach has its own complexities, so we choose the simpler
6708 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6709 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6710 #ifdef DISABLE_REMOTING
6711 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6714 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6715 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6718 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6719 emit_trampoline (acfg, acfg->got_offset, info);
6722 /* Emit the exception related code pieces */
6723 mono_arch_get_restore_context (&info, TRUE);
6724 emit_trampoline (acfg, acfg->got_offset, info);
6725 mono_arch_get_call_filter (&info, TRUE);
6726 emit_trampoline (acfg, acfg->got_offset, info);
6727 mono_arch_get_throw_exception (&info, TRUE);
6728 emit_trampoline (acfg, acfg->got_offset, info);
6729 mono_arch_get_rethrow_exception (&info, TRUE);
6730 emit_trampoline (acfg, acfg->got_offset, info);
6731 mono_arch_get_throw_corlib_exception (&info, TRUE);
6732 emit_trampoline (acfg, acfg->got_offset, info);
6734 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6735 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6736 emit_trampoline (acfg, acfg->got_offset, info);
6737 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6738 emit_trampoline (acfg, acfg->got_offset, info);
6741 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6742 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6744 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6746 /* Create a separate out trampoline for more information in stack traces */
6747 info->name = g_strdup ("gsharedvt_out_trampoline");
6748 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6752 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6754 GSList *l = mono_arch_get_trampolines (TRUE);
6757 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6759 emit_trampoline (acfg, acfg->got_offset, info);
6765 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6768 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6769 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6770 emit_trampoline (acfg, acfg->got_offset, info);
6773 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6774 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6775 emit_trampoline (acfg, acfg->got_offset, info);
6779 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6780 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6781 emit_trampoline (acfg, acfg->got_offset, info);
6787 /* delegate_invoke_impl trampolines */
6788 l = mono_arch_get_delegate_invoke_impls ();
6790 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6792 emit_trampoline (acfg, acfg->got_offset, info);
6797 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6798 mono_arch_create_handler_block_trampoline (&info, TRUE);
6799 emit_trampoline (acfg, acfg->got_offset, info);
6802 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6804 /* Emit trampolines which are numerous */
6807 * These include the following:
6808 * - specific trampolines
6809 * - static rgctx invoke trampolines
6811 * These trampolines have the same code, they are parameterized by GOT
6813 * They are defined in this file, in the arch_... routines instead of
6814 * in tramp-<ARCH>.c, since it is easier to do it this way.
6818 * When running in aot-only mode, we can't create specific trampolines at
6819 * runtime, so we create a few, and save them in the AOT file.
6820 * Normal trampolines embed their argument as a literal inside the
6821 * trampoline code, we can't do that here, so instead we embed an offset
6822 * which needs to be added to the trampoline address to get the address of
6823 * the GOT slot which contains the argument value.
6824 * The generated trampolines jump to the generic trampolines using another
6825 * GOT slot, which will be setup by the AOT loader to point to the
6826 * generic trampoline code of the given type.
6830 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6834 emit_section_change (acfg, ".text", 0);
6836 tramp_got_offset = acfg->got_offset;
6838 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6840 case MONO_AOT_TRAMP_SPECIFIC:
6841 sprintf (symbol, "specific_trampolines");
6843 case MONO_AOT_TRAMP_STATIC_RGCTX:
6844 sprintf (symbol, "static_rgctx_trampolines");
6846 case MONO_AOT_TRAMP_IMT:
6847 sprintf (symbol, "imt_trampolines");
6849 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6850 sprintf (symbol, "gsharedvt_arg_trampolines");
6853 g_assert_not_reached ();
6856 sprintf (end_symbol, "%s_e", symbol);
6858 if (acfg->aot_opts.write_symbols)
6859 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6861 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6862 emit_info_symbol (acfg, symbol);
6864 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6866 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6870 case MONO_AOT_TRAMP_SPECIFIC:
6871 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6872 tramp_got_offset += 2;
6874 case MONO_AOT_TRAMP_STATIC_RGCTX:
6875 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6876 tramp_got_offset += 2;
6878 case MONO_AOT_TRAMP_IMT:
6879 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6880 tramp_got_offset += 1;
6882 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6883 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6884 tramp_got_offset += 2;
6887 g_assert_not_reached ();
6889 if (!acfg->trampoline_size [ntype]) {
6890 g_assert (tramp_size);
6891 acfg->trampoline_size [ntype] = tramp_size;
6895 emit_label (acfg, end_symbol);
6896 emit_int32 (acfg, 0);
6899 arch_emit_specific_trampoline_pages (acfg);
6901 /* Reserve some entries at the end of the GOT for our use */
6902 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6905 acfg->got_offset += acfg->num_trampoline_got_entries;
6909 str_begins_with (const char *str1, const char *str2)
6911 int len = strlen (str2);
6912 return strncmp (str1, str2, len) == 0;
6916 mono_aot_readonly_field_override (MonoClassField *field)
6919 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6920 char *p = rdv->name;
6922 len = strlen (field->parent->name_space);
6923 if (strncmp (p, field->parent->name_space, len))
6928 len = strlen (field->parent->name);
6929 if (strncmp (p, field->parent->name, len))
6934 if (strcmp (p, field->name))
6936 switch (rdv->type) {
6938 return &rdv->value.i1;
6940 return &rdv->value.i2;
6942 return &rdv->value.i4;
6951 add_readonly_value (MonoAotOptions *opts, const char *val)
6956 /* the format of val is:
6957 * namespace.typename.fieldname=type/value
6958 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6960 fval = strrchr (val, '/');
6962 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6965 tval = strrchr (val, '=');
6967 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6970 rdv = g_new0 (ReadOnlyValue, 1);
6971 rdv->name = (char *)g_malloc0 (tval - val + 1);
6972 memcpy (rdv->name, val, tval - val);
6975 if (strncmp (tval, "i1", 2) == 0) {
6976 rdv->value.i1 = atoi (fval);
6977 rdv->type = MONO_TYPE_I1;
6978 } else if (strncmp (tval, "i2", 2) == 0) {
6979 rdv->value.i2 = atoi (fval);
6980 rdv->type = MONO_TYPE_I2;
6981 } else if (strncmp (tval, "i4", 2) == 0) {
6982 rdv->value.i4 = atoi (fval);
6983 rdv->type = MONO_TYPE_I4;
6985 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6988 rdv->next = readonly_values;
6989 readonly_values = rdv;
6993 clean_path (gchar * path)
6998 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7001 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7008 wrap_path (gchar * path)
7014 // If the string contains no spaces, just return the original string.
7015 if (strstr (path, " ") == NULL)
7018 // If the string is already wrapped in quotes, return it.
7019 len = strlen (path);
7020 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7023 // If the string contains spaces, then wrap it in quotes.
7024 gchar *clean = g_strdup_printf ("\"%s\"", path);
7029 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7031 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7033 ptrdiff_t len = end-start;
7035 g_ptr_array_add (args, g_strndup (start, len));
7039 mono_aot_split_options (const char *aot_options)
7041 enum MonoAotOptionState {
7042 MONO_AOT_OPTION_STATE_DEFAULT,
7043 MONO_AOT_OPTION_STATE_STRING,
7044 MONO_AOT_OPTION_STATE_ESCAPE,
7047 GPtrArray *args = g_ptr_array_new ();
7048 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7049 gchar const *opt_start = aot_options;
7050 gboolean end_of_string = FALSE;
7053 g_return_val_if_fail (aot_options != NULL, NULL);
7055 while ((cur = *aot_options) != '\0') {
7056 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7061 // If we find a quote, then if we're in the default case then
7062 // it means we've found the start of a string, if not then it
7063 // means we've found the end of the string and should switch
7064 // back to the default case.
7066 case MONO_AOT_OPTION_STATE_DEFAULT:
7067 state = MONO_AOT_OPTION_STATE_STRING;
7069 case MONO_AOT_OPTION_STATE_STRING:
7070 state = MONO_AOT_OPTION_STATE_DEFAULT;
7072 case MONO_AOT_OPTION_STATE_ESCAPE:
7073 g_assert_not_reached ();
7078 // If we've found an escaping operator, then this means we
7079 // should not process the next character if inside a string.
7080 if (state == MONO_AOT_OPTION_STATE_STRING)
7081 state = MONO_AOT_OPTION_STATE_ESCAPE;
7084 // If we're in the default state then this means we've found
7085 // an option, store it for later processing.
7086 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7094 // If the next character is end of string, then process the last option.
7095 if (*(aot_options) == '\0') {
7096 end_of_string = TRUE;
7102 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7103 opt_start = ++aot_options;
7106 goto restart; // Check for null and continue loop
7113 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7117 args = mono_aot_split_options (aot_options ? aot_options : "");
7118 for (int i = 0; i < args->len; ++i) {
7119 const char *arg = (const char *)g_ptr_array_index (args, i);
7121 if (str_begins_with (arg, "outfile=")) {
7122 opts->outfile = g_strdup (arg + strlen ("outfile="));
7123 } else if (str_begins_with (arg, "llvm-outfile=")) {
7124 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7125 } else if (str_begins_with (arg, "temp-path=")) {
7126 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7127 } else if (str_begins_with (arg, "save-temps")) {
7128 opts->save_temps = TRUE;
7129 } else if (str_begins_with (arg, "keep-temps")) {
7130 opts->save_temps = TRUE;
7131 } else if (str_begins_with (arg, "write-symbols")) {
7132 opts->write_symbols = TRUE;
7133 } else if (str_begins_with (arg, "no-write-symbols")) {
7134 opts->write_symbols = FALSE;
7135 } else if (str_begins_with (arg, "metadata-only")) {
7136 opts->metadata_only = TRUE;
7137 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7138 opts->bind_to_runtime_version = TRUE;
7139 } else if (str_begins_with (arg, "full")) {
7140 opts->mode = MONO_AOT_MODE_FULL;
7141 } else if (str_begins_with (arg, "hybrid")) {
7142 opts->mode = MONO_AOT_MODE_HYBRID;
7143 } else if (str_begins_with (arg, "threads=")) {
7144 opts->nthreads = atoi (arg + strlen ("threads="));
7145 } else if (str_begins_with (arg, "static")) {
7146 opts->static_link = TRUE;
7147 opts->no_dlsym = TRUE;
7148 } else if (str_begins_with (arg, "asmonly")) {
7149 opts->asm_only = TRUE;
7150 } else if (str_begins_with (arg, "asmwriter")) {
7151 opts->asm_writer = TRUE;
7152 } else if (str_begins_with (arg, "nodebug")) {
7153 opts->nodebug = TRUE;
7154 } else if (str_begins_with (arg, "dwarfdebug")) {
7155 opts->dwarf_debug = TRUE;
7156 } else if (str_begins_with (arg, "nopagetrampolines")) {
7157 opts->use_trampolines_page = FALSE;
7158 } else if (str_begins_with (arg, "ntrampolines=")) {
7159 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7160 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7161 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7162 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7163 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7164 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7165 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7166 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7167 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7168 } else if (str_begins_with (arg, "tool-prefix=")) {
7169 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7170 } else if (str_begins_with (arg, "ld-flags=")) {
7171 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7172 } else if (str_begins_with (arg, "soft-debug")) {
7173 opts->soft_debug = TRUE;
7174 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7175 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7176 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7177 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7178 } else if (str_begins_with (arg, "msym-dir=")) {
7179 debug_options.no_seq_points_compact_data = FALSE;
7180 opts->gen_msym_dir = TRUE;
7181 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7182 } else if (str_begins_with (arg, "direct-pinvoke")) {
7183 opts->direct_pinvoke = TRUE;
7184 } else if (str_begins_with (arg, "direct-icalls")) {
7185 opts->direct_icalls = TRUE;
7186 } else if (str_begins_with (arg, "no-direct-calls")) {
7187 opts->no_direct_calls = TRUE;
7188 } else if (str_begins_with (arg, "print-skipped")) {
7189 opts->print_skipped_methods = TRUE;
7190 } else if (str_begins_with (arg, "stats")) {
7192 } else if (str_begins_with (arg, "no-instances")) {
7193 opts->no_instances = TRUE;
7194 } else if (str_begins_with (arg, "log-generics")) {
7195 opts->log_generics = TRUE;
7196 } else if (str_begins_with (arg, "log-instances=")) {
7197 opts->log_instances = TRUE;
7198 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7199 } else if (str_begins_with (arg, "log-instances")) {
7200 opts->log_instances = TRUE;
7201 } else if (str_begins_with (arg, "internal-logfile=")) {
7202 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7203 } else if (str_begins_with (arg, "mtriple=")) {
7204 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7205 } else if (str_begins_with (arg, "llvm-path=")) {
7206 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7207 } else if (!strcmp (arg, "llvm")) {
7209 } else if (str_begins_with (arg, "readonly-value=")) {
7210 add_readonly_value (opts, arg + strlen ("readonly-value="));
7211 } else if (str_begins_with (arg, "info")) {
7212 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7214 } else if (str_begins_with (arg, "gc-maps")) {
7215 mini_gc_enable_gc_maps_for_aot ();
7216 } else if (str_begins_with (arg, "dump")) {
7217 opts->dump_json = TRUE;
7218 } else if (str_begins_with (arg, "llvmonly")) {
7219 opts->mode = MONO_AOT_MODE_FULL;
7221 opts->llvm_only = TRUE;
7222 } else if (str_begins_with (arg, "data-outfile=")) {
7223 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7224 } else if (str_begins_with (arg, "profile=")) {
7225 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7226 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7227 printf ("Supported options for --aot:\n");
7228 printf (" outfile=\n");
7229 printf (" llvm-outfile=\n");
7230 printf (" llvm-path=\n");
7231 printf (" temp-path=\n");
7232 printf (" save-temps\n");
7233 printf (" keep-temps\n");
7234 printf (" write-symbols\n");
7235 printf (" metadata-only\n");
7236 printf (" bind-to-runtime-version\n");
7238 printf (" threads=\n");
7239 printf (" static\n");
7240 printf (" asmonly\n");
7241 printf (" asmwriter\n");
7242 printf (" nodebug\n");
7243 printf (" dwarfdebug\n");
7244 printf (" ntrampolines=\n");
7245 printf (" nrgctx-trampolines=\n");
7246 printf (" nimt-trampolines=\n");
7247 printf (" ngsharedvt-trampolines=\n");
7248 printf (" tool-prefix=\n");
7249 printf (" readonly-value=\n");
7250 printf (" soft-debug\n");
7251 printf (" msym-dir=\n");
7252 printf (" gc-maps\n");
7253 printf (" print-skipped\n");
7254 printf (" no-instances\n");
7255 printf (" stats\n");
7258 printf (" help/?\n");
7261 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7265 g_free ((gpointer) arg);
7268 if (opts->use_trampolines_page) {
7269 opts->ntrampolines = 0;
7270 opts->nrgctx_trampolines = 0;
7271 opts->nimt_trampolines = 0;
7272 opts->ngsharedvt_arg_trampolines = 0;
7275 g_ptr_array_free (args, /*free_seg=*/TRUE);
7279 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7281 MonoMethod *method = (MonoMethod*)key;
7282 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7283 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7284 MonoJumpInfoToken *new_ji;
7286 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7287 new_ji->image = ji->image;
7288 new_ji->token = ji->token;
7289 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7293 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7295 if (klass->type_token)
7297 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7300 return can_encode_class (acfg, klass->element_class);
7305 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7307 if (method->wrapper_type) {
7308 switch (method->wrapper_type) {
7309 case MONO_WRAPPER_NONE:
7310 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7311 case MONO_WRAPPER_XDOMAIN_INVOKE:
7312 case MONO_WRAPPER_STFLD:
7313 case MONO_WRAPPER_LDFLD:
7314 case MONO_WRAPPER_LDFLDA:
7315 case MONO_WRAPPER_STELEMREF:
7316 case MONO_WRAPPER_PROXY_ISINST:
7317 case MONO_WRAPPER_ALLOC:
7318 case MONO_WRAPPER_REMOTING_INVOKE:
7319 case MONO_WRAPPER_UNKNOWN:
7320 case MONO_WRAPPER_WRITE_BARRIER:
7321 case MONO_WRAPPER_DELEGATE_INVOKE:
7322 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7323 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7324 case MONO_WRAPPER_SYNCHRONIZED:
7326 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7327 case MONO_WRAPPER_CASTCLASS: {
7328 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7337 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7341 if (!method->token) {
7342 /* The method is part of a constructed type like Int[,].Set (). */
7343 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7344 if (method->klass->rank)
7354 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7356 switch (patch_info->type) {
7357 case MONO_PATCH_INFO_METHOD:
7358 case MONO_PATCH_INFO_METHODCONST:
7359 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7360 MonoMethod *method = patch_info->data.method;
7362 return can_encode_method (acfg, method);
7364 case MONO_PATCH_INFO_VTABLE:
7365 case MONO_PATCH_INFO_CLASS:
7366 case MONO_PATCH_INFO_IID:
7367 case MONO_PATCH_INFO_ADJUSTED_IID:
7368 if (!can_encode_class (acfg, patch_info->data.klass)) {
7369 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7373 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7374 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7375 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7380 case MONO_PATCH_INFO_RGCTX_FETCH:
7381 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7382 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7384 if (!can_encode_method (acfg, entry->method))
7386 if (!can_encode_patch (acfg, entry->data))
7398 is_concrete_type (MonoType *t)
7403 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7405 if (t->type == MONO_TYPE_GENERICINST) {
7406 MonoGenericContext *orig_ctx;
7407 MonoGenericInst *inst;
7410 if (!MONO_TYPE_ISSTRUCT (t))
7412 klass = mono_class_from_mono_type (t);
7413 orig_ctx = &mono_class_get_generic_class (klass)->context;
7415 inst = orig_ctx->class_inst;
7417 for (i = 0; i < inst->type_argc; ++i) {
7418 arg = mini_get_underlying_type (inst->type_argv [i]);
7419 if (!is_concrete_type (arg))
7423 inst = orig_ctx->method_inst;
7425 for (i = 0; i < inst->type_argc; ++i) {
7426 arg = mini_get_underlying_type (inst->type_argv [i]);
7427 if (!is_concrete_type (arg))
7435 /* LOCKING: Assumes the loader lock is held */
7437 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7439 MonoMethod *wrapper;
7440 gboolean concrete = TRUE;
7441 gboolean add_in = gsharedvt_in;
7442 gboolean add_out = gsharedvt_out;
7444 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7446 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7449 if (!add_in && !add_out)
7452 if (mini_is_gsharedvt_variable_signature (sig))
7456 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7458 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7460 if (!sig->has_type_parameters) {
7461 //printf ("%s\n", mono_signature_full_name (sig));
7464 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7465 add_extra_method (acfg, wrapper);
7467 if (gsharedvt_out) {
7468 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7469 add_extra_method (acfg, wrapper);
7472 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7473 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7476 //printf ("%s\n", mono_signature_full_name (sig));
7478 copy->ret = mini_get_underlying_type (sig->ret);
7479 if (!is_concrete_type (copy->ret))
7481 for (i = 0; i < sig->param_count; ++i) {
7482 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7483 if (!is_concrete_type (copy->params [i]))
7487 copy->has_type_parameters = 0;
7490 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7491 add_extra_method (acfg, wrapper);
7494 if (gsharedvt_out) {
7495 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7496 add_extra_method (acfg, wrapper);
7499 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7507 * AOT compile a given method.
7508 * This function might be called by multiple threads, so it must be thread-safe.
7511 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7514 MonoJumpInfo *patch_info;
7517 MonoMethod *wrapped;
7521 if (acfg->aot_opts.metadata_only)
7524 mono_acfg_lock (acfg);
7525 index = get_method_index (acfg, method);
7526 mono_acfg_unlock (acfg);
7528 /* fixme: maybe we can also precompile wrapper methods */
7529 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7530 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7531 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7532 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7536 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7539 wrapped = mono_marshal_method_from_wrapper (method);
7540 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7541 // FIXME: The wrapper should be generic too, but it is not
7544 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7547 InterlockedIncrement (&acfg->stats.mcount);
7550 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7551 InterlockedIncrement (&acfg->stats.genericcount);
7556 //acfg->aot_opts.print_skipped_methods = TRUE;
7559 * Since these methods are the only ones which are compiled with
7560 * AOT support, and they are not used by runtime startup/shutdown code,
7561 * the runtime will not see AOT methods during AOT compilation,so it
7562 * does not need to support them by creating a fake GOT etc.
7564 flags = JIT_FLAG_AOT;
7565 if (mono_aot_mode_is_full (&acfg->aot_opts))
7566 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7568 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7569 if (acfg->aot_opts.llvm_only)
7570 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7571 if (acfg->aot_opts.no_direct_calls)
7572 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7573 if (acfg->aot_opts.direct_pinvoke)
7574 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7576 jit_timer = mono_time_track_start ();
7577 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7578 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7580 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7581 if (acfg->aot_opts.print_skipped_methods)
7582 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7583 InterlockedIncrement (&acfg->stats.genericcount);
7586 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7587 if (acfg->aot_opts.print_skipped_methods)
7588 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7589 /* Let the exception happen at runtime */
7593 if (cfg->disable_aot) {
7594 if (acfg->aot_opts.print_skipped_methods)
7595 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7596 InterlockedIncrement (&acfg->stats.ocount);
7599 cfg->method_index = index;
7601 /* Nullify patches which need no aot processing */
7602 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7603 switch (patch_info->type) {
7604 case MONO_PATCH_INFO_LABEL:
7605 case MONO_PATCH_INFO_BB:
7606 patch_info->type = MONO_PATCH_INFO_NONE;
7613 /* Collect method->token associations from the cfg */
7614 mono_acfg_lock (acfg);
7615 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7616 mono_acfg_unlock (acfg);
7617 g_hash_table_destroy (cfg->token_info_hash);
7618 cfg->token_info_hash = NULL;
7621 * Check for absolute addresses.
7624 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7625 switch (patch_info->type) {
7626 case MONO_PATCH_INFO_ABS:
7627 /* unable to handle this */
7636 if (acfg->aot_opts.print_skipped_methods)
7637 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7638 InterlockedIncrement (&acfg->stats.abscount);
7642 /* Lock for the rest of the code */
7643 mono_acfg_lock (acfg);
7646 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7647 else if (cfg->gshared)
7648 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7649 else if (cfg->method->wrapper_type)
7650 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7652 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7655 * Check for methods/klasses we can't encode.
7658 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7659 if (!can_encode_patch (acfg, patch_info))
7664 if (acfg->aot_opts.print_skipped_methods)
7665 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7666 acfg->stats.ocount++;
7667 mono_acfg_unlock (acfg);
7671 if (!cfg->compile_llvm)
7672 acfg->has_jitted_code = TRUE;
7674 if (method->is_inflated && acfg->aot_opts.log_instances) {
7675 if (acfg->instances_logfile)
7676 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7678 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7681 /* Adds generic instances referenced by this method */
7683 * The depth is used to avoid infinite loops when generic virtual recursion is
7686 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7687 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7688 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7689 switch (patch_info->type) {
7690 case MONO_PATCH_INFO_RGCTX_FETCH:
7691 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7692 case MONO_PATCH_INFO_METHOD: {
7693 MonoMethod *m = NULL;
7695 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7696 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7698 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7699 m = e->data->data.method;
7701 m = patch_info->data.method;
7706 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7707 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7708 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7709 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7710 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7711 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7712 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7714 add_extra_method_with_depth (acfg, m, depth + 1);
7715 add_types_from_method_header (acfg, m);
7718 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7720 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7721 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7723 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7724 add_extra_method_with_depth (acfg, m, depth + 1);
7728 case MONO_PATCH_INFO_VTABLE: {
7729 MonoClass *klass = patch_info->data.klass;
7731 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7732 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7735 case MONO_PATCH_INFO_SFLDA: {
7736 MonoClass *klass = patch_info->data.field->parent;
7738 /* The .cctor needs to run at runtime. */
7739 if (mono_class_is_ginst (klass) && !mono_generic_context_is_sharable_full (&mono_class_get_generic_class (klass)->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7740 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7749 /* Determine whenever the method has GOT slots */
7750 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7751 switch (patch_info->type) {
7752 case MONO_PATCH_INFO_GOT_OFFSET:
7753 case MONO_PATCH_INFO_NONE:
7754 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7755 case MONO_PATCH_INFO_GC_NURSERY_START:
7756 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7758 case MONO_PATCH_INFO_IMAGE:
7759 /* The assembly is stored in GOT slot 0 */
7760 if (patch_info->data.image != acfg->image)
7761 cfg->has_got_slots = TRUE;
7764 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7765 cfg->has_got_slots = TRUE;
7770 if (!cfg->has_got_slots)
7771 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7773 /* Add gsharedvt wrappers for signatures used by the method */
7774 if (acfg->aot_opts.llvm_only) {
7777 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7778 /* These only need out wrappers */
7779 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7781 for (l = cfg->signatures; l; l = l->next) {
7782 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7784 /* These only need in wrappers */
7785 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7790 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7792 /* Make a copy of the patch info which is in the mempool */
7794 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7796 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7797 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7800 patches = new_patch_info;
7802 patches_end->next = new_patch_info;
7803 patches_end = new_patch_info;
7805 cfg->patch_info = patches;
7807 /* Make a copy of the unwind info */
7809 GSList *l, *unwind_ops;
7813 for (l = cfg->unwind_ops; l; l = l->next) {
7814 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7815 memcpy (op, l->data, sizeof (MonoUnwindOp));
7816 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7818 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7820 /* Make a copy of the argument/local info */
7823 MonoInst **args, **locals;
7824 MonoMethodSignature *sig;
7825 MonoMethodHeader *header;
7828 sig = mono_method_signature (method);
7829 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7830 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7831 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7832 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7836 header = mono_method_get_header_checked (method, &error);
7837 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7838 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7839 for (i = 0; i < header->num_locals; ++i) {
7840 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7841 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7843 mono_metadata_free_mh (header);
7844 cfg->locals = locals;
7847 /* Free some fields used by cfg to conserve memory */
7848 mono_empty_compile (cfg);
7850 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7852 while (index >= acfg->cfgs_size) {
7853 MonoCompile **new_cfgs;
7856 new_size = acfg->cfgs_size * 2;
7857 new_cfgs = g_new0 (MonoCompile*, new_size);
7858 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7859 g_free (acfg->cfgs);
7860 acfg->cfgs = new_cfgs;
7861 acfg->cfgs_size = new_size;
7863 acfg->cfgs [index] = cfg;
7865 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7867 mono_update_jit_stats (cfg);
7870 if (cfg->orig_method->wrapper_type)
7871 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7874 mono_acfg_unlock (acfg);
7876 InterlockedIncrement (&acfg->stats.ccount);
7879 static mono_thread_start_return_t WINAPI
7880 compile_thread_main (gpointer user_data)
7882 MonoDomain *domain = ((MonoDomain **)user_data) [0];
7883 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [1];
7884 GPtrArray *methods = ((GPtrArray **)user_data) [2];
7888 MonoThread *thread = mono_thread_attach (domain);
7889 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7890 mono_error_assert_ok (&error);
7892 for (i = 0; i < methods->len; ++i)
7893 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7898 /* Used by the LLVM backend */
7900 mono_aot_get_got_offset (MonoJumpInfo *ji)
7902 return get_got_offset (llvm_acfg, TRUE, ji);
7906 * mono_aot_is_shared_got_offset:
7908 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7909 * when the AOT image is loaded.
7912 mono_aot_is_shared_got_offset (int offset)
7914 return offset < llvm_acfg->nshared_got_entries;
7918 mono_aot_get_method_name (MonoCompile *cfg)
7920 if (llvm_acfg->aot_opts.static_link)
7921 /* Include the assembly name too to avoid duplicate symbol errors */
7922 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7924 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7928 * mono_aot_is_linkonce_method:
7930 * Return whenever METHOD should be emitted with linkonce linkage,
7931 * eliminating duplicate copies when compiling in static mode.
7934 mono_aot_is_linkonce_method (MonoMethod *method)
7940 // FIXME: Add more cases
7941 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7943 info = mono_marshal_get_wrapper_info (method);
7944 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7951 append_mangled_type (GString *s, MonoType *t)
7954 g_string_append_printf (s, "b");
7956 case MONO_TYPE_VOID:
7957 g_string_append_printf (s, "void_");
7960 g_string_append_printf (s, "i1");
7963 g_string_append_printf (s, "u1");
7966 g_string_append_printf (s, "i2");
7969 g_string_append_printf (s, "u2");
7972 g_string_append_printf (s, "i4");
7975 g_string_append_printf (s, "u4");
7978 g_string_append_printf (s, "i8");
7981 g_string_append_printf (s, "u8");
7984 g_string_append_printf (s, "ii");
7987 g_string_append_printf (s, "ui");
7990 g_string_append_printf (s, "fl");
7993 g_string_append_printf (s, "do");
7996 char *fullname = mono_type_full_name (t);
8002 * Have to create a mangled name which is:
8006 temp = g_string_new ("");
8007 len = strlen (fullname);
8008 for (i = 0; i < len; ++i) {
8009 char c = fullname [i];
8011 g_string_append_c (temp, c);
8012 } else if (c == '_') {
8013 g_string_append_c (temp, '_');
8014 g_string_append_c (temp, '_');
8016 g_string_append_c (temp, '_');
8017 g_string_append_printf (temp, "%x", (int)c);
8020 temps = g_string_free (temp, FALSE);
8021 /* Include the length to avoid different length type names aliasing each other */
8022 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8031 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8036 supported = append_mangled_type (s, sig->ret);
8040 g_string_append_printf (s, "this_");
8041 for (i = 0; i < sig->param_count; ++i) {
8042 supported = append_mangled_type (s, sig->params [i]);
8051 * mono_aot_get_mangled_method_name:
8053 * Return a unique mangled name for METHOD, or NULL.
8056 mono_aot_get_mangled_method_name (MonoMethod *method)
8062 // FIXME: Add more cases
8063 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8065 info = mono_marshal_get_wrapper_info (method);
8066 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8069 s = g_string_new ("");
8071 g_string_append_printf (s, "aot_method_w_");
8073 switch (info->subtype) {
8074 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8075 g_string_append_printf (s, "gsharedvt_in_");
8077 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8078 g_string_append_printf (s, "gsharedvt_out_");
8081 g_assert_not_reached ();
8085 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8087 g_string_free (s, TRUE);
8091 return g_string_free (s, FALSE);
8095 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8097 return is_direct_callable (llvm_acfg, NULL, patch_info);
8101 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8103 MonoPltEntry *plt_entry;
8105 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8106 plt_entry->llvm_used = FALSE;
8110 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8112 const char *sym = NULL;
8114 if (llvm_acfg->aot_opts.direct_icalls) {
8115 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8116 /* Call to a C function implementing a jit icall */
8117 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8118 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8119 MonoMethod *method = (MonoMethod *)data;
8120 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8121 sym = mono_lookup_icall_symbol (method);
8122 else if (llvm_acfg->aot_opts.direct_pinvoke)
8123 sym = get_pinvoke_import (llvm_acfg, method);
8126 return g_strdup (sym);
8132 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8134 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8135 MonoPltEntry *plt_entry;
8136 const char *sym = NULL;
8139 ji->data.target = data;
8141 if (!can_encode_patch (llvm_acfg, ji))
8144 if (llvm_acfg->aot_opts.direct_icalls) {
8145 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8146 /* Call to a C function implementing a jit icall */
8147 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8148 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8149 MonoMethod *method = (MonoMethod *)data;
8150 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8151 sym = mono_lookup_icall_symbol (method);
8154 return g_strdup (sym);
8157 plt_entry = get_plt_entry (llvm_acfg, ji);
8158 plt_entry->llvm_used = TRUE;
8160 #if defined(TARGET_MACH)
8161 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8163 return g_strdup_printf (plt_entry->llvm_symbol);
8168 mono_aot_get_method_index (MonoMethod *method)
8170 g_assert (llvm_acfg);
8171 return get_method_index (llvm_acfg, method);
8175 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8179 mono_acfg_lock (llvm_acfg);
8180 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8181 mono_acfg_unlock (llvm_acfg);
8187 execute_system (const char * command)
8192 // We need an extra set of quotes around the whole command to properly handle commands
8193 // with spaces since internally the command is called through "cmd /c.
8194 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8196 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8197 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8198 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8199 status = _wsystem (wstr);
8202 g_free (quoted_command);
8203 #elif defined (HAVE_SYSTEM)
8204 status = system (command);
8206 g_assert_not_reached ();
8217 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8221 emit_llvm_file (MonoAotCompile *acfg)
8223 char *command, *opts, *tempbc, *optbc, *output_fname;
8225 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8226 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8227 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8229 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8230 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8233 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8236 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8237 * a lot of time, and doesn't seem to save much space.
8238 * The following optimizations cannot be enabled:
8240 * - 'jump-threading' changes our blockaddress references to int constants.
8241 * - 'basiccg' fails because it contains:
8242 * if (CS && !isa<IntrinsicInst>(II)) {
8243 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8244 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8245 * The opt list below was produced by taking the output of:
8246 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8247 * then removing tailcallelim + the global opts.
8248 * strip-dead-prototypes deletes unused intrinsics definitions.
8250 /* The dse pass is disabled because of #13734 and #17616 */
8252 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8253 * // If we have no DataLayout information around, then the size of the store
8254 * // is inferrable from the pointee type. If they are the same type, then
8255 * // we know that the store is safe.
8256 * if (AA.getDataLayout() == 0 &&
8257 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8258 * return OverwriteComplete;
8259 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8261 if (acfg->aot_opts.llvm_only)
8262 // FIXME: This doesn't work yet
8263 opts = g_strdup ("");
8265 #if LLVM_API_VERSION > 100
8266 opts = g_strdup ("-O2 -disable-tail-calls");
8268 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");
8270 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8271 aot_printf (acfg, "Executing opt: %s\n", command);
8272 if (execute_system (command) != 0)
8276 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8277 /* Nothing else to do */
8280 if (acfg->aot_opts.llvm_only) {
8281 /* Use the stock clang from xcode */
8283 command = g_strdup_printf ("clang++ -fexceptions -march=x86-64 -fpic -msse -msse2 -msse3 -msse4 -O2 -fno-optimize-sibling-calls -Wno-override-module -c -o \"%s\" \"%s.opt.bc\"", acfg->llvm_ofile, acfg->tmpbasename);
8285 aot_printf (acfg, "Executing clang: %s\n", command);
8286 if (execute_system (command) != 0)
8291 if (!acfg->llc_args)
8292 acfg->llc_args = g_string_new ("");
8294 /* Verbose asm slows down llc greatly */
8295 g_string_append (acfg->llc_args, " -asm-verbose=false");
8297 if (acfg->aot_opts.mtriple)
8298 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8300 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8302 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8304 #if LLVM_API_VERSION > 100
8305 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8308 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8309 /* ios requires PIC code now */
8310 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8312 if (llvm_acfg->aot_opts.static_link)
8313 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8315 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8318 if (acfg->llvm_owriter) {
8319 /* Emit an object file directly */
8320 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8321 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8323 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8325 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8326 g_free (output_fname);
8328 aot_printf (acfg, "Executing llc: %s\n", command);
8330 if (execute_system (command) != 0)
8337 emit_code (MonoAotCompile *acfg)
8339 int oindex, i, prev_index;
8340 gboolean saved_unbox_info = FALSE;
8341 char symbol [MAX_SYMBOL_SIZE];
8343 if (acfg->aot_opts.llvm_only)
8346 #if defined(TARGET_POWERPC64)
8347 sprintf (symbol, ".Lgot_addr");
8348 emit_section_change (acfg, ".text", 0);
8349 emit_alignment (acfg, 8);
8350 emit_label (acfg, symbol);
8351 emit_pointer (acfg, acfg->got_symbol);
8355 * This global symbol is used to compute the address of each method using the
8356 * code_offsets array. It is also used to compute the memory ranges occupied by
8357 * AOT code, so it must be equal to the address of the first emitted method.
8359 emit_section_change (acfg, ".text", 0);
8360 emit_alignment_code (acfg, 8);
8361 emit_info_symbol (acfg, "jit_code_start");
8364 * Emit some padding so the local symbol for the first method doesn't have the
8365 * same address as 'methods'.
8367 emit_padding (acfg, 16);
8369 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8373 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8375 cfg = acfg->cfgs [i];
8380 method = cfg->orig_method;
8382 /* Emit unbox trampoline */
8383 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8384 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8386 emit_section_change (acfg, ".text", 0);
8388 if (acfg->thumb_mixed && cfg->compile_llvm) {
8389 emit_set_thumb_mode (acfg);
8390 fprintf (acfg->fp, "\n.thumb_func\n");
8393 emit_label (acfg, symbol);
8395 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8397 if (acfg->thumb_mixed && cfg->compile_llvm)
8398 emit_set_arm_mode (acfg);
8400 if (!saved_unbox_info) {
8401 char user_symbol [128];
8403 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8405 emit_label (acfg, "ut_end");
8407 unwind_ops = mono_unwind_get_cie_program ();
8408 save_unwind_info (acfg, user_symbol, unwind_ops);
8409 mono_free_unwind_info (unwind_ops);
8411 /* Save the unbox trampoline size */
8412 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8414 saved_unbox_info = TRUE;
8418 if (cfg->compile_llvm)
8419 acfg->stats.llvm_count ++;
8421 emit_method_code (acfg, cfg);
8424 emit_section_change (acfg, ".text", 0);
8425 emit_alignment_code (acfg, 8);
8426 emit_info_symbol (acfg, "jit_code_end");
8428 /* To distinguish it from the next symbol */
8429 emit_padding (acfg, 4);
8432 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8433 * from optimizing them away, since it doesn't see that code_offsets references them.
8434 * JITted methods don't need this since they are referenced using assembler local
8436 * FIXME: This is why write-symbols doesn't work on OSX ?
8438 if (acfg->llvm && acfg->need_no_dead_strip) {
8439 fprintf (acfg->fp, "\n");
8440 for (i = 0; i < acfg->nmethods; ++i) {
8441 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8442 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8447 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8448 * This is PIE code, and the linker can update it if needed.
8451 sprintf (symbol, "method_addresses");
8452 emit_section_change (acfg, ".text", 1);
8453 emit_alignment_code (acfg, 8);
8454 emit_info_symbol (acfg, symbol);
8455 if (acfg->aot_opts.write_symbols)
8456 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8457 emit_unset_mode (acfg);
8458 if (acfg->need_no_dead_strip)
8459 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8461 for (i = 0; i < acfg->nmethods; ++i) {
8462 #ifdef MONO_ARCH_AOT_SUPPORTED
8465 if (acfg->cfgs [i]) {
8466 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8468 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8473 sprintf (symbol, "method_addresses_end");
8474 emit_label (acfg, symbol);
8477 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8478 sprintf (symbol, "unbox_trampolines");
8479 emit_section_change (acfg, RODATA_SECT, 0);
8480 emit_alignment (acfg, 8);
8481 emit_info_symbol (acfg, symbol);
8484 for (i = 0; i < acfg->nmethods; ++i) {
8489 cfg = acfg->cfgs [i];
8493 method = cfg->orig_method;
8495 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8496 index = get_method_index (acfg, method);
8498 emit_int32 (acfg, index);
8499 /* Make sure the table is sorted by index */
8500 g_assert (index > prev_index);
8504 sprintf (symbol, "unbox_trampolines_end");
8505 emit_info_symbol (acfg, symbol);
8506 emit_int32 (acfg, 0);
8508 /* Emit a separate table with the trampoline addresses/offsets */
8509 sprintf (symbol, "unbox_trampoline_addresses");
8510 emit_section_change (acfg, ".text", 0);
8511 emit_alignment_code (acfg, 8);
8512 emit_info_symbol (acfg, symbol);
8514 for (i = 0; i < acfg->nmethods; ++i) {
8519 cfg = acfg->cfgs [i];
8523 method = cfg->orig_method;
8525 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8526 #ifdef MONO_ARCH_AOT_SUPPORTED
8529 index = get_method_index (acfg, method);
8530 sprintf (symbol, "ut_%d", index);
8532 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8536 emit_int32 (acfg, 0);
8540 emit_info (MonoAotCompile *acfg)
8545 offsets = g_new0 (gint32, acfg->nmethods);
8547 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8548 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8550 if (acfg->cfgs [i]) {
8551 emit_method_info (acfg, acfg->cfgs [i]);
8552 offsets [i] = acfg->cfgs [i]->method_info_offset;
8558 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8563 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8565 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8566 #define mix(a,b,c) { \
8567 a -= c; a ^= rot(c, 4); c += b; \
8568 b -= a; b ^= rot(a, 6); a += c; \
8569 c -= b; c ^= rot(b, 8); b += a; \
8570 a -= c; a ^= rot(c,16); c += b; \
8571 b -= a; b ^= rot(a,19); a += c; \
8572 c -= b; c ^= rot(b, 4); b += a; \
8574 #define final(a,b,c) { \
8575 c ^= b; c -= rot(b,14); \
8576 a ^= c; a -= rot(c,11); \
8577 b ^= a; b -= rot(a,25); \
8578 c ^= b; c -= rot(b,16); \
8579 a ^= c; a -= rot(c,4); \
8580 b ^= a; b -= rot(a,14); \
8581 c ^= b; c -= rot(b,24); \
8585 mono_aot_type_hash (MonoType *t1)
8587 guint hash = t1->type;
8589 hash |= t1->byref << 6; /* do not collide with t1->type values */
8591 case MONO_TYPE_VALUETYPE:
8592 case MONO_TYPE_CLASS:
8593 case MONO_TYPE_SZARRAY:
8594 /* check if the distribution is good enough */
8595 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8597 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8598 case MONO_TYPE_ARRAY:
8599 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8600 case MONO_TYPE_GENERICINST:
8601 return ((hash << 5) - hash) ^ 0;
8608 * mono_aot_method_hash:
8610 * Return a hash code for methods which only depends on metadata.
8613 mono_aot_method_hash (MonoMethod *method)
8615 MonoMethodSignature *sig;
8619 guint32 *hashes_start, *hashes;
8621 MonoGenericInst *class_ginst = NULL;
8622 MonoGenericInst *ginst = NULL;
8624 /* Similar to the hash in mono_method_get_imt_slot () */
8626 sig = mono_method_signature (method);
8628 if (mono_class_is_ginst (method->klass))
8629 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
8630 if (method->is_inflated)
8631 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8633 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8634 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8635 hashes = hashes_start;
8637 /* Some wrappers are assigned to random classes */
8638 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8639 klass = method->klass;
8641 klass = mono_defaults.object_class;
8643 if (!method->wrapper_type) {
8646 if (mono_class_is_ginst (klass))
8647 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
8649 full_name = mono_type_full_name (&klass->byval_arg);
8651 hashes [0] = mono_metadata_str_hash (full_name);
8655 hashes [0] = mono_metadata_str_hash (klass->name);
8656 hashes [1] = mono_metadata_str_hash (klass->name_space);
8658 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8659 /* The method name includes a stringified pointer */
8662 hashes [2] = mono_metadata_str_hash (method->name);
8663 hashes [3] = method->wrapper_type;
8664 hashes [4] = mono_aot_type_hash (sig->ret);
8666 for (i = 0; i < sig->param_count; i++) {
8667 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8670 for (i = 0; i < class_ginst->type_argc; ++i)
8671 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8674 for (i = 0; i < ginst->type_argc; ++i)
8675 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8677 g_assert (hindex == hashes_count);
8679 /* Setup internal state */
8680 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8682 /* Handle most of the hashes */
8683 while (hashes_count > 3) {
8692 /* Handle the last 3 hashes (all the case statements fall through) */
8693 switch (hashes_count) {
8694 case 3 : c += hashes [2];
8695 case 2 : b += hashes [1];
8696 case 1 : a += hashes [0];
8698 case 0: /* nothing left to add */
8702 g_free (hashes_start);
8711 * mono_aot_get_array_helper_from_wrapper;
8713 * Get the helper method in Array called by an array wrapper method.
8716 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8720 MonoGenericContext ctx;
8721 MonoType *args [16];
8722 char *mname, *iname, *s, *s2, *helper_name = NULL;
8724 prefix = "System.Collections.Generic";
8725 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8726 s2 = strstr (s, "`1.");
8732 //printf ("X: %s %s\n", iname, mname);
8734 if (!strcmp (iname, "IList"))
8735 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8737 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8738 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8740 g_free (helper_name);
8743 if (m->is_generic) {
8745 memset (&ctx, 0, sizeof (ctx));
8746 args [0] = &method->klass->element_class->byval_arg;
8747 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8748 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8749 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8755 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8757 typedef struct HashEntry {
8758 guint32 key, value, index;
8759 struct HashEntry *next;
8763 * emit_extra_methods:
8765 * Emit methods which are not in the METHOD table, like wrappers.
8768 emit_extra_methods (MonoAotCompile *acfg)
8770 int i, table_size, buf_size;
8772 guint32 *info_offsets;
8775 HashEntry *entry, *new_entry;
8776 int nmethods, max_chain_length;
8779 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8781 /* Emit method info */
8783 for (i = 0; i < acfg->extra_methods->len; ++i) {
8784 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8785 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8791 p = buf = (guint8 *)g_malloc (buf_size);
8795 method = cfg->method_to_register;
8797 encode_method_ref (acfg, method, p, &p);
8799 g_assert ((p - buf) < buf_size);
8801 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8806 * Construct a chained hash table for mapping indexes in extra_method_info to
8809 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8810 table = g_ptr_array_sized_new (table_size);
8811 for (i = 0; i < table_size; ++i)
8812 g_ptr_array_add (table, NULL);
8813 chain_lengths = g_new0 (int, table_size);
8814 max_chain_length = 0;
8815 for (i = 0; i < acfg->extra_methods->len; ++i) {
8816 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8817 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8823 key = info_offsets [i];
8824 value = get_method_index (acfg, method);
8826 hash = mono_aot_method_hash (method) % table_size;
8827 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8829 chain_lengths [hash] ++;
8830 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8832 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8833 new_entry->key = key;
8834 new_entry->value = value;
8836 entry = (HashEntry *)g_ptr_array_index (table, hash);
8837 if (entry == NULL) {
8838 new_entry->index = hash;
8839 g_ptr_array_index (table, hash) = new_entry;
8842 entry = entry->next;
8844 entry->next = new_entry;
8845 new_entry->index = table->len;
8846 g_ptr_array_add (table, new_entry);
8849 g_free (chain_lengths);
8851 //printf ("MAX: %d\n", max_chain_length);
8853 buf_size = table->len * 12 + 4;
8854 p = buf = (guint8 *)g_malloc (buf_size);
8855 encode_int (table_size, p, &p);
8857 for (i = 0; i < table->len; ++i) {
8858 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8860 if (entry == NULL) {
8861 encode_int (0, p, &p);
8862 encode_int (0, p, &p);
8863 encode_int (0, p, &p);
8865 //g_assert (entry->key > 0);
8866 encode_int (entry->key, p, &p);
8867 encode_int (entry->value, p, &p);
8869 encode_int (entry->next->index, p, &p);
8871 encode_int (0, p, &p);
8874 g_assert (p - buf <= buf_size);
8876 /* Emit the table */
8877 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8882 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8883 * This is used by mono_aot_find_jit_info ().
8885 buf_size = acfg->extra_methods->len * 8 + 4;
8886 p = buf = (guint8 *)g_malloc (buf_size);
8887 encode_int (acfg->extra_methods->len, p, &p);
8888 for (i = 0; i < acfg->extra_methods->len; ++i) {
8889 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8891 encode_int (get_method_index (acfg, method), p, &p);
8892 encode_int (info_offsets [i], p, &p);
8894 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8897 g_free (info_offsets);
8898 g_ptr_array_free (table, TRUE);
8902 generate_aotid (guint8* aotid)
8904 gpointer rand_handle;
8908 rand_handle = mono_rand_init (NULL, 0);
8910 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8911 mono_error_assert_ok (&error);
8913 mono_rand_close (rand_handle);
8917 emit_exception_info (MonoAotCompile *acfg)
8921 SeqPointData sp_data;
8922 gboolean seq_points_to_file = FALSE;
8924 offsets = g_new0 (gint32, acfg->nmethods);
8925 for (i = 0; i < acfg->nmethods; ++i) {
8926 if (acfg->cfgs [i]) {
8927 MonoCompile *cfg = acfg->cfgs [i];
8929 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8930 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8931 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8932 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8933 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8935 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8936 offsets [i] = cfg->ex_info_offset;
8938 if (method_seq_points_to_file) {
8939 if (!seq_points_to_file) {
8940 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8941 seq_points_to_file = TRUE;
8943 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8950 if (seq_points_to_file) {
8951 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8952 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8953 char *image_basename = g_path_get_basename (acfg->image->name);
8954 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8955 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8957 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8958 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8962 mono_seq_point_data_write (&sp_data, aot_file_path);
8963 mono_seq_point_data_free (&sp_data);
8967 g_free (image_basename);
8969 g_free (aot_file_path);
8972 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8977 emit_unwind_info (MonoAotCompile *acfg)
8982 if (acfg->aot_opts.llvm_only) {
8983 g_assert (acfg->unwind_ops->len == 0);
8988 * The unwind info contains a lot of duplicates so we emit each unique
8989 * entry once, and only store the offset from the start of the table in the
8993 sprintf (symbol, "unwind_info");
8994 emit_section_change (acfg, RODATA_SECT, 1);
8995 emit_alignment (acfg, 8);
8996 emit_info_symbol (acfg, symbol);
8998 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8999 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9000 guint8 *unwind_info;
9001 guint32 unwind_info_len;
9005 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9008 encode_value (unwind_info_len, p, &p);
9009 emit_bytes (acfg, buf, p - buf);
9010 emit_bytes (acfg, unwind_info, unwind_info_len);
9012 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9017 emit_class_info (MonoAotCompile *acfg)
9022 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9023 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9024 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9026 acfg->stats.offsets_size += emit_offset_table (acfg, "class_info_offsets", MONO_AOT_TABLE_CLASS_INFO_OFFSETS, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
9030 typedef struct ClassNameTableEntry {
9031 guint32 token, index;
9032 struct ClassNameTableEntry *next;
9033 } ClassNameTableEntry;
9036 emit_class_name_table (MonoAotCompile *acfg)
9038 int i, table_size, buf_size;
9039 guint32 token, hash;
9044 ClassNameTableEntry *entry, *new_entry;
9047 * Construct a chained hash table for mapping class names to typedef tokens.
9049 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9050 table = g_ptr_array_sized_new (table_size);
9051 for (i = 0; i < table_size; ++i)
9052 g_ptr_array_add (table, NULL);
9053 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9055 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9056 klass = mono_class_get_checked (acfg->image, token, &error);
9058 mono_error_cleanup (&error);
9061 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9062 hash = mono_metadata_str_hash (full_name) % table_size;
9065 /* FIXME: Allocate from the mempool */
9066 new_entry = g_new0 (ClassNameTableEntry, 1);
9067 new_entry->token = token;
9069 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9070 if (entry == NULL) {
9071 new_entry->index = hash;
9072 g_ptr_array_index (table, hash) = new_entry;
9075 entry = entry->next;
9077 entry->next = new_entry;
9078 new_entry->index = table->len;
9079 g_ptr_array_add (table, new_entry);
9083 /* Emit the table */
9084 buf_size = table->len * 4 + 4;
9085 p = buf = (guint8 *)g_malloc0 (buf_size);
9087 /* FIXME: Optimize memory usage */
9088 g_assert (table_size < 65000);
9089 encode_int16 (table_size, p, &p);
9090 g_assert (table->len < 65000);
9091 for (i = 0; i < table->len; ++i) {
9092 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9094 if (entry == NULL) {
9095 encode_int16 (0, p, &p);
9096 encode_int16 (0, p, &p);
9098 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9100 encode_int16 (entry->next->index, p, &p);
9102 encode_int16 (0, p, &p);
9106 g_assert (p - buf <= buf_size);
9107 g_ptr_array_free (table, TRUE);
9109 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9115 emit_image_table (MonoAotCompile *acfg)
9121 * The image table is small but referenced in a lot of places.
9122 * So we emit it at once, and reference its elements by an index.
9124 buf_size = acfg->image_table->len * 28 + 4;
9125 for (i = 0; i < acfg->image_table->len; i++) {
9126 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9127 MonoAssemblyName *aname = &image->assembly->aname;
9129 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9132 buf = p = (guint8 *)g_malloc0 (buf_size);
9133 encode_int (acfg->image_table->len, p, &p);
9134 for (i = 0; i < acfg->image_table->len; i++) {
9135 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9136 MonoAssemblyName *aname = &image->assembly->aname;
9138 /* FIXME: Support multi-module assemblies */
9139 g_assert (image->assembly->image == image);
9141 encode_string (image->assembly_name, p, &p);
9142 encode_string (image->guid, p, &p);
9143 encode_string (aname->culture ? aname->culture : "", p, &p);
9144 encode_string ((const char*)aname->public_key_token, p, &p);
9146 while (GPOINTER_TO_UINT (p) % 8 != 0)
9149 encode_int (aname->flags, p, &p);
9150 encode_int (aname->major, p, &p);
9151 encode_int (aname->minor, p, &p);
9152 encode_int (aname->build, p, &p);
9153 encode_int (aname->revision, p, &p);
9155 g_assert (p - buf <= buf_size);
9157 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9163 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9165 int i, first_plt_got_patch = 0, buf_size;
9167 guint32 *got_info_offsets;
9168 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9170 /* Add the patches needed by the PLT to the GOT */
9172 acfg->plt_got_offset_base = acfg->got_offset;
9173 first_plt_got_patch = info->got_patches->len;
9174 for (i = 1; i < acfg->plt_offset; ++i) {
9175 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9177 g_ptr_array_add (info->got_patches, plt_entry->ji);
9179 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9182 acfg->got_offset += acfg->plt_offset;
9187 * - optimize offsets table.
9188 * - reduce number of exported symbols.
9189 * - emit info for a klass only once.
9190 * - determine when a method uses a GOT slot which is guaranteed to be already
9192 * - clean up and document the code.
9193 * - use String.Empty in class libs.
9196 /* Encode info required to decode shared GOT entries */
9197 buf_size = info->got_patches->len * 128;
9198 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9199 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9201 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9203 if (acfg->plt_offset)
9204 acfg->plt_got_info_offsets [0] = 0;
9206 for (i = 0; i < info->got_patches->len; ++i) {
9207 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9212 encode_value (ji->type, p, &p);
9214 encode_patch (acfg, ji, p, &p);
9215 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9216 g_assert (p - buf <= buf_size);
9217 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9219 if (!llvm && i >= first_plt_got_patch)
9220 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9221 acfg->stats.got_info_size += p - buf;
9224 /* Emit got_info_offsets table */
9226 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9227 acfg->stats.offsets_size += emit_offset_table (acfg, llvm ? "llvm_got_info_offsets" : "got_info_offsets", llvm ? MONO_AOT_TABLE_LLVM_GOT_INFO_OFFSETS : MONO_AOT_TABLE_GOT_INFO_OFFSETS, llvm ? acfg->llvm_got_offset : first_plt_got_patch, 10, (gint32*)got_info_offsets);
9231 emit_got (MonoAotCompile *acfg)
9233 char symbol [MAX_SYMBOL_SIZE];
9235 if (acfg->aot_opts.llvm_only)
9238 /* Don't make GOT global so accesses to it don't need relocations */
9239 sprintf (symbol, "%s", acfg->got_symbol);
9242 emit_unset_mode (acfg);
9243 fprintf (acfg->fp, ".section __DATA, __bss\n");
9244 emit_alignment (acfg, 8);
9246 emit_info_symbol (acfg, "jit_got");
9247 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9249 emit_section_change (acfg, ".bss", 0);
9250 emit_alignment (acfg, 8);
9251 if (acfg->aot_opts.write_symbols)
9252 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9253 emit_label (acfg, symbol);
9255 emit_info_symbol (acfg, "jit_got");
9256 if (acfg->got_offset > 0)
9257 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9260 sprintf (symbol, "got_end");
9261 emit_label (acfg, symbol);
9264 typedef struct GlobalsTableEntry {
9265 guint32 value, index;
9266 struct GlobalsTableEntry *next;
9267 } GlobalsTableEntry;
9269 #ifdef TARGET_WIN32_MSVC
9270 #define DLL_ENTRY_POINT "DllMain"
9273 emit_library_info (MonoAotCompile *acfg)
9275 // Only include for shared libraries linked directly from generated object.
9276 if (link_shared_library (acfg)) {
9278 char symbol [MAX_SYMBOL_SIZE];
9280 // Ask linker to export all global symbols.
9281 emit_section_change (acfg, ".drectve", 0);
9282 for (guint i = 0; i < acfg->globals->len; ++i) {
9283 name = (char *)g_ptr_array_index (acfg->globals, i);
9284 g_assert (name != NULL);
9285 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9286 emit_string (acfg, symbol);
9289 // Emit DLLMain function, needed by MSVC linker for DLL's.
9290 // NOTE, DllMain should not go into exports above.
9291 emit_section_change (acfg, ".text", 0);
9292 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9293 emit_label (acfg, DLL_ENTRY_POINT);
9295 // Simple implementation of DLLMain, just returning TRUE.
9296 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9297 fprintf (acfg->fp, "movl $1, %%eax\n");
9298 fprintf (acfg->fp, "ret\n");
9300 // Inform linker about our dll entry function.
9301 emit_section_change (acfg, ".drectve", 0);
9302 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9310 emit_library_info (MonoAotCompile *acfg)
9317 emit_globals (MonoAotCompile *acfg)
9323 GlobalsTableEntry *entry, *new_entry;
9325 if (!acfg->aot_opts.static_link)
9328 if (acfg->aot_opts.llvm_only) {
9329 g_assert (acfg->globals->len == 0);
9334 * When static linking, we emit a table containing our globals.
9338 * Construct a chained hash table for mapping global names to their index in
9339 * the globals table.
9341 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9342 table = g_ptr_array_sized_new (table_size);
9343 for (i = 0; i < table_size; ++i)
9344 g_ptr_array_add (table, NULL);
9345 for (i = 0; i < acfg->globals->len; ++i) {
9346 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9348 hash = mono_metadata_str_hash (name) % table_size;
9350 /* FIXME: Allocate from the mempool */
9351 new_entry = g_new0 (GlobalsTableEntry, 1);
9352 new_entry->value = i;
9354 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9355 if (entry == NULL) {
9356 new_entry->index = hash;
9357 g_ptr_array_index (table, hash) = new_entry;
9360 entry = entry->next;
9362 entry->next = new_entry;
9363 new_entry->index = table->len;
9364 g_ptr_array_add (table, new_entry);
9368 /* Emit the table */
9369 sprintf (symbol, ".Lglobals_hash");
9370 emit_section_change (acfg, RODATA_SECT, 0);
9371 emit_alignment (acfg, 8);
9372 emit_label (acfg, symbol);
9374 /* FIXME: Optimize memory usage */
9375 g_assert (table_size < 65000);
9376 emit_int16 (acfg, table_size);
9377 for (i = 0; i < table->len; ++i) {
9378 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9380 if (entry == NULL) {
9381 emit_int16 (acfg, 0);
9382 emit_int16 (acfg, 0);
9384 emit_int16 (acfg, entry->value + 1);
9386 emit_int16 (acfg, entry->next->index);
9388 emit_int16 (acfg, 0);
9392 /* Emit the names */
9393 for (i = 0; i < acfg->globals->len; ++i) {
9394 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9396 sprintf (symbol, "name_%d", i);
9397 emit_section_change (acfg, RODATA_SECT, 1);
9399 emit_alignment (acfg, 4);
9401 emit_label (acfg, symbol);
9402 emit_string (acfg, name);
9405 /* Emit the globals table */
9406 sprintf (symbol, "globals");
9407 emit_section_change (acfg, ".data", 0);
9408 /* This is not a global, since it is accessed by the init function */
9409 emit_alignment (acfg, 8);
9410 emit_info_symbol (acfg, symbol);
9412 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9413 emit_pointer (acfg, symbol);
9415 for (i = 0; i < acfg->globals->len; ++i) {
9416 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9418 sprintf (symbol, "name_%d", i);
9419 emit_pointer (acfg, symbol);
9421 g_assert (strlen (name) < sizeof (symbol));
9422 sprintf (symbol, "%s", name);
9423 emit_pointer (acfg, symbol);
9425 /* Null terminate the table */
9426 emit_int32 (acfg, 0);
9427 emit_int32 (acfg, 0);
9431 emit_mem_end (MonoAotCompile *acfg)
9435 if (acfg->aot_opts.llvm_only)
9438 sprintf (symbol, "mem_end");
9439 emit_section_change (acfg, ".text", 1);
9440 emit_alignment_code (acfg, 8);
9441 emit_label (acfg, symbol);
9445 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9449 info->version = MONO_AOT_FILE_VERSION;
9450 info->plt_got_offset_base = acfg->plt_got_offset_base;
9451 info->got_size = acfg->got_offset * sizeof (gpointer);
9452 info->plt_size = acfg->plt_offset;
9453 info->nmethods = acfg->nmethods;
9454 info->flags = acfg->flags;
9455 info->opts = acfg->opts;
9456 info->simd_opts = acfg->simd_opts;
9457 info->gc_name_index = acfg->gc_name_offset;
9458 info->datafile_size = acfg->datafile_offset;
9459 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9460 info->table_offsets [i] = acfg->table_offsets [i];
9461 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9462 info->num_trampolines [i] = acfg->num_trampolines [i];
9463 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9464 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9465 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9466 info->trampoline_size [i] = acfg->trampoline_size [i];
9467 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9469 info->double_align = MONO_ABI_ALIGNOF (double);
9470 info->long_align = MONO_ABI_ALIGNOF (gint64);
9471 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9472 info->tramp_page_size = acfg->tramp_page_size;
9473 info->nshared_got_entries = acfg->nshared_got_entries;
9474 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9475 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9477 memcpy(&info->aotid, acfg->image->aotid, 16);
9481 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9483 char symbol [MAX_SYMBOL_SIZE];
9485 const char **symbols;
9487 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9489 symbols [sindex ++] = acfg->got_symbol;
9491 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9492 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9494 symbols [sindex ++] = NULL;
9495 symbols [sindex ++] = NULL;
9497 /* llvm_get_method */
9498 symbols [sindex ++] = NULL;
9499 /* llvm_get_unbox_tramp */
9500 symbols [sindex ++] = NULL;
9501 if (!acfg->aot_opts.llvm_only) {
9502 symbols [sindex ++] = "jit_code_start";
9503 symbols [sindex ++] = "jit_code_end";
9504 symbols [sindex ++] = "method_addresses";
9506 symbols [sindex ++] = NULL;
9507 symbols [sindex ++] = NULL;
9508 symbols [sindex ++] = NULL;
9510 if (acfg->data_outfile) {
9511 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9512 symbols [sindex ++] = NULL;
9514 symbols [sindex ++] = "blob";
9515 symbols [sindex ++] = "class_name_table";
9516 symbols [sindex ++] = "class_info_offsets";
9517 symbols [sindex ++] = "method_info_offsets";
9518 symbols [sindex ++] = "ex_info_offsets";
9519 symbols [sindex ++] = "extra_method_info_offsets";
9520 symbols [sindex ++] = "extra_method_table";
9521 symbols [sindex ++] = "got_info_offsets";
9523 symbols [sindex ++] = "llvm_got_info_offsets";
9525 symbols [sindex ++] = NULL;
9526 symbols [sindex ++] = "image_table";
9528 symbols [sindex ++] = "mem_end";
9529 symbols [sindex ++] = "assembly_guid";
9530 symbols [sindex ++] = "runtime_version";
9531 if (acfg->num_trampoline_got_entries) {
9532 symbols [sindex ++] = "specific_trampolines";
9533 symbols [sindex ++] = "static_rgctx_trampolines";
9534 symbols [sindex ++] = "imt_trampolines";
9535 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9537 symbols [sindex ++] = NULL;
9538 symbols [sindex ++] = NULL;
9539 symbols [sindex ++] = NULL;
9540 symbols [sindex ++] = NULL;
9542 if (acfg->aot_opts.static_link) {
9543 symbols [sindex ++] = "globals";
9545 symbols [sindex ++] = NULL;
9547 symbols [sindex ++] = "assembly_name";
9548 symbols [sindex ++] = "plt";
9549 symbols [sindex ++] = "plt_end";
9550 symbols [sindex ++] = "unwind_info";
9551 if (!acfg->aot_opts.llvm_only) {
9552 symbols [sindex ++] = "unbox_trampolines";
9553 symbols [sindex ++] = "unbox_trampolines_end";
9554 symbols [sindex ++] = "unbox_trampoline_addresses";
9556 symbols [sindex ++] = NULL;
9557 symbols [sindex ++] = NULL;
9558 symbols [sindex ++] = NULL;
9561 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9563 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9564 emit_section_change (acfg, ".data", 0);
9565 emit_alignment (acfg, 8);
9566 emit_label (acfg, symbol);
9567 if (!acfg->aot_opts.static_link)
9568 emit_global (acfg, symbol, FALSE);
9570 /* The data emitted here must match MonoAotFileInfo. */
9572 emit_int32 (acfg, info->version);
9573 emit_int32 (acfg, info->dummy);
9576 * We emit pointers to our data structures instead of emitting global symbols which
9577 * point to them, to reduce the number of globals, and because using globals leads to
9578 * various problems (i.e. arm/thumb).
9580 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9581 emit_pointer (acfg, symbols [i]);
9583 emit_int32 (acfg, info->plt_got_offset_base);
9584 emit_int32 (acfg, info->got_size);
9585 emit_int32 (acfg, info->plt_size);
9586 emit_int32 (acfg, info->nmethods);
9587 emit_int32 (acfg, info->flags);
9588 emit_int32 (acfg, info->opts);
9589 emit_int32 (acfg, info->simd_opts);
9590 emit_int32 (acfg, info->gc_name_index);
9591 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9592 emit_int32 (acfg, info->double_align);
9593 emit_int32 (acfg, info->long_align);
9594 emit_int32 (acfg, info->generic_tramp_num);
9595 emit_int32 (acfg, info->tramp_page_size);
9596 emit_int32 (acfg, info->nshared_got_entries);
9597 emit_int32 (acfg, info->datafile_size);
9599 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9600 emit_int32 (acfg, info->table_offsets [i]);
9601 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9602 emit_int32 (acfg, info->num_trampolines [i]);
9603 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9604 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9605 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9606 emit_int32 (acfg, info->trampoline_size [i]);
9607 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9608 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9610 emit_bytes (acfg, info->aotid, 16);
9612 if (acfg->aot_opts.static_link) {
9613 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9614 emit_alignment (acfg, sizeof (gpointer));
9615 emit_label (acfg, acfg->static_linking_symbol);
9616 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9621 * Emit a structure containing all the information not stored elsewhere.
9624 emit_file_info (MonoAotCompile *acfg)
9627 MonoAotFileInfo *info;
9629 if (acfg->aot_opts.bind_to_runtime_version) {
9630 build_info = mono_get_runtime_build_info ();
9631 emit_string_symbol (acfg, "runtime_version", build_info);
9632 g_free (build_info);
9634 emit_string_symbol (acfg, "runtime_version", "");
9637 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9639 /* Emit a string holding the assembly name */
9640 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9642 info = g_new0 (MonoAotFileInfo, 1);
9643 init_aot_file_info (acfg, info);
9645 if (acfg->aot_opts.static_link) {
9646 char symbol [MAX_SYMBOL_SIZE];
9650 * Emit a global symbol which can be passed by an embedding app to
9651 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9654 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9656 /* Get rid of characters which cannot occur in symbols */
9658 for (p = symbol; *p; ++p) {
9659 if (!(isalnum (*p) || *p == '_'))
9662 acfg->static_linking_symbol = g_strdup (symbol);
9666 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9668 emit_aot_file_info (acfg, info);
9672 emit_blob (MonoAotCompile *acfg)
9674 acfg->blob_closed = TRUE;
9676 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9680 emit_objc_selectors (MonoAotCompile *acfg)
9685 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9690 * cat > foo.m << EOF
9693 * return @selector(print:);
9698 mono_img_writer_emit_unset_mode (acfg->w);
9699 g_assert (acfg->fp);
9700 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9701 fprintf (acfg->fp, ".align 3\n");
9702 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9703 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9704 emit_label (acfg, symbol);
9705 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9706 emit_pointer (acfg, symbol);
9709 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9710 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9711 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9712 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9715 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9716 fprintf (acfg->fp, ".align 3\n");
9717 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9718 fprintf (acfg->fp, ".long 0\n");
9719 fprintf (acfg->fp, ".long 16\n");
9723 emit_dwarf_info (MonoAotCompile *acfg)
9725 #ifdef EMIT_DWARF_INFO
9729 /* DIEs for methods */
9730 for (i = 0; i < acfg->nmethods; ++i) {
9731 MonoCompile *cfg = acfg->cfgs [i];
9736 // FIXME: LLVM doesn't define .Lme_...
9737 if (cfg->compile_llvm)
9740 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9742 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_symbol, symbol2, cfg->asm_debug_symbol, (guint8 *)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 ()));
9748 collect_methods (MonoAotCompile *acfg)
9751 MonoImage *image = acfg->image;
9753 /* Collect methods */
9754 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9757 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9759 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9762 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9763 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9764 mono_error_cleanup (&error);
9768 /* Load all methods eagerly to skip the slower lazy loading code */
9769 mono_class_setup_methods (method->klass);
9771 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9772 /* Compile the wrapper instead */
9773 /* We do this here instead of add_wrappers () because it is easy to do it here */
9774 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9778 /* FIXME: Some mscorlib methods don't have debug info */
9780 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9781 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9782 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9783 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9784 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9785 if (!mono_debug_lookup_method (method)) {
9786 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9793 if (method->is_generic || mono_class_is_gtd (method->klass))
9794 /* Compile the ref shared version instead */
9795 method = mini_get_shared_method (method);
9797 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9798 add_method_with_index (acfg, method, i, FALSE);
9799 acfg->method_index ++;
9802 /* gsharedvt methods */
9803 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9806 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9808 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9811 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9812 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9814 if (method->is_generic || mono_class_is_gtd (method->klass)) {
9815 MonoMethod *gshared;
9817 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9818 add_extra_method (acfg, gshared);
9822 if (mono_aot_mode_is_full (&acfg->aot_opts))
9823 add_generic_instances (acfg);
9825 if (mono_aot_mode_is_full (&acfg->aot_opts))
9826 add_wrappers (acfg);
9831 compile_methods (MonoAotCompile *acfg)
9835 if (acfg->aot_opts.nthreads > 0) {
9839 MonoThreadHandle *thread_handle;
9840 gpointer *user_data;
9841 MonoMethod **methods;
9843 methods_len = acfg->methods->len;
9845 len = acfg->methods->len / acfg->aot_opts.nthreads;
9848 * Partition the list of methods into fragments, and hand it to threads to
9851 threads = g_ptr_array_new ();
9852 /* Make a copy since acfg->methods is modified by compile_method () */
9853 methods = g_new0 (MonoMethod*, methods_len);
9854 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9855 for (i = 0; i < methods_len; ++i)
9856 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9858 while (i < methods_len) {
9859 frag = g_ptr_array_new ();
9860 for (j = 0; j < len; ++j) {
9861 if (i < methods_len) {
9862 g_ptr_array_add (frag, methods [i]);
9867 user_data = g_new0 (gpointer, 3);
9868 user_data [0] = mono_domain_get ();
9869 user_data [1] = acfg;
9870 user_data [2] = frag;
9872 thread_handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
9873 g_ptr_array_add (threads, thread_handle);
9877 for (i = 0; i < threads->len; ++i) {
9878 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
9879 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9885 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9886 for (i = methods_len; i < acfg->methods->len; ++i) {
9887 /* This can add new methods to acfg->methods */
9888 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9893 compile_asm (MonoAotCompile *acfg)
9895 char *command, *objfile;
9896 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9897 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9898 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9900 #ifdef TARGET_WIN32_MSVC
9901 #define AS_OPTIONS "-c -x assembler"
9902 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
9903 #define AS_OPTIONS "--64"
9904 #elif defined(TARGET_POWERPC64)
9905 #define AS_OPTIONS "-a64 -mppc64"
9906 #elif defined(sparc) && SIZEOF_VOID_P == 8
9907 #define AS_OPTIONS "-xarch=v9"
9908 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9909 #define AS_OPTIONS "-arch i386"
9911 #define AS_OPTIONS ""
9914 #ifdef __native_client_codegen__
9915 #if defined(TARGET_AMD64)
9916 #define AS_NAME "nacl64-as"
9918 #define AS_NAME "nacl-as"
9920 #elif defined(TARGET_OSX)
9921 #define AS_NAME "clang"
9922 #elif defined(TARGET_WIN32_MSVC)
9923 #define AS_NAME "clang.exe"
9925 #define AS_NAME "as"
9928 #ifdef TARGET_WIN32_MSVC
9929 #define AS_OBJECT_FILE_SUFFIX "obj"
9931 #define AS_OBJECT_FILE_SUFFIX "o"
9935 #define LD_NAME "ld"
9936 #define LD_OPTIONS "-shared -G"
9937 #elif defined(__ppc__) && defined(TARGET_MACH)
9938 #define LD_NAME "gcc"
9939 #define LD_OPTIONS "-dynamiclib"
9940 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9941 #define LD_NAME "clang"
9942 #define LD_OPTIONS "--shared"
9943 #elif defined(TARGET_WIN32_MSVC)
9944 #define LD_NAME "link.exe"
9945 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
9946 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9947 #define LD_NAME "gcc"
9948 #define LD_OPTIONS "-shared"
9949 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9950 #define LD_NAME "clang"
9951 #define LD_OPTIONS "-m32 -dynamiclib"
9952 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9953 #define LD_NAME "gcc"
9954 #define LD_OPTIONS "--shared"
9955 #elif defined(TARGET_POWERPC64)
9956 #define LD_OPTIONS "-m elf64ppc"
9960 #define LD_OPTIONS ""
9963 if (acfg->aot_opts.asm_only) {
9964 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9965 if (acfg->aot_opts.static_link)
9966 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9968 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9972 if (acfg->aot_opts.static_link) {
9973 if (acfg->aot_opts.outfile)
9974 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9976 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
9978 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
9982 g_string_append (acfg->as_args, "-c -x assembler");
9985 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9986 acfg->as_args ? acfg->as_args->str : "",
9987 wrap_path (objfile), wrap_path (acfg->tmpfname));
9988 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9989 if (execute_system (command) != 0) {
9995 if (acfg->llvm && !acfg->llvm_owriter) {
9996 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9997 acfg->as_args ? acfg->as_args->str : "",
9998 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9999 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10000 if (execute_system (command) != 0) {
10009 if (acfg->aot_opts.static_link) {
10010 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10011 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10016 if (acfg->aot_opts.outfile)
10017 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10019 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10021 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10024 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10026 llvm_ofile = g_strdup ("");
10029 /* replace the ; flags separators with spaces */
10030 g_strdelimit (ld_flags, ";", ' ');
10032 if (acfg->aot_opts.llvm_only)
10033 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10035 #ifdef TARGET_WIN32_MSVC
10036 g_assert (tmp_outfile_name != NULL);
10037 g_assert (objfile != NULL);
10038 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10039 ld_flags, tmp_outfile_name, objfile);
10040 #elif defined(LD_NAME)
10041 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10042 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10043 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10046 if (acfg->aot_opts.tool_prefix) {
10047 /* Cross compiling */
10048 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10049 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10050 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10052 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10053 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10054 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10056 if (acfg->aot_opts.llvm_only) {
10057 command = g_strdup_printf ("clang++ %s", args);
10059 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10064 aot_printf (acfg, "Executing the native linker: %s\n", command);
10065 if (execute_system (command) != 0) {
10066 g_free (tmp_outfile_name);
10067 g_free (outfile_name);
10076 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10077 printf ("Stripping the binary: %s\n", com);
10078 execute_system (com);
10081 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10083 * gas generates 'mapping symbols' each time code and data is mixed, which
10084 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10086 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10087 aot_printf (acfg, "Stripping the binary: %s\n", command);
10088 if (execute_system (command) != 0) {
10089 g_free (tmp_outfile_name);
10090 g_free (outfile_name);
10097 if (0 != rename (tmp_outfile_name, outfile_name)) {
10098 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10099 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10100 unlink (outfile_name);
10101 rename (tmp_outfile_name, outfile_name);
10105 #if defined(TARGET_MACH)
10106 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10107 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10108 if (execute_system (command) != 0) {
10113 if (!acfg->aot_opts.save_temps)
10116 g_free (tmp_outfile_name);
10117 g_free (outfile_name);
10120 if (acfg->aot_opts.save_temps)
10121 aot_printf (acfg, "Retained input file.\n");
10123 unlink (acfg->tmpfname);
10129 profread_byte (FILE *infile)
10134 res = fread (&i, 1, 1, infile);
10135 g_assert (res == 1);
10140 profread_int (FILE *infile)
10144 res = fread (&i, 4, 1, infile);
10145 g_assert (res == 1);
10150 profread_string (FILE *infile)
10156 len = profread_int (infile);
10157 if (len + 1 > 1024)
10158 pbuf = g_malloc (len + 1);
10161 res = fread (pbuf, 1, len, infile);
10162 g_assert (res == len);
10165 return g_strdup (buf);
10171 load_profile_file (MonoAotCompile *acfg, char *filename)
10175 int res, len, version;
10178 infile = fopen (filename, "r");
10180 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10184 printf ("Using profile data file '%s'\n", filename);
10186 sprintf (magic, AOT_PROFILER_MAGIC);
10187 len = strlen (magic);
10188 res = fread (buf, 1, len, infile);
10189 magic [len] = '\0';
10191 if ((res != len) || strcmp (buf, magic) != 0) {
10192 printf ("Profile file has wrong header: '%s'.\n", buf);
10196 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10197 version = profread_int (infile);
10198 if (version != expected_version) {
10199 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10204 ProfileData *data = g_new0 (ProfileData, 1);
10205 data->images = g_hash_table_new (NULL, NULL);
10206 data->classes = g_hash_table_new (NULL, NULL);
10207 data->ginsts = g_hash_table_new (NULL, NULL);
10208 data->methods = g_hash_table_new (NULL, NULL);
10211 int type = profread_byte (infile);
10212 int id = profread_int (infile);
10214 if (type == AOTPROF_RECORD_NONE)
10218 case AOTPROF_RECORD_IMAGE: {
10219 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10220 idata->name = profread_string (infile);
10221 char *mvid = profread_string (infile);
10223 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10226 case AOTPROF_RECORD_GINST: {
10228 int len = profread_int (infile);
10230 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10232 gdata->argv = g_new0 (ClassProfileData*, len);
10234 for (i = 0; i < len; ++i) {
10235 int class_id = profread_int (infile);
10237 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10238 g_assert (gdata->argv [i]);
10240 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10243 case AOTPROF_RECORD_TYPE: {
10244 int type = profread_byte (infile);
10247 case MONO_TYPE_CLASS: {
10248 int image_id = profread_int (infile);
10249 int ginst_id = profread_int (infile);
10250 char *class_name = profread_string (infile);
10252 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10255 char *p = strrchr (class_name, '.');
10259 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10260 cdata->image = image;
10261 cdata->ns = g_strdup (class_name);
10262 cdata->name = g_strdup (p + 1);
10264 if (ginst_id != -1) {
10265 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10266 g_assert (cdata->inst);
10268 g_free (class_name);
10270 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10274 case MONO_TYPE_SZARRAY: {
10275 int elem_id = profread_int (infile);
10281 g_assert_not_reached ();
10286 case AOTPROF_RECORD_METHOD: {
10287 int class_id = profread_int (infile);
10288 int ginst_id = profread_int (infile);
10289 int param_count = profread_int (infile);
10290 char *method_name = profread_string (infile);
10291 char *sig = profread_string (infile);
10293 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10296 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10298 mdata->klass = klass;
10299 mdata->name = method_name;
10300 mdata->signature = sig;
10301 mdata->param_count = param_count;
10303 if (ginst_id != -1) {
10304 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10305 g_assert (mdata->inst);
10307 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10311 printf ("%d\n", type);
10312 g_assert_not_reached ();
10317 acfg->profile_data = g_list_append (acfg->profile_data, data);
10321 resolve_class (ClassProfileData *cdata);
10324 resolve_ginst (GInstProfileData *inst_data)
10328 if (inst_data->inst)
10331 for (i = 0; i < inst_data->argc; ++i) {
10332 resolve_class (inst_data->argv [i]);
10333 if (!inst_data->argv [i]->klass)
10336 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10337 for (i = 0; i < inst_data->argc; ++i)
10338 args [i] = &inst_data->argv [i]->klass->byval_arg;
10340 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10344 resolve_class (ClassProfileData *cdata)
10349 if (!cdata->image->image)
10352 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10354 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10358 resolve_ginst (cdata->inst);
10359 if (!cdata->inst->inst)
10361 MonoGenericContext ctx;
10363 memset (&ctx, 0, sizeof (ctx));
10364 ctx.class_inst = cdata->inst->inst;
10365 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10367 cdata->klass = klass;
10372 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10375 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10377 GHashTableIter iter;
10378 gpointer key, value;
10385 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10386 g_hash_table_iter_init (&iter, data->images);
10387 while (g_hash_table_iter_next (&iter, &key, &value)) {
10388 ImageProfileData *idata = (ImageProfileData*)value;
10390 for (i = 0; i < assemblies->len; ++i) {
10391 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10393 if (!strcmp (ass->aname.name, idata->name)) {
10394 idata->image = ass->image;
10399 g_ptr_array_free (assemblies, TRUE);
10402 g_hash_table_iter_init (&iter, data->classes);
10403 while (g_hash_table_iter_next (&iter, &key, &value)) {
10404 ClassProfileData *cdata = (ClassProfileData*)value;
10406 if (!cdata->image->image)
10409 resolve_class (cdata);
10412 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10417 g_hash_table_iter_init (&iter, data->methods);
10418 while (g_hash_table_iter_next (&iter, &key, &value)) {
10419 MethodProfileData *mdata = (MethodProfileData*)value;
10424 resolve_class (mdata->klass);
10425 klass = mdata->klass->klass;
10429 while ((m = mono_class_get_methods (klass, &miter))) {
10432 if (strcmp (m->name, mdata->name))
10434 MonoMethodSignature *sig = mono_method_signature (m);
10437 if (sig->param_count != mdata->param_count)
10440 resolve_ginst (mdata->inst);
10441 if (!mdata->inst->inst)
10443 MonoGenericContext ctx;
10445 memset (&ctx, 0, sizeof (ctx));
10446 ctx.method_inst = mdata->inst->inst;
10448 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10451 sig = mono_method_signature_checked (m, &error);
10452 if (!is_ok (&error)) {
10453 mono_error_cleanup (&error);
10457 char *sig_str = mono_signature_full_name (sig);
10458 gboolean match = !strcmp (sig_str, mdata->signature);
10462 //printf ("%s\n", mono_method_full_name (m, 1));
10470 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10474 for (i = 0; i < inst->type_argc; ++i) {
10475 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10476 if (k->image == image)
10478 if (mono_class_is_ginst (k)) {
10479 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10480 if (inst_references_image (kinst, image))
10488 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10492 for (i = 0; i < inst->type_argc; ++i) {
10493 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10494 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10501 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10503 GHashTableIter iter;
10504 gpointer key, value;
10511 * Add method instances 'related' to this assembly to the AOT image.
10513 g_hash_table_iter_init (&iter, data->methods);
10514 while (g_hash_table_iter_next (&iter, &key, &value)) {
10515 MethodProfileData *mdata = (MethodProfileData*)value;
10516 MonoMethod *m = mdata->method;
10517 MonoGenericContext *ctx;
10521 if (!m->is_inflated)
10524 ctx = mono_method_get_context (m);
10525 /* For simplicity, add instances which reference the assembly we are compiling */
10526 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10527 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10528 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10529 //printf ("%s\n", mono_method_full_name (m, TRUE));
10530 add_extra_method (acfg, m);
10532 } else if (m->klass->image == acfg->image &&
10533 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
10534 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
10535 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10536 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
10537 //printf ("%s\n", mono_method_full_name (m, TRUE));
10538 add_extra_method (acfg, m);
10542 * FIXME: We might skip some instances, for example:
10543 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
10544 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
10548 printf ("Added %d methods from profile.\n", count);
10552 init_got_info (GotInfo *info)
10556 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10557 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10558 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10559 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10560 info->got_patches = g_ptr_array_new ();
10563 static MonoAotCompile*
10564 acfg_create (MonoAssembly *ass, guint32 opts)
10566 MonoImage *image = ass->image;
10567 MonoAotCompile *acfg;
10569 acfg = g_new0 (MonoAotCompile, 1);
10570 acfg->methods = g_ptr_array_new ();
10571 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10572 acfg->method_depth = g_hash_table_new (NULL, NULL);
10573 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10574 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10575 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10576 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10577 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10578 acfg->image_hash = g_hash_table_new (NULL, NULL);
10579 acfg->image_table = g_ptr_array_new ();
10580 acfg->globals = g_ptr_array_new ();
10581 acfg->image = image;
10583 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10584 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10585 acfg->mempool = mono_mempool_new ();
10586 acfg->extra_methods = g_ptr_array_new ();
10587 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10588 acfg->unwind_ops = g_ptr_array_new ();
10589 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10590 acfg->method_order = g_ptr_array_new ();
10591 acfg->export_names = g_hash_table_new (NULL, NULL);
10592 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10593 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10594 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10595 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10596 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10597 mono_os_mutex_init_recursive (&acfg->mutex);
10599 init_got_info (&acfg->got_info);
10600 init_got_info (&acfg->llvm_got_info);
10606 got_info_free (GotInfo *info)
10610 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10611 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10612 g_free (info->patch_to_got_offset_by_type);
10613 g_hash_table_destroy (info->patch_to_got_offset);
10614 g_ptr_array_free (info->got_patches, TRUE);
10618 acfg_free (MonoAotCompile *acfg)
10622 mono_img_writer_destroy (acfg->w);
10623 for (i = 0; i < acfg->nmethods; ++i)
10624 if (acfg->cfgs [i])
10625 mono_destroy_compile (acfg->cfgs [i]);
10627 g_free (acfg->cfgs);
10629 g_free (acfg->static_linking_symbol);
10630 g_free (acfg->got_symbol);
10631 g_free (acfg->plt_symbol);
10632 g_ptr_array_free (acfg->methods, TRUE);
10633 g_ptr_array_free (acfg->image_table, TRUE);
10634 g_ptr_array_free (acfg->globals, TRUE);
10635 g_ptr_array_free (acfg->unwind_ops, TRUE);
10636 g_hash_table_destroy (acfg->method_indexes);
10637 g_hash_table_destroy (acfg->method_depth);
10638 g_hash_table_destroy (acfg->plt_offset_to_entry);
10639 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10640 if (acfg->patch_to_plt_entry [i])
10641 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10643 g_free (acfg->patch_to_plt_entry);
10644 g_hash_table_destroy (acfg->method_to_cfg);
10645 g_hash_table_destroy (acfg->token_info_hash);
10646 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10647 g_hash_table_destroy (acfg->image_hash);
10648 g_hash_table_destroy (acfg->unwind_info_offsets);
10649 g_hash_table_destroy (acfg->method_label_hash);
10650 if (acfg->typespec_classes)
10651 g_hash_table_destroy (acfg->typespec_classes);
10652 g_hash_table_destroy (acfg->export_names);
10653 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10654 g_hash_table_destroy (acfg->klass_blob_hash);
10655 g_hash_table_destroy (acfg->method_blob_hash);
10656 got_info_free (&acfg->got_info);
10657 got_info_free (&acfg->llvm_got_info);
10658 mono_mempool_destroy (acfg->mempool);
10662 #define WRAPPER(e,n) n,
10663 static const char* const
10664 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10665 #include "mono/metadata/wrapper-types.h"
10669 static G_GNUC_UNUSED const char*
10670 get_wrapper_type_name (int type)
10672 return wrapper_type_names [type];
10678 static void aot_dump (MonoAotCompile *acfg)
10684 mono_json_writer_init (&writer);
10686 mono_json_writer_object_begin(&writer);
10689 mono_json_writer_indent (&writer);
10690 mono_json_writer_object_key(&writer, "methods");
10691 mono_json_writer_array_begin (&writer);
10694 for (i = 0; i < acfg->nmethods; ++i) {
10696 MonoMethod *method;
10699 cfg = acfg->cfgs [i];
10703 method = cfg->orig_method;
10705 mono_json_writer_indent (&writer);
10706 mono_json_writer_object_begin(&writer);
10708 mono_json_writer_indent (&writer);
10709 mono_json_writer_object_key(&writer, "name");
10710 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10712 mono_json_writer_indent (&writer);
10713 mono_json_writer_object_key(&writer, "signature");
10714 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10716 mono_json_writer_indent (&writer);
10717 mono_json_writer_object_key(&writer, "code_size");
10718 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10720 klass = method->klass;
10722 mono_json_writer_indent (&writer);
10723 mono_json_writer_object_key(&writer, "class");
10724 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10726 mono_json_writer_indent (&writer);
10727 mono_json_writer_object_key(&writer, "namespace");
10728 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10730 mono_json_writer_indent (&writer);
10731 mono_json_writer_object_key(&writer, "wrapper_type");
10732 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10734 mono_json_writer_indent_pop (&writer);
10735 mono_json_writer_indent (&writer);
10736 mono_json_writer_object_end (&writer);
10737 mono_json_writer_printf (&writer, ",\n");
10740 mono_json_writer_indent_pop (&writer);
10741 mono_json_writer_indent (&writer);
10742 mono_json_writer_array_end (&writer);
10743 mono_json_writer_printf (&writer, ",\n");
10747 mono_json_writer_indent_push (&writer);
10748 mono_json_writer_indent (&writer);
10749 mono_json_writer_object_key(&writer, "plt");
10750 mono_json_writer_array_begin (&writer);
10752 for (i = 0; i < acfg->plt_offset; ++i) {
10753 MonoPltEntry *plt_entry = NULL;
10758 * The first plt entry is unused.
10762 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10763 ji = plt_entry->ji;
10765 mono_json_writer_indent (&writer);
10766 mono_json_writer_printf (&writer, "{ ");
10767 mono_json_writer_object_key(&writer, "symbol");
10768 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10771 mono_json_writer_indent_pop (&writer);
10772 mono_json_writer_indent (&writer);
10773 mono_json_writer_array_end (&writer);
10774 mono_json_writer_printf (&writer, ",\n");
10779 mono_json_writer_indent_push (&writer);
10780 mono_json_writer_indent (&writer);
10781 mono_json_writer_object_key(&writer, "got");
10782 mono_json_writer_array_begin (&writer);
10784 mono_json_writer_indent_push (&writer);
10785 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10786 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10788 mono_json_writer_indent (&writer);
10789 mono_json_writer_printf (&writer, "{ ");
10790 mono_json_writer_object_key(&writer, "patch_name");
10791 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10794 mono_json_writer_indent_pop (&writer);
10795 mono_json_writer_indent (&writer);
10796 mono_json_writer_array_end (&writer);
10797 mono_json_writer_printf (&writer, ",\n");
10800 mono_json_writer_indent_pop (&writer);
10801 mono_json_writer_indent (&writer);
10802 mono_json_writer_object_end (&writer);
10804 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10805 dumpfile = fopen (dumpname, "w+");
10808 fprintf (dumpfile, "%s", writer.text->str);
10811 mono_json_writer_destroy (&writer);
10814 static const char *preinited_jit_icalls[] = {
10815 "mono_aot_init_llvm_method",
10816 "mono_aot_init_gshared_method_this",
10817 "mono_aot_init_gshared_method_mrgctx",
10818 "mono_aot_init_gshared_method_vtable",
10819 "mono_llvm_throw_corlib_exception",
10820 "mono_init_vtable_slot",
10821 "mono_helper_ldstr_mscorlib"
10825 add_preinit_got_slots (MonoAotCompile *acfg)
10831 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10832 * during method initialization etc.
10835 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10836 ji->type = MONO_PATCH_INFO_IMAGE;
10837 ji->data.image = acfg->image;
10838 get_got_offset (acfg, FALSE, ji);
10839 get_got_offset (acfg, TRUE, ji);
10841 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10842 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10843 get_got_offset (acfg, FALSE, ji);
10844 get_got_offset (acfg, TRUE, ji);
10846 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10847 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10848 get_got_offset (acfg, FALSE, ji);
10849 get_got_offset (acfg, TRUE, ji);
10851 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10852 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10853 get_got_offset (acfg, FALSE, ji);
10854 get_got_offset (acfg, TRUE, ji);
10856 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10857 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10858 get_got_offset (acfg, FALSE, ji);
10859 get_got_offset (acfg, TRUE, ji);
10861 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10862 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10863 get_got_offset (acfg, FALSE, ji);
10864 get_got_offset (acfg, TRUE, ji);
10866 for (i = 0; i < TLS_KEY_NUM; i++) {
10867 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10868 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
10869 ji->data.index = i;
10870 get_got_offset (acfg, FALSE, ji);
10871 get_got_offset (acfg, TRUE, ji);
10873 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10874 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
10875 ji->data.index = i;
10876 get_got_offset (acfg, FALSE, ji);
10877 get_got_offset (acfg, TRUE, ji);
10880 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10881 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
10882 get_got_offset (acfg, FALSE, ji);
10883 get_got_offset (acfg, TRUE, ji);
10885 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10886 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10887 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10888 ji->data.name = preinited_jit_icalls [i];
10889 get_got_offset (acfg, FALSE, ji);
10890 get_got_offset (acfg, TRUE, ji);
10893 acfg->nshared_got_entries = acfg->got_offset;
10897 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10899 MonoImage *image = ass->image;
10902 MonoAotCompile *acfg;
10903 char *outfile_name, *tmp_outfile_name, *p;
10904 char llvm_stats_msg [256];
10908 acfg = acfg_create (ass, opts);
10910 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10911 acfg->aot_opts.write_symbols = TRUE;
10912 acfg->aot_opts.ntrampolines = 4096;
10913 acfg->aot_opts.nrgctx_trampolines = 4096;
10914 acfg->aot_opts.nimt_trampolines = 512;
10915 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10916 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10917 acfg->aot_opts.llvm_path = g_strdup ("");
10918 acfg->aot_opts.temp_path = g_strdup ("");
10920 acfg->aot_opts.use_trampolines_page = TRUE;
10923 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10925 if (acfg->aot_opts.logfile) {
10926 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10929 if (acfg->aot_opts.data_outfile) {
10930 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10931 if (!acfg->data_outfile) {
10932 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10935 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10938 //acfg->aot_opts.print_skipped_methods = TRUE;
10940 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10941 if (acfg->opts & MONO_OPT_GSHAREDVT) {
10942 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10945 if (acfg->aot_opts.llvm_only) {
10946 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10950 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10951 acfg->opts |= MONO_OPT_GSHAREDVT;
10954 #if !defined(ENABLE_LLVM)
10955 if (acfg->aot_opts.llvm_only) {
10956 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
10961 if (acfg->opts & MONO_OPT_GSHAREDVT)
10962 mono_set_generic_sharing_vt_supported (TRUE);
10964 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10966 generate_aotid ((guint8*) &acfg->image->aotid);
10968 char *aotid = mono_guid_to_string (acfg->image->aotid);
10969 aot_printf (acfg, "AOTID %s\n", aotid);
10972 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10973 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10974 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10979 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10980 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10984 if (acfg->aot_opts.static_link)
10985 acfg->aot_opts.asm_writer = TRUE;
10987 if (acfg->aot_opts.soft_debug) {
10988 MonoDebugOptions *opt = mini_get_debug_options ();
10990 opt->mdb_optimizations = TRUE;
10991 opt->gen_sdb_seq_points = TRUE;
10993 if (!mono_debug_enabled ()) {
10994 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10997 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11000 if (mono_use_llvm || acfg->aot_opts.llvm) {
11002 acfg->aot_opts.asm_writer = TRUE;
11003 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11005 if (acfg->aot_opts.soft_debug) {
11006 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11012 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11013 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11018 if (mono_aot_mode_is_full (&acfg->aot_opts))
11019 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11021 if (mono_threads_is_coop_enabled ())
11022 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11024 if (acfg->aot_opts.instances_logfile_path) {
11025 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11026 if (!acfg->instances_logfile) {
11027 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11032 if (acfg->aot_opts.profile_files) {
11035 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11036 load_profile_file (acfg, (char*)l->data);
11043 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11044 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11048 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11049 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11050 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11052 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11053 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11054 if (acfg->opts & MONO_OPT_GSHAREDVT)
11055 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11058 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11062 if (mono_use_llvm || acfg->aot_opts.llvm) {
11065 * Emit all LLVM code into a separate assembly/object file and link with it
11068 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11069 acfg->llvm_owriter = TRUE;
11070 } else if (acfg->aot_opts.llvm_outfile) {
11071 int len = strlen (acfg->aot_opts.llvm_outfile);
11073 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11074 acfg->llvm_owriter = TRUE;
11078 if (acfg->llvm && acfg->thumb_mixed)
11079 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11080 if (acfg->aot_opts.llvm_only)
11081 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11083 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11084 /* Get rid of characters which cannot occur in symbols */
11085 for (p = acfg->assembly_name_sym; *p; ++p) {
11086 if (!(isalnum (*p) || *p == '_'))
11090 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11091 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11092 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11094 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11095 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11098 acfg->method_index = 1;
11100 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11101 mono_set_partial_sharing_supported (TRUE);
11103 res = collect_methods (acfg);
11110 for (l = acfg->profile_data; l; l = l->next)
11111 resolve_profile_data (acfg, (ProfileData*)l->data);
11112 for (l = acfg->profile_data; l; l = l->next)
11113 add_profile_instances (acfg, (ProfileData*)l->data);
11116 acfg->cfgs_size = acfg->methods->len + 32;
11117 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11119 /* PLT offset 0 is reserved for the PLT trampoline */
11120 acfg->plt_offset = 1;
11121 add_preinit_got_slots (acfg);
11126 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11132 compile_methods (acfg);
11136 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11142 if (acfg->aot_opts.asm_only) {
11143 if (acfg->aot_opts.outfile) {
11144 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11145 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11147 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11148 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11150 g_assert (acfg->aot_opts.llvm_outfile);
11151 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11152 if (acfg->llvm_owriter)
11153 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11155 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11157 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11158 g_strdup_printf ("%s", "temp") :
11159 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11161 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11162 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11163 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11168 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11169 if (acfg->aot_opts.outfile)
11170 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11172 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11173 acfg->fp = fopen (acfg->tmpfname, "w+");
11175 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11176 acfg->fp = fdopen (i, "w+");
11178 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11179 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11183 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11185 tmp_outfile_name = NULL;
11186 outfile_name = NULL;
11188 /* Compute symbols for methods */
11189 for (i = 0; i < acfg->nmethods; ++i) {
11190 if (acfg->cfgs [i]) {
11191 MonoCompile *cfg = acfg->cfgs [i];
11192 int method_index = get_method_index (acfg, cfg->orig_method);
11194 if (COMPILE_LLVM (cfg))
11195 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11196 else if (acfg->global_symbols || acfg->llvm)
11197 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11199 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11200 cfg->asm_debug_symbol = cfg->asm_symbol;
11204 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11206 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11208 acfg->gas_line_numbers = TRUE;
11211 #ifdef EMIT_DWARF_INFO
11212 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11213 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11214 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11217 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11219 #endif /* EMIT_DWARF_INFO */
11222 mono_img_writer_emit_start (acfg->w);
11225 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11231 emit_extra_methods (acfg);
11233 emit_trampolines (acfg);
11235 emit_class_name_table (acfg);
11237 emit_got_info (acfg, FALSE);
11239 emit_got_info (acfg, TRUE);
11241 emit_exception_info (acfg);
11243 emit_unwind_info (acfg);
11245 emit_class_info (acfg);
11249 emit_image_table (acfg);
11255 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11258 const char *gc_name = mono_gc_get_gc_name ();
11259 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11264 emit_objc_selectors (acfg);
11266 emit_globals (acfg);
11268 emit_file_info (acfg);
11270 emit_library_info (acfg);
11273 emit_dwarf_info (acfg);
11274 mono_dwarf_writer_close (acfg->dwarf);
11277 emit_mem_end (acfg);
11279 if (acfg->need_pt_gnu_stack) {
11280 /* This is required so the .so doesn't have an executable stack */
11281 /* The bin writer already emits this */
11282 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11285 if (acfg->aot_opts.data_outfile)
11286 fclose (acfg->data_outfile);
11292 res = emit_llvm_file (acfg);
11300 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11303 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11305 strcpy (llvm_stats_msg, "");
11307 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;
11309 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",
11310 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11311 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11312 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11313 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11314 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11315 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,
11316 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11317 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11318 (int)(acfg->got_offset * sizeof (gpointer)));
11319 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11320 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11322 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11323 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11324 if (acfg->stats.genericcount)
11325 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11326 if (acfg->stats.abscount)
11327 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11328 if (acfg->stats.lmfcount)
11329 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11330 if (acfg->stats.ocount)
11331 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11335 res = mono_img_writer_emit_writeout (acfg->w);
11340 res = compile_asm (acfg);
11347 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11349 if (acfg->aot_opts.stats) {
11352 aot_printf (acfg, "GOT slot distribution:\n");
11353 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11354 if (acfg->stats.got_slot_types [i])
11355 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]);
11356 aot_printf (acfg, "\nMethod stats:\n");
11357 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11358 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11359 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11360 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11363 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);
11365 if (acfg->aot_opts.dump_json)
11378 mono_aot_readonly_field_override (MonoClassField *field)
11384 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11390 mono_aot_is_shared_got_offset (int offset)