3 * mono Ahead of Time compiler
6 * Dietmar Maurer (dietmar@ximian.com)
7 * Zoltan Varga (vargaz@gmail.com)
8 * Johan Lorensson (lateralusx.github@gmail.com)
10 * (C) 2002 Ximian, Inc.
11 * Copyright 2003-2011 Novell, Inc
12 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 #include <sys/types.h>
37 #include <mono/metadata/abi-details.h>
38 #include <mono/metadata/tabledefs.h>
39 #include <mono/metadata/class.h>
40 #include <mono/metadata/object.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/appdomain.h>
43 #include <mono/metadata/debug-helpers.h>
44 #include <mono/metadata/assembly.h>
45 #include <mono/metadata/metadata-internals.h>
46 #include <mono/metadata/reflection-internals.h>
47 #include <mono/metadata/marshal.h>
48 #include <mono/metadata/gc-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/mono-endian.h>
51 #include <mono/metadata/threads-types.h>
52 #include <mono/utils/mono-logger-internals.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-time.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/mono-rand.h>
57 #include <mono/utils/json.h>
58 #include <mono/utils/mono-threads-coop.h>
59 #include <mono/profiler/mono-profiler-aot.h>
60 #include <mono/utils/w32api.h>
62 #include "aot-compiler.h"
63 #include "seq-points.h"
64 #include "image-writer.h"
65 #include "dwarfwriter.h"
67 #include "mini-llvm.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
72 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
73 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
74 #define TARGET_X86_64_WIN32_MSVC
77 #if defined(TARGET_X86_64_WIN32_MSVC)
78 #define TARGET_WIN32_MSVC
81 #if defined(__linux__) || defined(__native_client_codegen__)
82 #define RODATA_SECT ".rodata"
83 #elif defined(TARGET_MACH)
84 #define RODATA_SECT ".section __TEXT, __const"
85 #elif defined(TARGET_WIN32_MSVC)
86 #define RODATA_SECT ".rdata"
88 #define RODATA_SECT ".text"
91 #define TV_DECLARE(name) gint64 name
92 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
93 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
95 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
96 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
97 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
104 typedef struct ClassProfileData ClassProfileData;
108 ClassProfileData **argv;
109 MonoGenericInst *inst;
112 struct ClassProfileData {
113 ImageProfileData *image;
115 GInstProfileData *inst;
120 ClassProfileData *klass;
125 GInstProfileData *inst;
130 GHashTable *images, *classes, *ginsts, *methods;
133 /* predefined values for static readonly fields without needed to run the .cctor */
134 typedef struct _ReadOnlyValue ReadOnlyValue;
135 struct _ReadOnlyValue {
138 int type; /* to be used later for typechecking to prevent user errors */
147 static ReadOnlyValue *readonly_values;
149 typedef struct MonoAotOptions {
153 GList *profile_files;
155 gboolean write_symbols;
156 gboolean metadata_only;
157 gboolean bind_to_runtime_version;
160 gboolean static_link;
164 gboolean dwarf_debug;
166 gboolean log_generics;
167 gboolean log_instances;
168 gboolean gen_msym_dir;
169 char *gen_msym_dir_path;
170 gboolean direct_pinvoke;
171 gboolean direct_icalls;
172 gboolean no_direct_calls;
173 gboolean use_trampolines_page;
174 gboolean no_instances;
180 int nrgctx_trampolines;
181 int nimt_trampolines;
182 int ngsharedvt_arg_trampolines;
183 int nrgctx_fetch_trampolines;
184 gboolean print_skipped_methods;
192 char *instances_logfile_path;
195 gboolean profile_only;
200 METHOD_CAT_GSHAREDVT,
206 typedef struct MonoAotStats {
207 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
208 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
209 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
210 int got_slots, offsets_size;
211 int method_categories [METHOD_CAT_NUM];
212 int got_slot_types [MONO_PATCH_INFO_NUM];
213 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
214 int jit_time, gen_time, link_time;
217 typedef struct GotInfo {
218 GHashTable *patch_to_got_offset;
219 GHashTable **patch_to_got_offset_by_type;
220 GPtrArray *got_patches;
223 typedef struct MonoAotCompile {
226 GHashTable *method_indexes;
227 GHashTable *method_depth;
230 GHashTable **patch_to_plt_entry;
231 GHashTable *plt_offset_to_entry;
232 //GHashTable *patch_to_got_offset;
233 //GHashTable **patch_to_got_offset_by_type;
234 //GPtrArray *got_patches;
235 GotInfo got_info, llvm_got_info;
236 GHashTable *image_hash;
237 GHashTable *method_to_cfg;
238 GHashTable *token_info_hash;
239 GHashTable *method_to_pinvoke_import;
240 GPtrArray *extra_methods;
241 GPtrArray *image_table;
243 GPtrArray *method_order;
244 GHashTable *export_names;
245 /* Maps MonoClass* -> blob offset */
246 GHashTable *klass_blob_hash;
247 /* Maps MonoMethod* -> blob offset */
248 GHashTable *method_blob_hash;
249 GHashTable *gsharedvt_in_signatures;
250 GHashTable *gsharedvt_out_signatures;
251 guint32 *plt_got_info_offsets;
252 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
253 /* Number of GOT entries reserved for trampolines */
254 guint32 num_trampoline_got_entries;
255 guint32 tramp_page_size;
257 guint32 table_offsets [MONO_AOT_TABLE_NUM];
258 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
259 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
260 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
261 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
263 MonoAotOptions aot_opts;
267 MonoMemPool *mempool;
270 char *static_linking_symbol;
272 gboolean gas_line_numbers;
273 /* Whenever to emit an object file directly from llc */
274 gboolean llvm_owriter;
275 gboolean llvm_owriter_supported;
277 MonoDwarfWriter *dwarf;
284 GHashTable *unwind_info_offsets;
285 GPtrArray *unwind_ops;
286 guint32 unwind_info_offset;
289 char *llvm_got_symbol;
291 char *llvm_eh_frame_symbol;
292 GHashTable *method_label_hash;
293 const char *temp_prefix;
294 const char *user_symbol_prefix;
295 const char *llvm_label_prefix;
296 const char *inst_directive;
298 guint32 label_generator;
300 gboolean has_jitted_code;
301 gboolean is_full_aot;
302 MonoAotFileFlags flags;
303 MonoDynamicStream blob;
304 gboolean blob_closed;
305 GHashTable *typespec_classes;
308 char *assembly_name_sym;
309 GHashTable *plt_entry_debug_sym_cache;
310 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
311 GHashTable *ginst_hash;
312 GHashTable *dwarf_ln_filenames;
313 gboolean global_symbols;
314 int objc_selector_index, objc_selector_index_2;
315 GPtrArray *objc_selectors;
316 GHashTable *objc_selector_to_index;
318 GHashTable *profile_methods;
320 FILE *instances_logfile;
328 char *symbol, *llvm_symbol, *debug_sym;
330 gboolean jit_used, llvm_used;
333 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
334 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
336 /* This points to the current acfg in LLVM mode */
337 static MonoAotCompile *llvm_acfg;
339 #ifdef HAVE_ARRAY_ELEM_INIT
340 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
341 #define MSGSTRFIELD1(line) str##line
342 static const struct msgstr_t {
343 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
344 #include "patch-info.h"
347 #define PATCH_INFO(a,b) b,
348 #include "patch-info.h"
351 static const gint16 opidx [] = {
352 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
353 #include "patch-info.h"
357 static G_GNUC_UNUSED const char*
358 get_patch_name (int info)
360 return (const char*)&opstr + opidx [info];
364 #define PATCH_INFO(a,b) b,
365 static const char* const
366 patch_types [MONO_PATCH_INFO_NUM + 1] = {
367 #include "patch-info.h"
371 static G_GNUC_UNUSED const char*
372 get_patch_name (int info)
374 return patch_types [info];
380 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
383 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
386 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
389 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
392 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
398 output = acfg->logfile;
402 va_start (args, format);
403 vfprintf (output, format, args);
408 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
414 output = acfg->logfile;
418 va_start (args, format);
419 vfprintf (output, format, args);
424 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
429 if (mono_error_ok (error))
433 output = acfg->logfile;
437 va_start (args, format);
438 vfprintf (output, format, args);
440 mono_error_cleanup (error);
442 if (acfg->is_full_aot) {
443 fprintf (output, "FullAOT cannot continue if there are loader errors.\n");
448 /* Wrappers around the image writer functions */
450 #define MAX_SYMBOL_SIZE 256
452 static inline const char *
453 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
455 gsize needed_size = length;
457 g_assert (NULL != symbol);
458 g_assert (NULL != mangled_symbol);
459 g_assert (0 != length);
461 #if defined(TARGET_WIN32) && defined(TARGET_X86)
462 if (symbol && '_' != symbol [0]) {
463 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
465 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
468 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
471 g_assert (0 <= needed_size && needed_size < length);
472 return mangled_symbol;
476 mangle_symbol_alloc (const char * symbol)
478 g_assert (NULL != symbol);
480 #if defined(TARGET_WIN32) && defined(TARGET_X86)
481 if (symbol && '_' != symbol [0]) {
482 return g_strdup_printf ("_%s", symbol);
485 return g_strdup_printf ("%s", symbol);
488 return g_strdup_printf ("%s", symbol);
493 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
495 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
498 #if defined(TARGET_WIN32) && defined(TARGET_X86)
501 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
503 const char * mangled_symbol_name = name;
504 char * mangled_symbol_name_alloc = NULL;
507 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
508 mangled_symbol_name = mangled_symbol_name_alloc;
511 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
512 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
514 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
516 if (NULL != mangled_symbol_name_alloc) {
517 g_free (mangled_symbol_name_alloc);
524 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
526 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
532 emit_label (MonoAotCompile *acfg, const char *name)
534 mono_img_writer_emit_label (acfg->w, name);
538 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
540 mono_img_writer_emit_bytes (acfg->w, buf, size);
544 emit_string (MonoAotCompile *acfg, const char *value)
546 mono_img_writer_emit_string (acfg->w, value);
550 emit_line (MonoAotCompile *acfg)
552 mono_img_writer_emit_line (acfg->w);
556 emit_alignment (MonoAotCompile *acfg, int size)
558 mono_img_writer_emit_alignment (acfg->w, size);
562 emit_alignment_code (MonoAotCompile *acfg, int size)
564 if (acfg->align_pad_value)
565 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
567 mono_img_writer_emit_alignment (acfg->w, size);
571 emit_padding (MonoAotCompile *acfg, int size)
576 if (acfg->align_pad_value) {
577 for (i = 0; i < 16; ++i)
578 buf [i] = acfg->align_pad_value;
580 memset (buf, 0, sizeof (buf));
583 for (i = 0; i < size; i += 16) {
585 emit_bytes (acfg, buf, size - i);
587 emit_bytes (acfg, buf, 16);
592 emit_pointer (MonoAotCompile *acfg, const char *target)
594 mono_img_writer_emit_pointer (acfg->w, target);
598 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
600 if (prefix [0] != '\0') {
601 char *s = g_strdup_printf ("%s%s", prefix, target);
602 mono_img_writer_emit_pointer (acfg->w, s);
605 mono_img_writer_emit_pointer (acfg->w, target);
610 emit_int16 (MonoAotCompile *acfg, int value)
612 mono_img_writer_emit_int16 (acfg->w, value);
616 emit_int32 (MonoAotCompile *acfg, int value)
618 mono_img_writer_emit_int32 (acfg->w, value);
622 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
624 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
628 emit_zero_bytes (MonoAotCompile *acfg, int num)
630 mono_img_writer_emit_zero_bytes (acfg->w, num);
634 emit_byte (MonoAotCompile *acfg, guint8 val)
636 mono_img_writer_emit_byte (acfg->w, val);
639 #if defined(TARGET_WIN32) && defined(TARGET_X86)
641 static G_GNUC_UNUSED void
642 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
644 const char * mangled_symbol_name = name;
645 char * mangled_symbol_name_alloc = NULL;
647 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
648 mangled_symbol_name = mangled_symbol_name_alloc;
650 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
651 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
653 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
655 if (NULL != mangled_symbol_name_alloc) {
656 g_free (mangled_symbol_name_alloc);
662 static G_GNUC_UNUSED void
663 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
665 mono_img_writer_emit_global (acfg->w, name, func);
670 static inline gboolean
671 link_shared_library (MonoAotCompile *acfg)
673 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
676 static inline gboolean
677 add_to_global_symbol_table (MonoAotCompile *acfg)
679 #ifdef TARGET_WIN32_MSVC
680 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
682 return acfg->aot_opts.no_dlsym;
687 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
689 if (add_to_global_symbol_table (acfg))
690 g_ptr_array_add (acfg->globals, g_strdup (name));
692 if (acfg->aot_opts.no_dlsym) {
693 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
695 emit_global_inner (acfg, name, func);
700 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
702 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
705 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
707 emit_info_symbol (MonoAotCompile *acfg, const char *name)
709 char symbol [MAX_SYMBOL_SIZE];
712 emit_label (acfg, name);
713 /* LLVM generated code references this */
714 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
715 emit_label (acfg, symbol);
716 emit_global_inner (acfg, symbol, FALSE);
718 emit_label (acfg, name);
723 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
726 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
730 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
732 /* On apple, all symbols need to be aligned to avoid warnings from ld */
733 emit_alignment (acfg, 4);
735 mono_img_writer_emit_label (acfg->w, name);
736 mono_img_writer_emit_string (acfg->w, value);
739 static G_GNUC_UNUSED void
740 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
743 guint8 b = value & 0x7f;
745 if (value != 0) /* more bytes to come */
751 static G_GNUC_UNUSED void
752 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
755 gboolean negative = (value < 0);
762 /* the following is unnecessary if the
763 * implementation of >>= uses an arithmetic rather
764 * than logical shift for a signed left operand
768 value |= - ((gint64)1 <<(size - 7));
769 /* sign bit of byte is second high order bit (0x40) */
770 if ((value == 0 && !(byte & 0x40)) ||
771 (value == -1 && (byte & 0x40)))
775 emit_byte (acfg, byte);
779 static G_GNUC_UNUSED void
780 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
785 guint8 b = value & 0x7f;
787 if (value != 0) /* more bytes to come */
795 static G_GNUC_UNUSED void
796 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
799 gboolean negative = (value < 0);
807 /* the following is unnecessary if the
808 * implementation of >>= uses an arithmetic rather
809 * than logical shift for a signed left operand
813 value |= - (1 <<(size - 7));
814 /* sign bit of byte is second high order bit (0x40) */
815 if ((value == 0 && !(byte & 0x40)) ||
816 (value == -1 && (byte & 0x40)))
827 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
830 buf [0] = (val >> 0) & 0xff;
831 buf [1] = (val >> 8) & 0xff;
832 buf [2] = (val >> 16) & 0xff;
833 buf [3] = (val >> 24) & 0xff;
839 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
841 buf [0] = (val >> 0) & 0xff;
842 buf [1] = (val >> 8) & 0xff;
848 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
850 int len = strlen (s);
852 memcpy (buf, s, len + 1);
853 *endbuf = buf + len + 1;
857 emit_unset_mode (MonoAotCompile *acfg)
859 mono_img_writer_emit_unset_mode (acfg->w);
862 static G_GNUC_UNUSED void
863 emit_set_thumb_mode (MonoAotCompile *acfg)
865 emit_unset_mode (acfg);
866 fprintf (acfg->fp, ".code 16\n");
869 static G_GNUC_UNUSED void
870 emit_set_arm_mode (MonoAotCompile *acfg)
872 emit_unset_mode (acfg);
873 fprintf (acfg->fp, ".code 32\n");
877 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
882 g_assert (size % 4 == 0);
883 emit_unset_mode (acfg);
884 for (i = 0; i < size; i += 4)
885 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
887 emit_bytes (acfg, buf, size);
891 /* ARCHITECTURE SPECIFIC CODE */
893 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
894 #define EMIT_DWARF_INFO 1
897 #ifdef TARGET_WIN32_MSVC
898 #undef EMIT_DWARF_INFO
901 #if defined(TARGET_ARM)
902 #define AOT_FUNC_ALIGNMENT 4
904 #define AOT_FUNC_ALIGNMENT 16
907 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
908 #define PPC_LD_OP "ld"
909 #define PPC_LDX_OP "ldx"
911 #define PPC_LD_OP "lwz"
912 #define PPC_LDX_OP "lwzx"
915 #ifdef TARGET_X86_64_WIN32_MSVC
916 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
918 #define AOT_TARGET_STR "AMD64"
923 #define AOT_TARGET_STR "ARM (MACH)"
925 #define AOT_TARGET_STR "ARM (!MACH)"
931 #define AOT_TARGET_STR "ARM64 (MACH)"
933 #define AOT_TARGET_STR "ARM64 (!MACH)"
937 #ifdef TARGET_POWERPC64
938 #ifdef __mono_ilp32__
939 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
941 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
944 #ifdef TARGET_POWERPC
945 #ifdef __mono_ilp32__
946 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
948 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
955 #define AOT_TARGET_STR "X86 (WIN32)"
956 #elif defined(__native_client_codegen__)
957 #define AOT_TARGET_STR "X86 (native client codegen)"
959 #define AOT_TARGET_STR "X86 (!native client codegen)"
963 #ifndef AOT_TARGET_STR
964 #define AOT_TARGET_STR ""
968 arch_init (MonoAotCompile *acfg)
970 acfg->llc_args = g_string_new ("");
971 acfg->as_args = g_string_new ("");
972 acfg->llvm_owriter_supported = TRUE;
975 * The prefix LLVM likes to put in front of symbol names on darwin.
976 * The mach-os specs require this for globals, but LLVM puts them in front of all
977 * symbols. We need to handle this, since we need to refer to LLVM generated
980 acfg->llvm_label_prefix = "";
981 acfg->user_symbol_prefix = "";
983 #if defined(TARGET_X86)
984 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
987 #if defined(TARGET_AMD64)
988 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
990 acfg->align_pad_value = 0x90;
994 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
995 g_string_append (acfg->llc_args, "-mattr=+v6");
997 #if defined(ARM_FPU_VFP_HARD)
998 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
999 g_string_append (acfg->as_args, " -mfpu=vfp3");
1000 #elif defined(ARM_FPU_VFP)
1001 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
1002 g_string_append (acfg->as_args, " -mfpu=vfp3");
1004 g_string_append (acfg->llc_args, " -soft-float");
1007 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1008 acfg->thumb_mixed = TRUE;
1010 if (acfg->aot_opts.mtriple)
1011 mono_arch_set_target (acfg->aot_opts.mtriple);
1015 acfg->inst_directive = ".inst";
1016 if (acfg->aot_opts.mtriple)
1017 mono_arch_set_target (acfg->aot_opts.mtriple);
1021 acfg->user_symbol_prefix = "_";
1022 acfg->llvm_label_prefix = "_";
1023 acfg->inst_directive = ".word";
1024 acfg->need_no_dead_strip = TRUE;
1025 acfg->aot_opts.gnu_asm = TRUE;
1028 #if defined(__linux__) && !defined(TARGET_ARM)
1029 acfg->need_pt_gnu_stack = TRUE;
1033 acfg->global_symbols = TRUE;
1036 #ifdef TARGET_ANDROID
1037 acfg->llvm_owriter_supported = FALSE;
1044 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1046 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1050 g_assert (acfg->fp);
1051 emit_unset_mode (acfg);
1053 offset = (int)(got_slot * sizeof (gpointer));
1055 /* clang's integrated assembler */
1056 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1057 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1058 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1061 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1062 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1063 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1068 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1072 g_assert (acfg->fp);
1073 emit_unset_mode (acfg);
1075 /* ldr rt, target */
1076 reg = arm_get_ldr_lit_reg (code);
1078 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1079 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1080 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1086 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1088 g_assert (acfg->fp);
1089 emit_unset_mode (acfg);
1090 if (ji && ji->relocation == MONO_R_ARM64_B) {
1091 fprintf (acfg->fp, "b %s\n", target);
1094 g_assert (ji->relocation == MONO_R_ARM64_BL);
1095 fprintf (acfg->fp, "bl %s\n", target);
1101 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1105 /* ldr rt, target */
1106 reg = arm_get_ldr_lit_reg (code);
1107 arm64_emit_load_got_slot (acfg, reg, got_slot);
1112 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1114 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1115 fprintf (acfg->fp, "br x16\n");
1116 /* Used by mono_aot_get_plt_info_offset () */
1117 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1121 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1127 /* The common code */
1130 /* The trampoline address is in IP0 */
1131 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1132 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1133 /* Compute the data slot address */
1134 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1135 /* Trampoline argument */
1136 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1138 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1139 arm_brx (code, ARMREG_IP0);
1142 emit_code_bytes (acfg, buf, code - buf);
1148 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1154 count = (pagesize - common_tramp_size) / specific_tramp_size;
1155 for (i = 0; i < count; ++i) {
1157 arm_adrx (code, ARMREG_IP0, code);
1158 /* Branch to the generic code */
1159 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1160 /* This has to be 2 pointers long */
1163 g_assert (code - buf == specific_tramp_size);
1164 emit_code_bytes (acfg, buf, code - buf);
1169 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1173 guint8 *labels [16];
1174 int common_tramp_size;
1175 int specific_tramp_size = 2 * 8;
1179 if (!acfg->aot_opts.use_trampolines_page)
1183 /* Have to match the target pagesize */
1186 pagesize = mono_pagesize ();
1188 acfg->tramp_page_size = pagesize;
1190 /* The specific trampolines */
1191 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1192 emit_alignment (acfg, pagesize);
1193 emit_global (acfg, symbol, TRUE);
1194 emit_label (acfg, symbol);
1196 /* The common code */
1197 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1198 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1200 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1202 /* The rgctx trampolines */
1203 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1204 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1205 emit_alignment (acfg, pagesize);
1206 emit_global (acfg, symbol, TRUE);
1207 emit_label (acfg, symbol);
1209 /* The common code */
1210 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1211 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1213 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1215 /* The gsharedvt arg trampolines */
1216 /* These are the same as the specific trampolines */
1217 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1218 emit_alignment (acfg, pagesize);
1219 emit_global (acfg, symbol, TRUE);
1220 emit_label (acfg, symbol);
1222 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1223 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1225 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1227 /* The IMT trampolines */
1228 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1229 emit_alignment (acfg, pagesize);
1230 emit_global (acfg, symbol, TRUE);
1231 emit_label (acfg, symbol);
1235 /* The trampoline address is in IP0 */
1236 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1237 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1238 /* Compute the data slot address */
1239 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1240 /* Trampoline argument */
1241 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1243 /* Same as arch_emit_imt_trampoline () */
1245 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1246 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1248 arm_bcc (code, ARMCOND_EQ, 0);
1250 /* End-of-loop check */
1252 arm_cbzx (code, ARMREG_IP0, 0);
1255 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1256 arm_b (code, labels [0]);
1259 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1260 /* Load vtable slot addr */
1261 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1262 /* Load vtable slot */
1263 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1264 arm_brx (code, ARMREG_IP0);
1267 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1268 /* Load fail addr */
1269 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1270 arm_brx (code, ARMREG_IP0);
1272 emit_code_bytes (acfg, buf, code - buf);
1274 common_tramp_size = code - buf;
1275 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1277 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1281 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1283 /* Load argument from second GOT slot */
1284 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1285 /* Load generic trampoline address from first GOT slot */
1286 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1287 fprintf (acfg->fp, "br x16\n");
1288 *tramp_size = 7 * 4;
1292 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1294 emit_unset_mode (acfg);
1295 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1296 fprintf (acfg->fp, "b %s\n", call_target);
1300 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1302 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1304 /* Load argument from first GOT slot */
1305 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1306 /* Load generic trampoline address from second GOT slot */
1307 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1308 fprintf (acfg->fp, "br x16\n");
1309 *tramp_size = 7 * 4;
1313 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1316 guint8 *code, *labels [16];
1318 /* Load parameter from GOT slot into ip1 */
1319 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1323 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1324 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1326 arm_bcc (code, ARMCOND_EQ, 0);
1328 /* End-of-loop check */
1330 arm_cbzx (code, ARMREG_IP0, 0);
1333 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1334 arm_b (code, labels [0]);
1337 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1338 /* Load vtable slot addr */
1339 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1340 /* Load vtable slot */
1341 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1342 arm_brx (code, ARMREG_IP0);
1345 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1346 /* Load fail addr */
1347 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1348 arm_brx (code, ARMREG_IP0);
1350 emit_code_bytes (acfg, buf, code - buf);
1352 *tramp_size = code - buf + (3 * 4);
1356 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1358 /* Similar to the specific trampolines, but the address is in the second slot */
1359 /* Load argument from first GOT slot */
1360 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1361 /* Load generic trampoline address from second GOT slot */
1362 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1363 fprintf (acfg->fp, "br x16\n");
1364 *tramp_size = 7 * 4;
1370 #ifdef MONO_ARCH_AOT_SUPPORTED
1372 * arch_emit_direct_call:
1374 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1378 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1380 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1381 /* Need to make sure this is exactly 5 bytes long */
1382 emit_unset_mode (acfg);
1383 fprintf (acfg->fp, "call %s\n", target);
1385 #elif defined(TARGET_ARM)
1386 emit_unset_mode (acfg);
1388 fprintf (acfg->fp, "blx %s\n", target);
1390 fprintf (acfg->fp, "bl %s\n", target);
1392 #elif defined(TARGET_ARM64)
1393 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1394 #elif defined(TARGET_POWERPC)
1395 emit_unset_mode (acfg);
1396 fprintf (acfg->fp, "bl %s\n", target);
1399 g_assert_not_reached ();
1406 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1408 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1409 * in in the 2. slot of every GOT, and require every method to place the GOT
1410 * address in r30, even when it doesn't access the GOT otherwise. This way,
1411 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1416 * PPC64 uses function descriptors which greatly complicate all code, since
1417 * these are used very inconsistently in the runtime. Some functions like
1418 * mono_compile_method () return ftn descriptors, while others like the
1419 * trampoline creation functions do not.
1420 * We assume that all GOT slots contain function descriptors, and create
1421 * descriptors in aot-runtime.c when needed.
1422 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1423 * from function descriptors, we could do the same, but it would require
1424 * rewriting all the ppc/aot code to handle function descriptors properly.
1425 * So instead, we use the same approach as on PPC32.
1426 * This is a horrible mess, but fixing it would probably lead to an even bigger
1432 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1435 #ifdef MONO_ARCH_AOT_SUPPORTED
1437 * arch_emit_got_offset:
1439 * The memory pointed to by CODE should hold native code for computing the GOT
1440 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1441 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1444 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1446 #if defined(TARGET_POWERPC64)
1447 emit_unset_mode (acfg);
1449 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1450 * unsupported relocations. So we store the got address into the .Lgot_addr
1451 * symbol which is in the text segment, compute its address, and load it.
1453 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1454 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1455 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1456 fprintf (acfg->fp, "add 30, 30, 0\n");
1457 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1458 acfg->label_generator ++;
1460 #elif defined(TARGET_POWERPC)
1461 emit_unset_mode (acfg);
1462 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1463 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1464 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1465 acfg->label_generator ++;
1468 guint32 offset = mono_arch_get_patch_offset (code);
1469 emit_bytes (acfg, code, offset);
1470 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1472 *code_size = offset + 4;
1477 * arch_emit_got_access:
1479 * The memory pointed to by CODE should hold native code for loading a GOT
1480 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1481 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1484 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1487 /* mov reg, got+offset(%rip) */
1489 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1493 /* Decode reg, see amd64_mov_reg_membase () */
1494 rex_r = code [0] & AMD64_REX_R;
1495 g_assert (code [0] == 0x49 + rex_r);
1496 g_assert (code [1] == 0x8b);
1497 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1499 emit_unset_mode (acfg);
1500 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1503 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1504 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1505 *code_size = mono_arch_get_patch_offset (code) + 4;
1507 #elif defined(TARGET_X86)
1508 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1509 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1510 *code_size = mono_arch_get_patch_offset (code) + 4;
1511 #elif defined(TARGET_ARM)
1512 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1513 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1514 *code_size = mono_arch_get_patch_offset (code) + 4;
1515 #elif defined(TARGET_ARM64)
1516 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1517 arm64_emit_got_access (acfg, code, got_slot, code_size);
1518 #elif defined(TARGET_POWERPC)
1522 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1524 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1525 g_assert (code - buf == 8);
1526 emit_bytes (acfg, buf, code - buf);
1527 *code_size = code - buf;
1530 g_assert_not_reached ();
1536 #ifdef MONO_ARCH_AOT_SUPPORTED
1538 * arch_emit_objc_selector_ref:
1540 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1543 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1545 #if defined(TARGET_ARM)
1546 char symbol1 [MAX_SYMBOL_SIZE];
1547 char symbol2 [MAX_SYMBOL_SIZE];
1548 int lindex = acfg->objc_selector_index_2 ++;
1550 /* Emit ldr.imm/b */
1551 emit_bytes (acfg, code, 8);
1553 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1554 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1556 emit_label (acfg, symbol1);
1557 mono_img_writer_emit_unset_mode (acfg->w);
1558 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1561 #elif defined(TARGET_ARM64)
1562 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1564 g_assert_not_reached ();
1570 * arch_emit_plt_entry:
1572 * Emit code for the PLT entry.
1573 * The plt entry should look like this:
1574 * <indirect jump to GOT_SYMBOL + OFFSET>
1575 * <INFO_OFFSET embedded into the instruction stream>
1578 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1580 #if defined(TARGET_X86)
1581 /* jmp *<offset>(%ebx) */
1582 emit_byte (acfg, 0xff);
1583 emit_byte (acfg, 0xa3);
1584 emit_int32 (acfg, offset);
1585 /* Used by mono_aot_get_plt_info_offset */
1586 emit_int32 (acfg, info_offset);
1587 #elif defined(TARGET_AMD64)
1588 emit_unset_mode (acfg);
1589 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1590 /* Used by mono_aot_get_plt_info_offset */
1591 emit_int32 (acfg, info_offset);
1592 acfg->stats.plt_size += 10;
1593 #elif defined(TARGET_ARM)
1598 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1599 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1600 emit_bytes (acfg, buf, code - buf);
1601 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1602 /* Used by mono_aot_get_plt_info_offset */
1603 emit_int32 (acfg, info_offset);
1604 #elif defined(TARGET_ARM64)
1605 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1606 #elif defined(TARGET_POWERPC)
1607 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1608 emit_unset_mode (acfg);
1609 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1610 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1611 fprintf (acfg->fp, "add 11, 11, 30\n");
1612 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1613 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1614 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1615 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1617 fprintf (acfg->fp, "mtctr 11\n");
1618 fprintf (acfg->fp, "bctr\n");
1619 emit_int32 (acfg, info_offset);
1621 g_assert_not_reached ();
1626 * arch_emit_llvm_plt_entry:
1628 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1629 * This is only needed on arm to handle thumb interop.
1632 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1634 #if defined(TARGET_ARM)
1635 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1636 /* The caller already transitioned to thumb */
1637 /* The code below should be 12 bytes long */
1638 /* clang has trouble encoding these instructions, so emit the binary */
1640 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1641 /* thumb can't encode ld pc, [pc, ip] */
1642 fprintf (acfg->fp, "add ip, pc, ip\n");
1643 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1644 fprintf (acfg->fp, "bx ip\n");
1646 emit_set_thumb_mode (acfg);
1647 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1648 fprintf (acfg->fp, ".2byte 0x44fc\n");
1649 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1650 fprintf (acfg->fp, ".2byte 0x4760\n");
1651 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1652 emit_int32 (acfg, info_offset);
1653 emit_unset_mode (acfg);
1654 emit_set_arm_mode (acfg);
1656 g_assert_not_reached ();
1660 /* Save unwind_info in the module and emit the offset to the information at symbol */
1661 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1663 guint32 uw_offset, encoded_len;
1666 emit_section_change (acfg, RODATA_SECT, 0);
1667 emit_global (acfg, symbol, FALSE);
1668 emit_label (acfg, symbol);
1670 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1671 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1673 emit_int32 (acfg, uw_offset);
1677 * arch_emit_specific_trampoline_pages:
1679 * Emits a page full of trampolines: each trampoline uses its own address to
1680 * lookup both the generic trampoline code and the data argument.
1681 * This page can be remapped in process multiple times so we can get an
1682 * unlimited number of trampolines.
1683 * Specifically this implementation uses the following trick: two memory pages
1684 * are allocated, with the first containing the data and the second containing the trampolines.
1685 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1686 * implementation does all the lifting.
1687 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1688 * on the arm 32 bit system.
1691 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1693 #if defined(TARGET_ARM)
1696 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1698 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1699 GSList *unwind_ops = NULL;
1700 #define COMMON_TRAMP_SIZE 16
1701 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1702 int imm8, rot_amount;
1705 if (!acfg->aot_opts.use_trampolines_page)
1708 acfg->tramp_page_size = pagesize;
1710 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1711 emit_alignment (acfg, pagesize);
1712 emit_global (acfg, symbol, TRUE);
1713 emit_label (acfg, symbol);
1715 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1717 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1718 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1719 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1720 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1722 g_assert (code - buf == COMMON_TRAMP_SIZE);
1725 emit_bytes (acfg, buf, code - buf);
1727 for (i = 0; i < count; ++i) {
1729 ARM_PUSH (code, 0x5fff);
1731 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1732 g_assert (code - buf == 8);
1733 emit_bytes (acfg, buf, code - buf);
1736 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1737 * the instruction pointer address, so the generic trampoline at the start of the page
1738 * subtracts 4096 to get to the data page and loads the values
1739 * We again fit the generic trampiline in 16 bytes.
1741 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1742 emit_global (acfg, symbol, TRUE);
1743 emit_label (acfg, symbol);
1745 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1746 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1747 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1748 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1750 g_assert (code - buf == COMMON_TRAMP_SIZE);
1753 emit_bytes (acfg, buf, code - buf);
1755 for (i = 0; i < count; ++i) {
1757 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1759 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1760 g_assert (code - buf == 8);
1761 emit_bytes (acfg, buf, code - buf);
1765 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1767 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1768 emit_global (acfg, symbol, TRUE);
1769 emit_label (acfg, symbol);
1771 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1772 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1773 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1774 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1775 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1776 g_assert (code - buf == COMMON_TRAMP_SIZE);
1778 emit_bytes (acfg, buf, code - buf);
1780 for (i = 0; i < count; ++i) {
1782 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1784 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1785 g_assert (code - buf == 8);
1786 emit_bytes (acfg, buf, code - buf);
1789 /* now the imt trampolines: each specific trampolines puts in the ip register
1790 * the instruction pointer address, so the generic trampoline at the start of the page
1791 * subtracts 4096 to get to the data page and loads the values
1793 #define IMT_TRAMP_SIZE 72
1794 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1795 emit_global (acfg, symbol, TRUE);
1796 emit_label (acfg, symbol);
1798 /* Need at least two free registers, plus a slot for storing the pc */
1799 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1801 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1802 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1803 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1805 /* The IMT method is in v5, r0 has the imt array address */
1808 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1809 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1810 imt_found_check = code;
1811 ARM_B_COND (code, ARMCOND_EQ, 0);
1813 /* End-of-loop check */
1814 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1815 loop_end_check = code;
1816 ARM_B_COND (code, ARMCOND_EQ, 0);
1819 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1820 loop_branch_back = code;
1822 arm_patch (loop_branch_back, loop_start);
1825 arm_patch (imt_found_check, code);
1826 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1827 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1828 /* Save it to the third stack slot */
1829 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1830 /* Restore the registers and branch */
1831 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1834 arm_patch (loop_end_check, code);
1835 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1836 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1837 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1841 g_assert (code - buf == IMT_TRAMP_SIZE);
1842 emit_bytes (acfg, buf, code - buf);
1844 for (i = 0; i < count; ++i) {
1846 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1848 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1849 g_assert (code - buf == 8);
1850 emit_bytes (acfg, buf, code - buf);
1853 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1854 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1855 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1856 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1858 /* Unwind info for specifc trampolines */
1859 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1860 /* We unwind to the original caller, from the stack, since lr is clobbered */
1861 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1862 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1863 save_unwind_info (acfg, symbol, unwind_ops);
1864 mono_free_unwind_info (unwind_ops);
1866 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1867 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1868 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1869 save_unwind_info (acfg, symbol, unwind_ops);
1870 mono_free_unwind_info (unwind_ops);
1872 /* Unwind info for rgctx trampolines */
1873 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1874 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1875 save_unwind_info (acfg, symbol, unwind_ops);
1877 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1878 save_unwind_info (acfg, symbol, unwind_ops);
1879 mono_free_unwind_info (unwind_ops);
1881 /* Unwind info for gsharedvt trampolines */
1882 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1883 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1884 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1885 save_unwind_info (acfg, symbol, unwind_ops);
1886 mono_free_unwind_info (unwind_ops);
1888 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1889 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1890 save_unwind_info (acfg, symbol, unwind_ops);
1891 mono_free_unwind_info (unwind_ops);
1893 /* Unwind info for imt trampolines */
1894 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1895 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1896 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1897 save_unwind_info (acfg, symbol, unwind_ops);
1898 mono_free_unwind_info (unwind_ops);
1900 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1901 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1902 save_unwind_info (acfg, symbol, unwind_ops);
1903 mono_free_unwind_info (unwind_ops);
1904 #elif defined(TARGET_ARM64)
1905 arm64_emit_specific_trampoline_pages (acfg);
1910 * arch_emit_specific_trampoline:
1912 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1913 * two GOT slots which contain the generic trampoline address and the trampoline
1914 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1917 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1920 * The trampolines created here are variations of the specific
1921 * trampolines created in mono_arch_create_specific_trampoline (). The
1923 * - the generic trampoline address is taken from a got slot.
1924 * - the offset of the got slot where the trampoline argument is stored
1925 * is embedded in the instruction stream, and the generic trampoline
1926 * can load the argument by loading the offset, adding it to the
1927 * address of the trampoline to get the address of the got slot, and
1928 * loading the argument from there.
1929 * - all the trampolines should be of the same length.
1931 #if defined(TARGET_AMD64)
1932 /* This should be exactly 8 bytes long */
1934 /* call *<offset>(%rip) */
1936 emit_unset_mode (acfg);
1937 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1938 emit_zero_bytes (acfg, 2);
1940 emit_byte (acfg, '\x41');
1941 emit_byte (acfg, '\xff');
1942 emit_byte (acfg, '\x15');
1943 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1944 emit_zero_bytes (acfg, 1);
1946 #elif defined(TARGET_ARM)
1950 /* This should be exactly 20 bytes long */
1953 ARM_PUSH (code, 0x5fff);
1954 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1955 /* Load the value from the GOT */
1956 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1958 ARM_BLX_REG (code, ARMREG_R1);
1960 g_assert (code - buf == 16);
1963 emit_bytes (acfg, buf, code - buf);
1965 * Only one offset is needed, since the second one would be equal to the
1968 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1969 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1970 #elif defined(TARGET_ARM64)
1971 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1972 #elif defined(TARGET_POWERPC)
1980 * PPC has no ip relative addressing, so we need to compute the address
1981 * of the mscorlib got. That is slow and complex, so instead, we store it
1982 * in the second got slot of every aot image. The caller already computed
1983 * the address of its got and placed it into r30.
1985 emit_unset_mode (acfg);
1986 /* Load mscorlib got address */
1987 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1988 /* Load generic trampoline address */
1989 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1990 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1991 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1992 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1993 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1995 fprintf (acfg->fp, "mtctr 11\n");
1996 /* Load trampoline argument */
1997 /* On ppc, we pass it normally to the generic trampoline */
1998 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1999 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2000 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
2001 /* Branch to generic trampoline */
2002 fprintf (acfg->fp, "bctr\n");
2004 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2005 *tramp_size = 10 * 4;
2007 *tramp_size = 9 * 4;
2009 #elif defined(TARGET_X86)
2013 /* Similar to the PPC code above */
2015 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2018 /* Load mscorlib got address */
2019 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2020 /* Push trampoline argument */
2021 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2022 /* Load generic trampoline address */
2023 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2024 /* Branch to generic trampoline */
2025 x86_jump_reg (code, X86_ECX);
2027 emit_bytes (acfg, buf, code - buf);
2030 g_assert (code - buf == *tramp_size);
2032 g_assert_not_reached ();
2037 * arch_emit_unbox_trampoline:
2039 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2040 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2043 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2045 #if defined(TARGET_AMD64)
2050 this_reg = mono_arch_get_this_arg_reg (NULL);
2052 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2054 emit_bytes (acfg, buf, code - buf);
2057 emit_unset_mode (acfg);
2058 fprintf (acfg->fp, "jmp %s\n", call_target);
2060 emit_byte (acfg, '\xe9');
2061 emit_symbol_diff (acfg, call_target, ".", -4);
2063 #elif defined(TARGET_X86)
2070 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2072 emit_bytes (acfg, buf, code - buf);
2075 emit_byte (acfg, '\xe9');
2076 emit_symbol_diff (acfg, call_target, ".", -4);
2077 #elif defined(TARGET_ARM)
2081 if (acfg->thumb_mixed && cfg->compile_llvm) {
2082 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2083 fprintf (acfg->fp, "b %s\n", call_target);
2084 fprintf (acfg->fp, ".arm\n");
2085 fprintf (acfg->fp, ".align 2\n");
2091 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2093 emit_bytes (acfg, buf, code - buf);
2094 /* jump to method */
2095 if (acfg->thumb_mixed && cfg->compile_llvm)
2096 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2098 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2099 #elif defined(TARGET_ARM64)
2100 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2101 #elif defined(TARGET_POWERPC)
2104 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2105 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2107 g_assert_not_reached ();
2112 * arch_emit_static_rgctx_trampoline:
2114 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2115 * two GOT slots which contain the rgctx argument, and the method to jump to.
2116 * TRAMP_SIZE is set to the size of the emitted trampoline.
2117 * These kinds of trampolines cannot be enumerated statically, since there could
2118 * be one trampoline per method instantiation, so we emit the same code for all
2119 * trampolines, and parameterize them using two GOT slots.
2122 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2124 #if defined(TARGET_AMD64)
2125 /* This should be exactly 13 bytes long */
2129 emit_unset_mode (acfg);
2130 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2131 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2133 /* mov <OFFSET>(%rip), %r10 */
2134 emit_byte (acfg, '\x4d');
2135 emit_byte (acfg, '\x8b');
2136 emit_byte (acfg, '\x15');
2137 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2139 /* jmp *<offset>(%rip) */
2140 emit_byte (acfg, '\xff');
2141 emit_byte (acfg, '\x25');
2142 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2144 #elif defined(TARGET_ARM)
2148 /* This should be exactly 24 bytes long */
2151 /* Load rgctx value */
2152 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2153 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2154 /* Load branch addr + branch */
2155 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2156 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2158 g_assert (code - buf == 16);
2161 emit_bytes (acfg, buf, code - buf);
2162 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2163 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2164 #elif defined(TARGET_ARM64)
2165 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2166 #elif defined(TARGET_POWERPC)
2174 * PPC has no ip relative addressing, so we need to compute the address
2175 * of the mscorlib got. That is slow and complex, so instead, we store it
2176 * in the second got slot of every aot image. The caller already computed
2177 * the address of its got and placed it into r30.
2179 emit_unset_mode (acfg);
2180 /* Load mscorlib got address */
2181 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2183 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2184 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2185 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2186 /* Load target address */
2187 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2188 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2189 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2190 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2191 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2192 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2194 fprintf (acfg->fp, "mtctr 11\n");
2195 /* Branch to the target address */
2196 fprintf (acfg->fp, "bctr\n");
2198 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2199 *tramp_size = 11 * 4;
2201 *tramp_size = 9 * 4;
2204 #elif defined(TARGET_X86)
2208 /* Similar to the PPC code above */
2210 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2213 /* Load mscorlib got address */
2214 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2216 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2217 /* Branch to the target address */
2218 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2220 emit_bytes (acfg, buf, code - buf);
2223 g_assert (code - buf == *tramp_size);
2225 g_assert_not_reached ();
2230 * arch_emit_imt_trampoline:
2232 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2233 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2234 * key is the IMT key, and ptr holds the address of a memory location holding
2235 * the address to branch to if the IMT arg matches the key. The array is
2236 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2238 * TRAMP_SIZE is set to the size of the emitted trampoline.
2241 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2243 #if defined(TARGET_AMD64)
2245 guint8 *labels [16];
2247 guint8 *mov_buf_ptr = mov_buf;
2249 const int kSizeOfMove = 7;
2251 code = buf = (guint8 *)g_malloc (256);
2253 /* FIXME: Optimize this, i.e. use binary search etc. */
2254 /* Maybe move the body into a separate function (slower, but much smaller) */
2256 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2259 emit_unset_mode (acfg);
2260 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2264 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2266 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2269 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2271 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2274 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2275 amd64_jump_code (code, labels [0]);
2278 mono_amd64_patch (labels [2], code);
2279 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2280 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2283 mono_amd64_patch (labels [1], code);
2284 /* Load fail tramp */
2285 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2286 /* Check if there is a fail tramp */
2287 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2289 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2290 /* Jump to fail tramp */
2291 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2294 mono_amd64_patch (labels [3], code);
2295 x86_breakpoint (code);
2298 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2299 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2300 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2301 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2302 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2303 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2305 emit_bytes (acfg, buf, code - buf);
2307 *tramp_size = code - buf + kSizeOfMove;
2311 #elif defined(TARGET_X86)
2313 guint8 *labels [16];
2315 code = buf = g_malloc (256);
2317 /* Allocate a temporary stack slot */
2318 x86_push_reg (code, X86_EAX);
2320 x86_push_reg (code, X86_EAX);
2322 /* Load mscorlib got address */
2323 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2325 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2328 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2330 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2333 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2335 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2338 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2339 x86_jump_code (code, labels [0]);
2342 mono_x86_patch (labels [2], code);
2343 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2344 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2345 /* Save the target address to the temporary stack location */
2346 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2348 x86_pop_reg (code, X86_EAX);
2349 /* Jump to the target address */
2353 mono_x86_patch (labels [1], code);
2354 /* Load fail tramp */
2355 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2356 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2358 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2359 /* Jump to fail tramp */
2360 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2361 x86_pop_reg (code, X86_EAX);
2365 mono_x86_patch (labels [3], code);
2366 x86_breakpoint (code);
2368 emit_bytes (acfg, buf, code - buf);
2370 *tramp_size = code - buf;
2374 #elif defined(TARGET_ARM)
2376 guint8 *code, *code2, *labels [16];
2380 /* The IMT method is in v5 */
2382 /* Need at least two free registers, plus a slot for storing the pc */
2383 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2385 /* Load the parameter from the GOT */
2386 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2387 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2390 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2391 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2393 ARM_B_COND (code, ARMCOND_EQ, 0);
2395 /* End-of-loop check */
2396 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2398 ARM_B_COND (code, ARMCOND_EQ, 0);
2401 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2404 arm_patch (labels [4], labels [1]);
2407 arm_patch (labels [2], code);
2408 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2409 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2410 /* Save it to the third stack slot */
2411 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2412 /* Restore the registers and branch */
2413 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2416 arm_patch (labels [3], code);
2417 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2418 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2419 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2423 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2425 emit_bytes (acfg, buf, code - buf);
2426 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2428 *tramp_size = code - buf + 4;
2429 #elif defined(TARGET_ARM64)
2430 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2431 #elif defined(TARGET_POWERPC)
2433 guint8 *code, *labels [16];
2437 /* Load the mscorlib got address */
2438 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2439 /* Load the parameter from the GOT */
2440 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2441 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2443 /* Load and check key */
2445 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2446 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2448 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2450 /* End-of-loop check */
2451 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2453 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2456 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2459 mono_ppc_patch (labels [4], labels [1]);
2462 mono_ppc_patch (labels [2], code);
2463 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2464 /* r12 now contains the value of the vtable slot */
2465 /* this is not a function descriptor on ppc64 */
2466 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2467 ppc_mtctr (code, ppc_r12);
2468 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2471 mono_ppc_patch (labels [3], code);
2475 *tramp_size = code - buf;
2477 emit_bytes (acfg, buf, code - buf);
2479 g_assert_not_reached ();
2484 #if defined (TARGET_AMD64)
2487 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2490 g_assert (acfg->fp);
2491 emit_unset_mode (acfg);
2493 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2500 * arch_emit_gsharedvt_arg_trampoline:
2502 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2503 * two GOT slots which contain the argument, and the code to jump to.
2504 * TRAMP_SIZE is set to the size of the emitted trampoline.
2505 * These kinds of trampolines cannot be enumerated statically, since there could
2506 * be one trampoline per method instantiation, so we emit the same code for all
2507 * trampolines, and parameterize them using two GOT slots.
2510 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2512 #if defined(TARGET_X86)
2516 /* Similar to the PPC code above */
2518 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2521 /* Load mscorlib got address */
2522 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2524 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2525 /* Branch to the target address */
2526 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2528 emit_bytes (acfg, buf, code - buf);
2531 g_assert (code - buf == *tramp_size);
2532 #elif defined(TARGET_ARM)
2536 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2537 /* Similar to arch_emit_specific_trampoline () */
2540 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2541 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2542 /* Load the arg value from the GOT */
2543 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2544 /* Load the addr from the GOT */
2545 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2547 ARM_BX (code, ARMREG_R1);
2549 g_assert (code - buf == 20);
2552 emit_bytes (acfg, buf, code - buf);
2553 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2554 #elif defined(TARGET_ARM64)
2555 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2556 #elif defined (TARGET_AMD64)
2558 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2559 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2560 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2561 fprintf (acfg->fp, "jmp *%%r11\n");
2565 g_assert_not_reached ();
2569 /* END OF ARCH SPECIFIC CODE */
2572 mono_get_field_token (MonoClassField *field)
2574 MonoClass *klass = field->parent;
2577 int fcount = mono_class_get_field_count (klass);
2578 for (i = 0; i < fcount; ++i) {
2579 if (field == &klass->fields [i])
2580 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2583 g_assert_not_reached ();
2588 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2592 //printf ("ENCODE: %d 0x%x.\n", value, value);
2595 * Same encoding as the one used in the metadata, extended to handle values
2596 * greater than 0x1fffffff.
2598 if ((value >= 0) && (value <= 127))
2600 else if ((value >= 0) && (value <= 16383)) {
2601 p [0] = 0x80 | (value >> 8);
2602 p [1] = value & 0xff;
2604 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2605 p [0] = (value >> 24) | 0xc0;
2606 p [1] = (value >> 16) & 0xff;
2607 p [2] = (value >> 8) & 0xff;
2608 p [3] = value & 0xff;
2613 p [1] = (value >> 24) & 0xff;
2614 p [2] = (value >> 16) & 0xff;
2615 p [3] = (value >> 8) & 0xff;
2616 p [4] = value & 0xff;
2624 stream_init (MonoDynamicStream *sh)
2627 sh->alloc_size = 4096;
2628 sh->data = (char *)g_malloc (4096);
2630 /* So offsets are > 0 */
2636 make_room_in_stream (MonoDynamicStream *stream, int size)
2638 if (size <= stream->alloc_size)
2641 while (stream->alloc_size <= size) {
2642 if (stream->alloc_size < 4096)
2643 stream->alloc_size = 4096;
2645 stream->alloc_size *= 2;
2648 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2652 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2656 make_room_in_stream (stream, stream->index + len);
2657 memcpy (stream->data + stream->index, data, len);
2658 idx = stream->index;
2659 stream->index += len;
2666 * Add data to the binary blob inside the aot image. Returns the offset inside the
2667 * blob where the data was stored.
2670 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2672 g_assert (!acfg->blob_closed);
2674 if (acfg->blob.alloc_size == 0)
2675 stream_init (&acfg->blob);
2677 return add_stream_data (&acfg->blob, (char*)data, data_len);
2681 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2686 if (acfg->blob.alloc_size == 0)
2687 stream_init (&acfg->blob);
2689 count = acfg->blob.index % align;
2691 /* we assume the stream data will be aligned */
2693 add_stream_data (&acfg->blob, buf, 4 - count);
2695 return add_stream_data (&acfg->blob, (char*)data, data_len);
2698 /* Emit a table of data into the aot image */
2700 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2702 if (acfg->data_outfile) {
2703 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2704 fwrite (data,1, size, acfg->data_outfile);
2705 acfg->datafile_offset += size;
2706 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2707 int align = 8 - size % 8;
2708 acfg->datafile_offset += align;
2709 guint8 align_buf [16];
2710 memset (&align_buf, 0, sizeof (align_buf));
2711 fwrite (align_buf, align, 1, acfg->data_outfile);
2712 } else if (acfg->llvm) {
2713 mono_llvm_emit_aot_data (symbol, data, size);
2715 emit_section_change (acfg, RODATA_SECT, 0);
2716 emit_alignment (acfg, 8);
2717 emit_label (acfg, symbol);
2718 emit_bytes (acfg, data, size);
2723 * emit_offset_table:
2725 * Emit a table of increasing offsets in a compact form using differential encoding.
2726 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2727 * group size, the more compact the table becomes, but the slower it becomes to compute
2728 * a given entry. Returns the size of the table.
2731 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2733 gint32 current_offset;
2734 int i, buf_size, ngroups, index_entry_size;
2736 guint8 *data_p, *data_buf;
2737 guint32 *index_offsets;
2739 ngroups = (noffsets + (group_size - 1)) / group_size;
2741 index_offsets = g_new0 (guint32, ngroups);
2743 buf_size = noffsets * 4;
2744 p = buf = (guint8 *)g_malloc0 (buf_size);
2747 for (i = 0; i < noffsets; ++i) {
2748 //printf ("D: %d -> %d\n", i, offsets [i]);
2749 if ((i % group_size) == 0) {
2750 index_offsets [i / group_size] = p - buf;
2751 /* Emit the full value for these entries */
2752 encode_value (offsets [i], p, &p);
2754 /* The offsets are allowed to be non-increasing */
2755 //g_assert (offsets [i] >= current_offset);
2756 encode_value (offsets [i] - current_offset, p, &p);
2758 current_offset = offsets [i];
2763 if (ngroups && index_offsets [ngroups - 1] < 65000)
2764 index_entry_size = 2;
2766 index_entry_size = 4;
2768 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2769 p = buf = (guint8 *)g_malloc0 (buf_size);
2771 /* Emit the header */
2772 encode_int (noffsets, p, &p);
2773 encode_int (group_size, p, &p);
2774 encode_int (ngroups, p, &p);
2775 encode_int (index_entry_size, p, &p);
2777 /* Emit the index */
2778 for (i = 0; i < ngroups; ++i) {
2779 if (index_entry_size == 2)
2780 encode_int16 (index_offsets [i], p, &p);
2782 encode_int (index_offsets [i], p, &p);
2785 memcpy (p, data_buf, data_p - data_buf);
2786 p += data_p - data_buf;
2788 g_assert (p - buf <= buf_size);
2790 emit_aot_data (acfg, table, symbol, buf, p - buf);
2795 return (int)(p - buf);
2799 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2803 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2807 index = g_hash_table_size (cfg->image_hash);
2808 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2809 g_ptr_array_add (cfg->image_table, image);
2815 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2818 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2820 /* FIXME: Search referenced images as well */
2821 if (!acfg->typespec_classes) {
2822 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2823 for (i = 0; i < len; i++) {
2825 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2826 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2827 if (!is_ok (&error)) {
2828 mono_error_cleanup (&error);
2831 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2834 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2838 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2841 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2844 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2847 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2850 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2855 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2859 if (mono_class_is_ginst (klass)) {
2861 g_assert (klass->type_token);
2863 /* Find a typespec for a class if possible */
2864 token = find_typespec_for_class (acfg, klass);
2866 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2867 encode_value (token, p, &p);
2869 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2870 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2871 static int count = 0;
2874 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2875 encode_klass_ref (acfg, gclass, p, &p);
2876 encode_ginst (acfg, inst, p, &p);
2880 } else if (klass->type_token) {
2881 int iindex = get_image_index (acfg, klass->image);
2883 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2885 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2886 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2888 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2889 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2890 encode_value (get_image_index (acfg, klass->image), p, &p);
2892 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2893 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2894 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2896 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2898 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2899 if (par->gshared_constraint) {
2900 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2901 encode_type (acfg, par->gshared_constraint, p, &p);
2902 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2904 encode_value (klass->byval_arg.type, p, &p);
2905 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2907 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2909 if (!container->is_anonymous) {
2910 encode_value (container->is_method, p, &p);
2911 if (container->is_method)
2912 encode_method_ref (acfg, container->owner.method, p, &p);
2914 encode_klass_ref (acfg, container->owner.klass, p, &p);
2917 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2918 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2919 encode_type (acfg, &klass->byval_arg, p, &p);
2922 g_assert (klass->rank > 0);
2923 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2924 encode_value (klass->rank, p, &p);
2925 encode_klass_ref (acfg, klass->element_class, p, &p);
2933 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2934 * standard metadata encoding.
2937 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2939 gboolean shared = FALSE;
2942 * The encoding of generic instances is large so emit them only once.
2944 if (mono_class_is_ginst (klass)) {
2946 g_assert (klass->type_token);
2948 /* Find a typespec for a class if possible */
2949 token = find_typespec_for_class (acfg, klass);
2952 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2957 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2961 buf2 = (guint8 *)g_malloc (1024);
2964 encode_klass_ref_inner (acfg, klass, p, &p);
2965 g_assert (p - buf2 < 1024);
2967 offset = add_to_blob (acfg, buf2, p - buf2);
2970 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2976 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2977 encode_value (offset, p, &p);
2982 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2986 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2988 guint32 token = mono_get_field_token (field);
2991 encode_klass_ref (cfg, field->parent, p, &p);
2992 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2993 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2998 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
3003 encode_value (inst->type_argc, p, &p);
3004 for (i = 0; i < inst->type_argc; ++i)
3005 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3010 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3013 MonoGenericInst *inst;
3015 inst = context->class_inst;
3017 g_assert (inst->type_argc);
3018 encode_ginst (acfg, inst, p, &p);
3020 encode_value (0, p, &p);
3022 inst = context->method_inst;
3024 g_assert (inst->type_argc);
3025 encode_ginst (acfg, inst, p, &p);
3027 encode_value (0, p, &p);
3033 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3037 g_assert (t->num_mods == 0);
3038 /* t->attrs can be ignored */
3039 //g_assert (t->attrs == 0);
3042 *p = MONO_TYPE_PINNED;
3046 *p = MONO_TYPE_BYREF;
3054 case MONO_TYPE_VOID:
3055 case MONO_TYPE_BOOLEAN:
3056 case MONO_TYPE_CHAR:
3069 case MONO_TYPE_STRING:
3070 case MONO_TYPE_OBJECT:
3071 case MONO_TYPE_TYPEDBYREF:
3073 case MONO_TYPE_VALUETYPE:
3074 case MONO_TYPE_CLASS:
3075 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3077 case MONO_TYPE_SZARRAY:
3078 encode_klass_ref (acfg, t->data.klass, p, &p);
3081 encode_type (acfg, t->data.type, p, &p);
3083 case MONO_TYPE_GENERICINST: {
3084 MonoClass *gclass = t->data.generic_class->container_class;
3085 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3087 encode_klass_ref (acfg, gclass, p, &p);
3088 encode_ginst (acfg, inst, p, &p);
3091 case MONO_TYPE_ARRAY: {
3092 MonoArrayType *array = t->data.array;
3095 encode_klass_ref (acfg, array->eklass, p, &p);
3096 encode_value (array->rank, p, &p);
3097 encode_value (array->numsizes, p, &p);
3098 for (i = 0; i < array->numsizes; ++i)
3099 encode_value (array->sizes [i], p, &p);
3100 encode_value (array->numlobounds, p, &p);
3101 for (i = 0; i < array->numlobounds; ++i)
3102 encode_value (array->lobounds [i], p, &p);
3106 case MONO_TYPE_MVAR:
3107 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3110 g_assert_not_reached ();
3117 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3123 /* Similar to the metadata encoding */
3124 if (sig->generic_param_count)
3128 if (sig->explicit_this)
3130 flags |= (sig->call_convention & 0x0F);
3134 if (sig->generic_param_count)
3135 encode_value (sig->generic_param_count, p, &p);
3136 encode_value (sig->param_count, p, &p);
3138 encode_type (acfg, sig->ret, p, &p);
3139 for (i = 0; i < sig->param_count; ++i) {
3140 if (sig->sentinelpos == i) {
3141 *p = MONO_TYPE_SENTINEL;
3144 encode_type (acfg, sig->params [i], p, &p);
3150 #define MAX_IMAGE_INDEX 250
3153 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3155 guint32 image_index = get_image_index (acfg, method->klass->image);
3156 guint32 token = method->token;
3157 MonoJumpInfoToken *ji;
3161 * The encoding for most methods is as follows:
3162 * - image index encoded as a leb128
3163 * - token index encoded as a leb128
3164 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3165 * types of method encodings.
3168 /* Mark methods which can't use aot trampolines because they need the further
3169 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3171 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3172 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3173 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3175 if (method->wrapper_type) {
3176 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3178 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3180 encode_value (method->wrapper_type, p, &p);
3182 switch (method->wrapper_type) {
3183 case MONO_WRAPPER_REMOTING_INVOKE:
3184 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3185 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3188 m = mono_marshal_method_from_wrapper (method);
3190 encode_method_ref (acfg, m, p, &p);
3193 case MONO_WRAPPER_PROXY_ISINST:
3194 case MONO_WRAPPER_LDFLD:
3195 case MONO_WRAPPER_LDFLDA:
3196 case MONO_WRAPPER_STFLD: {
3198 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3201 case MONO_WRAPPER_ALLOC: {
3202 /* The GC name is saved once in MonoAotFileInfo */
3203 g_assert (info->d.alloc.alloc_type != -1);
3204 encode_value (info->d.alloc.alloc_type, p, &p);
3207 case MONO_WRAPPER_WRITE_BARRIER: {
3211 case MONO_WRAPPER_STELEMREF: {
3213 encode_value (info->subtype, p, &p);
3214 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3215 encode_value (info->d.virtual_stelemref.kind, p, &p);
3218 case MONO_WRAPPER_UNKNOWN: {
3220 encode_value (info->subtype, p, &p);
3221 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3222 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3223 encode_klass_ref (acfg, method->klass, p, &p);
3224 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3225 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3226 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3227 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3228 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3229 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3230 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3231 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3234 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3236 encode_value (info->subtype, p, &p);
3237 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3238 strcpy ((char*)p, method->name);
3239 p += strlen (method->name) + 1;
3240 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3241 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3243 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3244 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3248 case MONO_WRAPPER_SYNCHRONIZED: {
3251 m = mono_marshal_method_from_wrapper (method);
3253 g_assert (m != method);
3254 encode_method_ref (acfg, m, p, &p);
3257 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3259 encode_value (info->subtype, p, &p);
3261 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3262 encode_value (info->d.element_addr.rank, p, &p);
3263 encode_value (info->d.element_addr.elem_size, p, &p);
3264 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3265 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3267 g_assert_not_reached ();
3271 case MONO_WRAPPER_CASTCLASS: {
3273 encode_value (info->subtype, p, &p);
3276 case MONO_WRAPPER_RUNTIME_INVOKE: {
3278 encode_value (info->subtype, p, &p);
3279 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3280 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3281 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3282 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3285 case MONO_WRAPPER_DELEGATE_INVOKE:
3286 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3287 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3288 if (method->is_inflated) {
3289 /* These wrappers are identified by their class */
3290 encode_value (1, p, &p);
3291 encode_klass_ref (acfg, method->klass, p, &p);
3293 MonoMethodSignature *sig = mono_method_signature (method);
3294 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3296 encode_value (0, p, &p);
3297 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3298 encode_value (info ? info->subtype : 0, p, &p);
3299 encode_signature (acfg, sig, p, &p);
3303 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3305 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3306 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3310 g_assert_not_reached ();
3312 } else if (mono_method_signature (method)->is_inflated) {
3314 * This is a generic method, find the original token which referenced it and
3316 * Obtain the token from information recorded by the JIT.
3318 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3320 image_index = get_image_index (acfg, ji->image);
3321 g_assert (image_index < MAX_IMAGE_INDEX);
3324 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3325 encode_value (image_index, p, &p);
3326 encode_value (token, p, &p);
3328 MonoMethod *declaring;
3329 MonoGenericContext *context = mono_method_get_context (method);
3331 g_assert (method->is_inflated);
3332 declaring = ((MonoMethodInflated*)method)->declaring;
3335 * This might be a non-generic method of a generic instance, which
3336 * doesn't have a token since the reference is generated by the JIT
3337 * like Nullable:Box/Unbox, or by generic sharing.
3339 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3340 /* Encode the klass */
3341 encode_klass_ref (acfg, method->klass, p, &p);
3342 /* Encode the method */
3343 image_index = get_image_index (acfg, method->klass->image);
3344 g_assert (image_index < MAX_IMAGE_INDEX);
3345 g_assert (declaring->token);
3346 token = declaring->token;
3347 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3348 encode_value (image_index, p, &p);
3349 encode_value (token, p, &p);
3350 encode_generic_context (acfg, context, p, &p);
3352 } else if (token == 0) {
3353 /* This might be a method of a constructed type like int[,].Set */
3354 /* Obtain the token from information recorded by the JIT */
3355 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3357 image_index = get_image_index (acfg, ji->image);
3358 g_assert (image_index < MAX_IMAGE_INDEX);
3361 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3362 encode_value (image_index, p, &p);
3363 encode_value (token, p, &p);
3366 g_assert (method->klass->rank);
3368 /* Encode directly */
3369 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3370 encode_klass_ref (acfg, method->klass, p, &p);
3371 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3372 encode_value (0, p, &p);
3373 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3374 encode_value (1, p, &p);
3375 else if (!strcmp (method->name, "Get"))
3376 encode_value (2, p, &p);
3377 else if (!strcmp (method->name, "Address"))
3378 encode_value (3, p, &p);
3379 else if (!strcmp (method->name, "Set"))
3380 encode_value (4, p, &p);
3382 g_assert_not_reached ();
3385 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3387 if (image_index >= MONO_AOT_METHODREF_MIN) {
3388 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3389 encode_value (image_index, p, &p);
3390 encode_value (mono_metadata_token_index (token), p, &p);
3392 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3399 compare_patches (gconstpointer a, gconstpointer b)
3403 i = (*(MonoJumpInfo**)a)->ip.i;
3404 j = (*(MonoJumpInfo**)b)->ip.i;
3415 static G_GNUC_UNUSED char*
3416 patch_to_string (MonoJumpInfo *patch_info)
3420 str = g_string_new ("");
3422 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3424 switch (patch_info->type) {
3425 case MONO_PATCH_INFO_VTABLE:
3426 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3431 g_string_append_printf (str, ")");
3432 return g_string_free (str, FALSE);
3438 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3441 static inline gboolean
3442 is_plt_patch (MonoJumpInfo *patch_info)
3444 switch (patch_info->type) {
3445 case MONO_PATCH_INFO_METHOD:
3446 case MONO_PATCH_INFO_INTERNAL_METHOD:
3447 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3448 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3449 case MONO_PATCH_INFO_RGCTX_FETCH:
3459 * Return the symbol identifying the plt entry PLT_OFFSET.
3462 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3466 * The Apple linker reorganizes object files, so it doesn't like branches to local
3467 * labels, since those have no relocations.
3469 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3471 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3478 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3480 static MonoPltEntry*
3481 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3484 gboolean synchronized = FALSE;
3485 static int synchronized_symbol_idx;
3487 if (!is_plt_patch (patch_info))
3490 if (!acfg->patch_to_plt_entry [patch_info->type])
3491 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3492 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3494 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3496 * Allocate a separate PLT slot for each such patch, since some plt
3497 * entries will refer to the method itself, and some will refer to the
3501 synchronized = TRUE;
3505 MonoJumpInfo *new_ji;
3507 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3509 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3510 res->plt_offset = acfg->plt_offset;
3512 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3513 if (acfg->aot_opts.write_symbols)
3514 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3516 /* Avoid duplicate symbols because we don't cache */
3517 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3519 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3520 synchronized_symbol_idx ++;
3523 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3525 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3527 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3529 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3531 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3532 //mono_print_ji (patch_info); printf ("\n");
3533 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3535 acfg->plt_offset ++;
3544 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3545 * JI could be found if it exists, otherwise allocates a new one.
3548 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3551 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3553 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3555 return got_offset - 1;
3558 got_offset = acfg->llvm_got_offset;
3559 acfg->llvm_got_offset ++;
3561 got_offset = acfg->got_offset;
3562 acfg->got_offset ++;
3565 acfg->stats.got_slots ++;
3566 acfg->stats.got_slot_types [ji->type] ++;
3568 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3569 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3570 g_ptr_array_add (info->got_patches, ji);
3575 /* Add a method to the list of methods which need to be emitted */
3577 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3580 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3581 g_ptr_array_add (acfg->methods, method);
3582 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3583 acfg->nmethods = acfg->methods->len + 1;
3586 if (method->wrapper_type || extra)
3587 g_ptr_array_add (acfg->extra_methods, method);
3591 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3593 /* One instantiation with valuetypes is generated for each async method */
3594 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3601 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3603 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3611 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3615 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3619 index = acfg->method_index;
3620 add_method_with_index (acfg, method, index, extra);
3622 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3624 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3626 acfg->method_index ++;
3632 add_method (MonoAotCompile *acfg, MonoMethod *method)
3634 return add_method_full (acfg, method, FALSE, 0);
3638 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3640 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3641 method = mini_get_shared_method (method);
3642 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3643 /* Use the gsharedvt version */
3644 method = mini_get_shared_method_full (method, TRUE, TRUE);
3646 if (acfg->aot_opts.log_generics)
3647 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3649 add_method_full (acfg, method, TRUE, depth);
3653 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3655 add_extra_method_with_depth (acfg, method, 0);
3659 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3661 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3662 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3663 MonoMethod *wrapper;
3669 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3670 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3673 add_method (acfg, wrapper);
3677 get_runtime_invoke_sig (MonoMethodSignature *sig)
3679 MonoMethodBuilder *mb;
3682 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3683 m = mono_mb_create_method (mb, sig, 16);
3684 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3690 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3692 return mono_marshal_get_runtime_invoke (method, virtual_);
3696 can_marshal_struct (MonoClass *klass)
3698 MonoClassField *field;
3699 gboolean can_marshal = TRUE;
3700 gpointer iter = NULL;
3701 MonoMarshalType *info;
3704 if (mono_class_is_auto_layout (klass))
3707 info = mono_marshal_load_type_info (klass);
3709 /* Only allow a few field types to avoid asserts in the marshalling code */
3710 while ((field = mono_class_get_fields (klass, &iter))) {
3711 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3714 switch (field->type->type) {
3719 case MONO_TYPE_BOOLEAN:
3722 case MONO_TYPE_CHAR:
3730 case MONO_TYPE_STRING:
3732 case MONO_TYPE_VALUETYPE:
3733 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3734 can_marshal = FALSE;
3736 case MONO_TYPE_SZARRAY: {
3737 gboolean has_mspec = FALSE;
3740 for (i = 0; i < info->num_fields; ++i) {
3741 if (info->fields [i].field == field && info->fields [i].mspec)
3746 can_marshal = FALSE;
3750 can_marshal = FALSE;
3756 /* Its hard to compute whenever these can be marshalled or not */
3757 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3764 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3766 /* Create a vtype instantiation */
3767 MonoGenericContext shared_context;
3769 MonoGenericInst *inst;
3770 MonoGenericContainer *container;
3771 MonoClass **constraints;
3774 memset (ctx, 0, sizeof (MonoGenericContext));
3776 if (mono_class_is_gtd (method->klass)) {
3777 shared_context = mono_class_get_generic_container (method->klass)->context;
3778 inst = shared_context.class_inst;
3780 args = g_new0 (MonoType*, inst->type_argc);
3781 for (i = 0; i < inst->type_argc; ++i) {
3782 args [i] = &mono_defaults.int_class->byval_arg;
3784 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3786 if (method->is_generic) {
3787 container = mono_method_get_generic_container (method);
3788 shared_context = container->context;
3789 inst = shared_context.method_inst;
3791 args = g_new0 (MonoType*, inst->type_argc);
3792 for (i = 0; i < container->type_argc; ++i) {
3793 MonoGenericParamInfo *info = &container->type_params [i].info;
3794 gboolean ref_only = FALSE;
3796 if (info && info->constraints) {
3797 constraints = info->constraints;
3799 while (*constraints) {
3800 MonoClass *cklass = *constraints;
3801 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3802 /* Inflaring the method with our vtype would not be valid */
3809 args [i] = &mono_defaults.object_class->byval_arg;
3811 args [i] = &mono_defaults.int_class->byval_arg;
3813 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3818 add_wrappers (MonoAotCompile *acfg)
3820 MonoMethod *method, *m;
3822 MonoMethodSignature *sig, *csig;
3826 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3827 * so there is only one wrapper of a given type, or inlining their contents into their
3830 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3833 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3834 gboolean skip = FALSE;
3836 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3837 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3839 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3840 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3841 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3844 /* Skip methods which can not be handled by get_runtime_invoke () */
3845 sig = mono_method_signature (method);
3848 if ((sig->ret->type == MONO_TYPE_PTR) ||
3849 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3851 if (mono_class_is_open_constructed_type (sig->ret))
3854 for (j = 0; j < sig->param_count; j++) {
3855 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3857 if (mono_class_is_open_constructed_type (sig->params [j]))
3861 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3862 if (!mono_class_is_contextbound (method->klass)) {
3863 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3864 gboolean has_nullable = FALSE;
3866 for (j = 0; j < sig->param_count; j++) {
3867 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3868 has_nullable = TRUE;
3871 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3872 /* Supported by the dynamic runtime-invoke wrapper */
3876 mono_arch_dyn_call_free (info);
3880 if (acfg->aot_opts.llvm_only)
3881 /* Supported by the gsharedvt based runtime-invoke wrapper */
3885 //printf ("%s\n", mono_method_full_name (method, TRUE));
3886 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3890 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3893 /* Runtime invoke wrappers */
3895 /* void runtime-invoke () [.cctor] */
3896 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3897 csig->ret = &mono_defaults.void_class->byval_arg;
3898 add_method (acfg, get_runtime_invoke_sig (csig));
3900 /* void runtime-invoke () [Finalize] */
3901 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3903 csig->ret = &mono_defaults.void_class->byval_arg;
3904 add_method (acfg, get_runtime_invoke_sig (csig));
3906 /* void runtime-invoke (string) [exception ctor] */
3907 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3909 csig->ret = &mono_defaults.void_class->byval_arg;
3910 csig->params [0] = &mono_defaults.string_class->byval_arg;
3911 add_method (acfg, get_runtime_invoke_sig (csig));
3913 /* void runtime-invoke (string, string) [exception ctor] */
3914 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3916 csig->ret = &mono_defaults.void_class->byval_arg;
3917 csig->params [0] = &mono_defaults.string_class->byval_arg;
3918 csig->params [1] = &mono_defaults.string_class->byval_arg;
3919 add_method (acfg, get_runtime_invoke_sig (csig));
3921 /* string runtime-invoke () [Exception.ToString ()] */
3922 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3924 csig->ret = &mono_defaults.string_class->byval_arg;
3925 add_method (acfg, get_runtime_invoke_sig (csig));
3927 /* void runtime-invoke (string, Exception) [exception ctor] */
3928 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3930 csig->ret = &mono_defaults.void_class->byval_arg;
3931 csig->params [0] = &mono_defaults.string_class->byval_arg;
3932 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3933 add_method (acfg, get_runtime_invoke_sig (csig));
3935 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3936 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3938 csig->ret = &(mono_class_load_from_name (
3939 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3940 csig->params [0] = &mono_defaults.string_class->byval_arg;
3941 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3942 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3943 add_method (acfg, get_runtime_invoke_sig (csig));
3945 /* runtime-invoke used by finalizers */
3946 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3948 /* This is used by mono_runtime_capture_context () */
3949 method = mono_get_context_capture_method ();
3951 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3953 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3954 if (!acfg->aot_opts.llvm_only)
3955 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3958 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3959 if (acfg->aot_opts.llvm_only) {
3962 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3963 for (variants = 0; variants < 4; ++variants) {
3964 for (i = 0; i < 16; ++i) {
3965 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3966 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3974 add_method (acfg, mono_marshal_get_stelemref ());
3976 /* Managed Allocators */
3977 nallocators = mono_gc_get_managed_allocator_types ();
3978 for (i = 0; i < nallocators; ++i) {
3979 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3980 add_method (acfg, m);
3981 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3982 add_method (acfg, m);
3985 /* write barriers */
3986 if (mono_gc_is_moving ()) {
3987 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3988 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3991 /* Stelemref wrappers */
3993 MonoMethod **wrappers;
3996 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3997 for (i = 0; i < nwrappers; ++i)
3998 add_method (acfg, wrappers [i]);
4002 /* castclass_with_check wrapper */
4003 add_method (acfg, mono_marshal_get_castclass_with_cache ());
4004 /* isinst_with_check wrapper */
4005 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4007 /* JIT icall wrappers */
4008 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4009 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4013 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4014 * we use the original method instead at runtime.
4015 * Since full-aot doesn't support remoting, this is not a problem.
4018 /* remoting-invoke wrappers */
4019 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4021 MonoMethodSignature *sig;
4023 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4024 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4025 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4027 sig = mono_method_signature (method);
4029 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4030 m = mono_marshal_get_remoting_invoke_with_check (method);
4032 add_method (acfg, m);
4037 /* delegate-invoke wrappers */
4038 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4041 MonoCustomAttrInfo *cattr;
4043 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4044 klass = mono_class_get_checked (acfg->image, token, &error);
4047 mono_error_cleanup (&error);
4051 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4054 if (!mono_class_is_gtd (klass)) {
4055 method = mono_get_delegate_invoke (klass);
4057 m = mono_marshal_get_delegate_invoke (method, NULL);
4059 add_method (acfg, m);
4061 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4063 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4065 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4067 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4069 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4070 if (!is_ok (&error)) {
4071 mono_error_cleanup (&error);
4078 for (j = 0; j < cattr->num_attrs; ++j)
4079 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4081 if (j < cattr->num_attrs) {
4083 MonoMethod *wrapper;
4084 MonoMethod *del_invoke;
4086 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4087 invoke = mono_get_delegate_invoke (klass);
4088 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4089 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4090 add_method (acfg, wrapper);
4091 add_method (acfg, del_invoke);
4094 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4096 MonoGenericContext ctx;
4097 MonoMethod *inst, *gshared;
4100 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4103 method = mono_get_delegate_invoke (klass);
4104 create_gsharedvt_inst (acfg, method, &ctx);
4106 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4107 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4109 m = mono_marshal_get_delegate_invoke (inst, NULL);
4110 g_assert (m->is_inflated);
4112 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4113 add_extra_method (acfg, gshared);
4116 method = mono_get_delegate_begin_invoke (klass);
4118 create_gsharedvt_inst (acfg, method, &ctx);
4120 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4121 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4123 m = mono_marshal_get_delegate_begin_invoke (inst);
4124 g_assert (m->is_inflated);
4126 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4127 add_extra_method (acfg, gshared);
4131 method = mono_get_delegate_end_invoke (klass);
4133 create_gsharedvt_inst (acfg, method, &ctx);
4135 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4136 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4138 m = mono_marshal_get_delegate_end_invoke (inst);
4139 g_assert (m->is_inflated);
4141 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4142 add_extra_method (acfg, gshared);
4147 /* array access wrappers */
4148 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4152 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4153 klass = mono_class_get_checked (acfg->image, token, &error);
4156 mono_error_cleanup (&error);
4160 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4161 MonoMethod *m, *wrapper;
4163 /* Add runtime-invoke wrappers too */
4165 m = mono_class_get_method_from_name (klass, "Get", -1);
4167 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4168 add_extra_method (acfg, wrapper);
4169 if (!acfg->aot_opts.llvm_only)
4170 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4172 m = mono_class_get_method_from_name (klass, "Set", -1);
4174 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4175 add_extra_method (acfg, wrapper);
4176 if (!acfg->aot_opts.llvm_only)
4177 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4181 /* Synchronized wrappers */
4182 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4184 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4185 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4186 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4188 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4189 if (method->is_generic) {
4191 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4193 MonoGenericContext ctx;
4194 MonoMethod *inst, *gshared, *m;
4197 * Create a generic wrapper for a generic instance, and AOT that.
4199 create_gsharedvt_inst (acfg, method, &ctx);
4200 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4201 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4202 m = mono_marshal_get_synchronized_wrapper (inst);
4203 g_assert (m->is_inflated);
4204 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4205 add_method (acfg, gshared);
4207 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4212 /* pinvoke wrappers */
4213 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4216 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4218 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4219 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4221 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4222 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4223 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4226 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4227 if (acfg->aot_opts.llvm_only) {
4228 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4229 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4234 /* native-to-managed wrappers */
4235 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4238 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4239 MonoCustomAttrInfo *cattr;
4242 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4243 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4246 * Only generate native-to-managed wrappers for methods which have an
4247 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4248 * name to avoid defining a new assembly to contain it.
4250 cattr = mono_custom_attrs_from_method_checked (method, &error);
4251 if (!is_ok (&error)) {
4252 char *name = mono_method_get_full_name (method);
4253 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4258 for (j = 0; j < cattr->num_attrs; ++j)
4259 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4261 if (j < cattr->num_attrs) {
4262 MonoCustomAttrEntry *e = &cattr->attrs [j];
4263 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4264 const char *p = (const char*)e->data;
4266 int slen, num_named, named_type;
4270 char *export_name = NULL;
4271 MonoMethod *wrapper;
4273 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4274 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4275 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4276 mono_method_full_name (method, TRUE));
4280 g_assert (sig->param_count == 1);
4281 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4284 * Decode the cattr manually since we can't create objects
4285 * during aot compilation.
4291 /* From load_cattr_value () in reflection.c */
4292 slen = mono_metadata_decode_value (p, &p);
4293 n = (char *)g_memdup (p, slen + 1);
4295 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4297 mono_error_assert_ok (&error);
4300 klass = mono_class_from_mono_type (t);
4301 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4305 num_named = read16 (p);
4308 g_assert (num_named < 2);
4309 if (num_named == 1) {
4313 /* parse ExportSymbol attribute */
4315 named_type = *named;
4317 /* data_type = *named; */
4320 name_len = mono_metadata_decode_blob_size (named, &named);
4321 name = (char *)g_malloc (name_len + 1);
4322 memcpy (name, named, name_len);
4323 name [name_len] = 0;
4326 g_assert (named_type == 0x54);
4327 g_assert (!strcmp (name, "ExportSymbol"));
4329 /* load_cattr_value (), string case */
4330 g_assert (*named != (char)0xff);
4331 slen = mono_metadata_decode_value (named, &named);
4332 export_name = (char *)g_malloc (slen + 1);
4333 memcpy (export_name, named, slen);
4334 export_name [slen] = 0;
4338 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, &error);
4339 mono_error_assert_ok (&error);
4341 add_method (acfg, wrapper);
4343 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4348 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4349 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4350 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4354 /* StructureToPtr/PtrToStructure wrappers */
4355 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4359 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4360 klass = mono_class_get_checked (acfg->image, token, &error);
4363 mono_error_cleanup (&error);
4367 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4368 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4369 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4370 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4376 has_type_vars (MonoClass *klass)
4378 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4381 return has_type_vars (klass->element_class);
4382 if (mono_class_is_ginst (klass)) {
4383 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4384 if (context->class_inst) {
4387 for (i = 0; i < context->class_inst->type_argc; ++i)
4388 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4392 if (mono_class_is_gtd (klass))
4398 is_vt_inst (MonoGenericInst *inst)
4402 for (i = 0; i < inst->type_argc; ++i) {
4403 MonoType *t = inst->type_argv [i];
4404 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4411 method_has_type_vars (MonoMethod *method)
4413 if (has_type_vars (method->klass))
4416 if (method->is_inflated) {
4417 MonoGenericContext *context = mono_method_get_context (method);
4418 if (context->method_inst) {
4421 for (i = 0; i < context->method_inst->type_argc; ++i)
4422 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4430 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4432 return opts->mode == MONO_AOT_MODE_FULL;
4436 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4438 return opts->mode == MONO_AOT_MODE_HYBRID;
4441 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4444 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4446 /* This might lead to a huge code blowup so only do it if neccesary */
4447 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4450 add_generic_class_with_depth (acfg, klass, 0, ref);
4454 check_type_depth (MonoType *t, int depth)
4462 case MONO_TYPE_GENERICINST: {
4463 MonoGenericClass *gklass = t->data.generic_class;
4464 MonoGenericInst *ginst = gklass->context.class_inst;
4467 for (i = 0; i < ginst->type_argc; ++i) {
4468 if (check_type_depth (ginst->type_argv [i], depth + 1))
4482 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4485 * add_generic_class:
4487 * Add all methods of a generic class.
4490 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4493 MonoClassField *field;
4495 gboolean use_gsharedvt = FALSE;
4497 if (!acfg->ginst_hash)
4498 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4500 mono_class_init (klass);
4502 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4505 if (has_type_vars (klass))
4508 if (!mono_class_is_ginst (klass) && !klass->rank)
4511 if (mono_class_has_failure (klass))
4514 if (!acfg->ginst_hash)
4515 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4517 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4520 if (check_type_depth (&klass->byval_arg, 0))
4523 if (acfg->aot_opts.log_generics)
4524 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4526 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4529 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4530 * Enable this only for some classes since gsharedvt might not support all methods.
4532 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) &&
4533 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4534 use_gsharedvt = TRUE;
4537 while ((method = mono_class_get_methods (klass, &iter))) {
4538 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4540 * This is partial sharing, and we can't handle it yet
4545 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4547 add_types_from_method_header (acfg, method);
4551 if (method->is_generic)
4556 * FIXME: Instances which are referenced by these methods are not added,
4557 * for example Array.Resize<int> for List<int>.Add ().
4559 add_extra_method_with_depth (acfg, method, depth + 1);
4563 while ((field = mono_class_get_fields (klass, &iter))) {
4564 if (field->type->type == MONO_TYPE_GENERICINST)
4565 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4568 if (klass->delegate) {
4569 method = mono_get_delegate_invoke (klass);
4571 method = mono_marshal_get_delegate_invoke (method, NULL);
4573 if (acfg->aot_opts.log_generics)
4574 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4576 add_method (acfg, method);
4579 /* Add superclasses */
4581 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4584 * For ICollection<T>, add instances of the helper methods
4585 * in Array, since a T[] could be cast to ICollection<T>.
4587 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4588 (!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"))) {
4589 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4590 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4594 if (!strcmp (klass->name, "IEnumerator`1"))
4595 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4597 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4599 /* Add the T[]/InternalEnumerator class */
4600 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4605 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4606 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4610 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4611 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4612 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4616 while ((method = mono_class_get_methods (array_class, &iter))) {
4617 if (strstr (method->name, name_prefix)) {
4618 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4620 add_extra_method_with_depth (acfg, m, depth);
4624 g_free (name_prefix);
4627 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4628 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4630 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4631 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4632 MonoGenericContext ctx;
4633 MonoType *args [16];
4635 memset (&ctx, 0, sizeof (ctx));
4637 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4639 args [0] = &tclass->byval_arg;
4640 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4642 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4643 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4645 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4646 MonoClass *gcomparer_inst;
4647 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4648 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4649 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4651 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4655 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4656 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4658 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4659 MonoClass *iface, *gcomparer, *iface_inst;
4660 MonoGenericContext ctx;
4661 MonoType *args [16];
4663 memset (&ctx, 0, sizeof (ctx));
4665 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4667 args [0] = &tclass->byval_arg;
4668 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4670 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4671 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4673 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4674 MonoClass *gcomparer_inst;
4677 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4678 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4679 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4680 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4684 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4685 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4686 MonoClass *enum_comparer;
4687 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4688 MonoGenericContext ctx;
4689 MonoType *args [16];
4691 if (mono_class_is_enum (tclass)) {
4692 MonoClass *enum_comparer_inst;
4695 memset (&ctx, 0, sizeof (ctx));
4696 args [0] = &tclass->byval_arg;
4697 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4699 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4700 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4701 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4702 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4706 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4707 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4708 MonoClass *comparer;
4709 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4710 MonoGenericContext ctx;
4711 MonoType *args [16];
4713 if (mono_class_is_enum (tclass)) {
4714 MonoClass *comparer_inst;
4717 memset (&ctx, 0, sizeof (ctx));
4718 args [0] = &tclass->byval_arg;
4719 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4721 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4722 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4723 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4724 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4730 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4733 MonoGenericContext ctx;
4734 MonoType *args [16];
4736 if (acfg->aot_opts.no_instances)
4739 memset (&ctx, 0, sizeof (ctx));
4741 for (i = 0; i < ninsts; ++i) {
4743 MonoClass *generic_inst;
4744 args [0] = insts [i];
4745 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4746 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4747 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4748 add_generic_class (acfg, generic_inst, force, "");
4753 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4756 MonoMethodHeader *header;
4757 MonoMethodSignature *sig;
4760 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4762 sig = mono_method_signature (method);
4765 for (j = 0; j < sig->param_count; ++j)
4766 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4767 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4770 header = mono_method_get_header_checked (method, &error);
4773 for (j = 0; j < header->num_locals; ++j)
4774 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4775 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4776 mono_metadata_free_mh (header);
4778 mono_error_cleanup (&error); /* FIXME report the error */
4784 * add_generic_instances:
4786 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4789 add_generic_instances (MonoAotCompile *acfg)
4794 MonoGenericContext *context;
4796 if (acfg->aot_opts.no_instances)
4799 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4801 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4802 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4805 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4806 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4807 mono_error_cleanup (&error);
4811 if (method->klass->image != acfg->image)
4814 context = mono_method_get_context (method);
4816 if (context && ((context->class_inst && context->class_inst->is_open)))
4820 * For open methods, create an instantiation which can be passed to the JIT.
4821 * FIXME: Handle class_inst as well.
4823 if (context && context->method_inst && context->method_inst->is_open) {
4825 MonoGenericContext shared_context;
4826 MonoGenericInst *inst;
4827 MonoType **type_argv;
4829 MonoMethod *declaring_method;
4830 gboolean supported = TRUE;
4832 /* Check that the context doesn't contain open constructed types */
4833 if (context->class_inst) {
4834 inst = context->class_inst;
4835 for (i = 0; i < inst->type_argc; ++i) {
4836 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)
4838 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4842 if (context->method_inst) {
4843 inst = context->method_inst;
4844 for (i = 0; i < inst->type_argc; ++i) {
4845 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)
4847 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4855 memset (&shared_context, 0, sizeof (MonoGenericContext));
4857 inst = context->class_inst;
4859 type_argv = g_new0 (MonoType*, inst->type_argc);
4860 for (i = 0; i < inst->type_argc; ++i) {
4861 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)
4862 type_argv [i] = &mono_defaults.object_class->byval_arg;
4864 type_argv [i] = inst->type_argv [i];
4867 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4871 inst = context->method_inst;
4873 type_argv = g_new0 (MonoType*, inst->type_argc);
4874 for (i = 0; i < inst->type_argc; ++i) {
4875 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)
4876 type_argv [i] = &mono_defaults.object_class->byval_arg;
4878 type_argv [i] = inst->type_argv [i];
4881 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4885 if (method->is_generic || mono_class_is_gtd (method->klass))
4886 declaring_method = method;
4888 declaring_method = mono_method_get_declaring_generic_method (method);
4890 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4891 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4895 * If the method is fully sharable, it was already added in place of its
4896 * generic definition.
4898 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4902 * FIXME: Partially shared methods are not shared here, so we end up with
4903 * many identical methods.
4905 add_extra_method (acfg, method);
4908 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4912 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4914 klass = mono_class_get_checked (acfg->image, token, &error);
4915 if (!klass || klass->rank) {
4916 mono_error_cleanup (&error);
4920 add_generic_class (acfg, klass, FALSE, "typespec");
4923 /* Add types of args/locals */
4924 for (i = 0; i < acfg->methods->len; ++i) {
4925 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4926 add_types_from_method_header (acfg, method);
4929 if (acfg->image == mono_defaults.corlib) {
4931 MonoType *insts [256];
4934 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4936 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4937 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4938 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4939 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4940 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4941 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4942 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4943 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4944 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4945 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4947 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4948 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4950 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4951 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4953 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4955 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4957 MonoClass *enum_comparer;
4958 MonoType *insts [16];
4962 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4963 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4964 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4965 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4966 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4967 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4970 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4971 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4972 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4975 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4976 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4977 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4979 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4981 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4982 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4983 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4986 /* Add instances of the array generic interfaces for primitive types */
4987 /* This will add instances of the InternalArray_ helper methods in Array too */
4988 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4990 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4992 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4994 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4996 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4998 add_instances_of (acfg, klass, insts, ninsts, TRUE);
5001 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
5002 * used for all instances of GetGenericValueImpl by the AOT runtime.
5005 MonoGenericContext ctx;
5006 MonoType *args [16];
5007 MonoMethod *get_method;
5008 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5010 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5014 memset (&ctx, 0, sizeof (ctx));
5015 args [0] = &mono_defaults.object_class->byval_arg;
5016 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5017 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5018 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5022 /* Same for CompareExchange<T>/Exchange<T> */
5024 MonoGenericContext ctx;
5025 MonoType *args [16];
5027 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5028 gpointer iter = NULL;
5030 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5031 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5033 memset (&ctx, 0, sizeof (ctx));
5034 args [0] = &mono_defaults.object_class->byval_arg;
5035 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5036 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5037 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5042 /* Same for Volatile.Read/Write<T> */
5044 MonoGenericContext ctx;
5045 MonoType *args [16];
5047 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5048 gpointer iter = NULL;
5050 if (volatile_klass) {
5051 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5052 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5054 memset (&ctx, 0, sizeof (ctx));
5055 args [0] = &mono_defaults.object_class->byval_arg;
5056 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5057 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5058 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5064 /* object[] accessor wrappers. */
5065 for (i = 1; i < 4; ++i) {
5066 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5069 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5072 m = mono_marshal_get_array_accessor_wrapper (m);
5073 add_extra_method (acfg, m);
5075 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5078 m = mono_marshal_get_array_accessor_wrapper (m);
5079 add_extra_method (acfg, m);
5081 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5084 m = mono_marshal_get_array_accessor_wrapper (m);
5085 add_extra_method (acfg, m);
5091 * is_direct_callable:
5093 * Return whenever the method identified by JI is directly callable without
5094 * going through the PLT.
5097 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5099 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5100 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5102 gboolean direct_callable = TRUE;
5104 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5105 direct_callable = FALSE;
5106 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5107 // FIXME: Maybe call the wrapper directly ?
5108 direct_callable = FALSE;
5110 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5111 /* Disable this so all calls go through load_method (), see the
5112 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5113 * mono_debugger_agent_init ().
5115 direct_callable = FALSE;
5118 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5119 /* sgen does some initialization when the allocator method is created */
5120 direct_callable = FALSE;
5121 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5122 /* we don't know at compile time whether sgen is concurrent or not */
5123 direct_callable = FALSE;
5125 if (direct_callable)
5128 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5129 if (acfg->aot_opts.direct_pinvoke)
5131 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5132 if (acfg->aot_opts.direct_icalls)
5140 #ifdef MONO_ARCH_AOT_SUPPORTED
5142 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5144 MonoImage *image = method->klass->image;
5145 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5146 MonoTableInfo *tables = image->tables;
5147 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5148 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5149 guint32 im_cols [MONO_IMPLMAP_SIZE];
5152 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5156 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5159 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5161 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5164 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5166 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5172 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5179 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5181 if (a->native_offset == b->native_offset)
5182 return a->il_offset - b->il_offset;
5184 return a->native_offset - b->native_offset;
5188 * compute_line_numbers:
5190 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5193 static MonoDebugSourceLocation**
5194 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5196 MonoDebugMethodInfo *minfo;
5197 MonoDebugLineNumberEntry *ln_array;
5198 MonoDebugSourceLocation *loc;
5199 int i, prev_line, prev_il_offset;
5200 int *native_to_il_offset = NULL;
5201 MonoDebugSourceLocation **res;
5204 minfo = mono_debug_lookup_method (method);
5207 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5208 if (debug_info->code_size != code_size)
5211 g_assert (code_size);
5213 /* Compute the native->IL offset mapping */
5215 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5216 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5218 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5220 native_to_il_offset = g_new0 (int, code_size + 1);
5222 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5224 MonoDebugLineNumberEntry *lne = &ln_array [i];
5227 for (j = 0; j < lne->native_offset; ++j)
5228 native_to_il_offset [j] = -1;
5231 if (i < debug_info->num_line_numbers - 1) {
5232 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5234 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5235 native_to_il_offset [j] = lne->il_offset;
5237 for (j = lne->native_offset; j < code_size; ++j)
5238 native_to_il_offset [j] = lne->il_offset;
5243 /* Compute the native->line number mapping */
5244 res = g_new0 (MonoDebugSourceLocation*, code_size);
5245 prev_il_offset = -1;
5248 for (i = 0; i < code_size; ++i) {
5249 int il_offset = native_to_il_offset [i];
5251 if (il_offset == -1 || il_offset == prev_il_offset)
5253 prev_il_offset = il_offset;
5254 loc = mono_debug_method_lookup_location (minfo, il_offset);
5255 if (!(loc && loc->source_file))
5257 if (loc->row == prev_line) {
5258 mono_debug_free_source_location (loc);
5261 prev_line = loc->row;
5262 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5264 /* This will cover the prolog too */
5274 get_file_index (MonoAotCompile *acfg, const char *source_file)
5278 // FIXME: Free these
5279 if (!acfg->dwarf_ln_filenames)
5280 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5281 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5283 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5284 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5285 emit_unset_mode (acfg);
5286 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5298 * emit_and_reloc_code:
5300 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5301 * is true, calls are made through the GOT too. This is used for emitting trampolines
5302 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5303 * since trampolines are needed to make PTL work.
5306 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5308 int i, pindex, start_index;
5310 MonoJumpInfo *patch_info;
5311 MonoDebugSourceLocation **locs = NULL;
5312 gboolean skip, prologue_end = FALSE;
5313 #ifdef MONO_ARCH_AOT_SUPPORTED
5314 gboolean direct_call, external_call;
5316 const char *direct_call_target = 0;
5317 const char *direct_pinvoke;
5320 if (acfg->gas_line_numbers && method && debug_info) {
5321 locs = compute_line_numbers (method, code_len, debug_info);
5323 int findex = get_file_index (acfg, "<unknown>");
5324 emit_unset_mode (acfg);
5325 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5329 /* Collect and sort relocations */
5330 patches = g_ptr_array_new ();
5331 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5332 g_ptr_array_add (patches, patch_info);
5333 g_ptr_array_sort (patches, compare_patches);
5336 for (i = 0; i < code_len; i += INST_LEN) {
5338 for (pindex = start_index; pindex < patches->len; ++pindex) {
5339 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5340 if (patch_info->ip.i >= i)
5344 if (locs && locs [i]) {
5345 MonoDebugSourceLocation *loc = locs [i];
5347 const char *options;
5349 findex = get_file_index (acfg, loc->source_file);
5350 emit_unset_mode (acfg);
5352 options = " prologue_end";
5355 prologue_end = TRUE;
5356 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5357 mono_debug_free_source_location (loc);
5361 #ifdef MONO_ARCH_AOT_SUPPORTED
5362 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5363 start_index = pindex;
5365 switch (patch_info->type) {
5366 case MONO_PATCH_INFO_NONE:
5368 case MONO_PATCH_INFO_GOT_OFFSET: {
5371 arch_emit_got_offset (acfg, code + i, &code_size);
5372 i += code_size - INST_LEN;
5374 patch_info->type = MONO_PATCH_INFO_NONE;
5377 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5378 int code_size, index;
5379 char *selector = (char *)patch_info->data.target;
5381 if (!acfg->objc_selector_to_index)
5382 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5383 if (!acfg->objc_selectors)
5384 acfg->objc_selectors = g_ptr_array_new ();
5385 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5389 index = acfg->objc_selector_index;
5390 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5391 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5392 acfg->objc_selector_index ++;
5395 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5396 i += code_size - INST_LEN;
5398 patch_info->type = MONO_PATCH_INFO_NONE;
5403 * If this patch is a call, try emitting a direct call instead of
5404 * through a PLT entry. This is possible if the called method is in
5405 * the same assembly and requires no initialization.
5407 direct_call = FALSE;
5408 external_call = FALSE;
5409 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5410 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5411 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5412 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5414 direct_call_target = callee_cfg->asm_symbol;
5415 patch_info->type = MONO_PATCH_INFO_NONE;
5416 acfg->stats.direct_calls ++;
5419 acfg->stats.all_calls ++;
5420 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5421 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5422 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5423 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5425 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5426 if (direct_pinvoke) {
5428 g_assert (strlen (direct_pinvoke) < 1000);
5429 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5432 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5433 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5434 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5435 /* Call to a C function implementing a jit icall */
5437 external_call = TRUE;
5438 g_assert (strlen (sym) < 1000);
5439 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5441 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5442 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5443 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5444 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5445 /* Call to a jit icall without a wrapper */
5447 external_call = TRUE;
5448 g_assert (strlen (sym) < 1000);
5449 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5454 patch_info->type = MONO_PATCH_INFO_NONE;
5455 acfg->stats.direct_calls ++;
5458 if (!got_only && !direct_call) {
5459 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5461 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5463 direct_call_target = plt_entry->symbol;
5465 /* Nullify the patch */
5466 patch_info->type = MONO_PATCH_INFO_NONE;
5467 plt_entry->jit_used = TRUE;
5474 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5475 i += call_size - INST_LEN;
5479 got_slot = get_got_offset (acfg, FALSE, patch_info);
5481 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5482 i += code_size - INST_LEN;
5488 #endif /* MONO_ARCH_AOT_SUPPORTED */
5491 /* Find next patch */
5493 for (pindex = start_index; pindex < patches->len; ++pindex) {
5494 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5495 if (patch_info->ip.i >= i)
5499 /* Try to emit multiple bytes at once */
5500 if (pindex < patches->len && patch_info->ip.i > i) {
5503 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5504 if (locs && locs [limit])
5508 emit_code_bytes (acfg, code + i, limit - i);
5509 i = limit - INST_LEN;
5511 emit_code_bytes (acfg, code + i, INST_LEN);
5516 g_ptr_array_free (patches, TRUE);
5523 * Return a modified version of S which only includes characters permissible in symbols.
5526 sanitize_symbol (MonoAotCompile *acfg, char *s)
5528 gboolean process = FALSE;
5537 for (i = 0; i < len; ++i)
5538 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5543 gs = g_string_sized_new (len);
5544 for (i = 0; i < len; ++i) {
5546 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5547 g_string_append_c (gs, c);
5548 } else if (c > 0x7f) {
5549 /* multi-byte utf8 */
5550 g_string_append_printf (gs, "_0x%x", c);
5553 while (c >> 6 == 0x2) {
5554 g_string_append_printf (gs, "%x", c);
5558 g_string_append_printf (gs, "_");
5561 g_string_append_c (gs, '_');
5565 res = mono_mempool_strdup (acfg->mempool, gs->str);
5566 g_string_free (gs, TRUE);
5571 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5573 char *name1, *name2, *cached;
5574 int i, j, len, count;
5575 MonoMethod *cached_method;
5577 name1 = mono_method_full_name (method, TRUE);
5580 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5581 if ((!prefix || !*prefix) && name1 [0] == 'L')
5585 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5586 char adjustedPrefix [MAX_SYMBOL_SIZE];
5587 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5590 len = strlen (name1);
5591 name2 = (char *)malloc (strlen (prefix) + len + 16);
5592 memcpy (name2, prefix, strlen (prefix));
5593 j = strlen (prefix);
5594 for (i = 0; i < len; ++i) {
5595 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5597 } else if (isalnum (name1 [i])) {
5598 name2 [j ++] = name1 [i];
5599 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5601 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5604 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5614 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5615 if (!(cached_method && cached_method != method))
5617 sprintf (name2 + j, "_%d", count);
5621 cached = g_strdup (name2);
5622 g_hash_table_insert (cache, cached, method);
5628 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5633 char *debug_sym = NULL;
5634 char *symbol = NULL;
5635 int func_alignment = AOT_FUNC_ALIGNMENT;
5638 method = cfg->orig_method;
5639 code = cfg->native_code;
5641 method_index = get_method_index (acfg, method);
5642 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5644 /* Make the labels local */
5645 emit_section_change (acfg, ".text", 0);
5646 emit_alignment_code (acfg, func_alignment);
5648 if (acfg->global_symbols && acfg->need_no_dead_strip)
5649 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5651 emit_label (acfg, cfg->asm_symbol);
5653 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5655 * Write a C style symbol for every method, this has two uses:
5656 * - it works on platforms where the dwarf debugging info is not
5658 * - it allows the setting of breakpoints of aot-ed methods.
5660 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5661 cfg->asm_debug_symbol = g_strdup (debug_sym);
5663 if (acfg->need_no_dead_strip)
5664 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5665 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5666 emit_label (acfg, debug_sym);
5669 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5671 /* Emit a global symbol for the method */
5672 emit_global_inner (acfg, export_name, TRUE);
5673 emit_label (acfg, export_name);
5676 if (cfg->verbose_level > 0)
5677 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5679 acfg->stats.code_size += cfg->code_len;
5681 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5683 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 ()));
5687 if (acfg->aot_opts.write_symbols) {
5689 emit_symbol_size (acfg, debug_sym, ".");
5691 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5695 emit_label (acfg, symbol);
5702 * Encode PATCH_INFO into its disk representation.
5705 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5709 switch (patch_info->type) {
5710 case MONO_PATCH_INFO_NONE:
5712 case MONO_PATCH_INFO_IMAGE:
5713 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5715 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5716 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5717 case MONO_PATCH_INFO_GC_NURSERY_START:
5718 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5720 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5721 encode_value (patch_info->data.index, p, &p);
5723 case MONO_PATCH_INFO_METHOD_REL:
5724 encode_value ((gint)patch_info->data.offset, p, &p);
5726 case MONO_PATCH_INFO_SWITCH: {
5727 gpointer *table = (gpointer *)patch_info->data.table->table;
5730 encode_value (patch_info->data.table->table_size, p, &p);
5731 for (k = 0; k < patch_info->data.table->table_size; k++)
5732 encode_value ((int)(gssize)table [k], p, &p);
5735 case MONO_PATCH_INFO_METHODCONST:
5736 case MONO_PATCH_INFO_METHOD:
5737 case MONO_PATCH_INFO_METHOD_JUMP:
5738 case MONO_PATCH_INFO_ICALL_ADDR:
5739 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5740 case MONO_PATCH_INFO_METHOD_RGCTX:
5741 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5742 encode_method_ref (acfg, patch_info->data.method, p, &p);
5744 case MONO_PATCH_INFO_AOT_JIT_INFO:
5745 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5746 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5747 encode_value (patch_info->data.index, p, &p);
5749 case MONO_PATCH_INFO_INTERNAL_METHOD:
5750 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5751 guint32 len = strlen (patch_info->data.name);
5753 encode_value (len, p, &p);
5755 memcpy (p, patch_info->data.name, len);
5760 case MONO_PATCH_INFO_LDSTR: {
5761 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5762 guint32 token = patch_info->data.token->token;
5763 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5764 encode_value (image_index, p, &p);
5765 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5768 case MONO_PATCH_INFO_RVA:
5769 case MONO_PATCH_INFO_DECLSEC:
5770 case MONO_PATCH_INFO_LDTOKEN:
5771 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5772 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5773 encode_value (patch_info->data.token->token, p, &p);
5774 encode_value (patch_info->data.token->has_context, p, &p);
5775 if (patch_info->data.token->has_context)
5776 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5778 case MONO_PATCH_INFO_EXC_NAME: {
5779 MonoClass *ex_class;
5782 mono_class_load_from_name (mono_defaults.exception_class->image,
5783 "System", (const char *)patch_info->data.target);
5784 encode_klass_ref (acfg, ex_class, p, &p);
5787 case MONO_PATCH_INFO_R4:
5788 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5790 case MONO_PATCH_INFO_R8:
5791 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5792 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5794 case MONO_PATCH_INFO_VTABLE:
5795 case MONO_PATCH_INFO_CLASS:
5796 case MONO_PATCH_INFO_IID:
5797 case MONO_PATCH_INFO_ADJUSTED_IID:
5798 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5800 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5801 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5802 if (patch_info->data.del_tramp->method) {
5803 encode_value (1, p, &p);
5804 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5806 encode_value (0, p, &p);
5808 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5810 case MONO_PATCH_INFO_FIELD:
5811 case MONO_PATCH_INFO_SFLDA:
5812 encode_field_info (acfg, patch_info->data.field, p, &p);
5814 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5816 case MONO_PATCH_INFO_RGCTX_FETCH:
5817 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5818 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5823 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5824 * reference the same method, so encode the method only once.
5826 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5828 buf2 = (guint8 *)g_malloc (1024);
5831 encode_method_ref (acfg, entry->method, p2, &p2);
5832 g_assert (p2 - buf2 < 1024);
5834 offset = add_to_blob (acfg, buf2, p2 - buf2);
5837 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5842 encode_value (offset, p, &p);
5843 g_assert ((int)entry->info_type < 256);
5844 g_assert (entry->data->type < 256);
5845 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5846 encode_patch (acfg, entry->data, p, &p);
5849 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5850 case MONO_PATCH_INFO_AOT_MODULE:
5852 case MONO_PATCH_INFO_SIGNATURE:
5853 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5854 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5856 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5857 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5858 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5860 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5861 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5864 encode_method_ref (acfg, info->method, p, &p);
5865 encode_value (info->num_entries, p, &p);
5866 for (i = 0; i < info->num_entries; ++i) {
5867 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5869 encode_value (template_->info_type, p, &p);
5870 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5871 case MONO_PATCH_INFO_CLASS:
5872 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5874 case MONO_PATCH_INFO_FIELD:
5875 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5878 g_assert_not_reached ();
5884 case MONO_PATCH_INFO_LDSTR_LIT: {
5885 const char *s = (const char *)patch_info->data.target;
5886 int len = strlen (s);
5888 encode_value (len, p, &p);
5889 memcpy (p, s, len + 1);
5893 case MONO_PATCH_INFO_VIRT_METHOD:
5894 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5895 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5897 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5898 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5901 g_warning ("unable to handle jump info %d", patch_info->type);
5902 g_assert_not_reached ();
5909 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5912 guint32 pindex, offset;
5913 MonoJumpInfo *patch_info;
5915 encode_value (n_patches, p, &p);
5917 for (pindex = 0; pindex < patches->len; ++pindex) {
5918 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5920 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5924 offset = get_got_offset (acfg, llvm, patch_info);
5925 encode_value (offset, p, &p);
5932 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5935 int pindex, buf_size, n_patches;
5937 MonoJumpInfo *patch_info;
5938 guint32 method_index;
5940 guint32 first_got_offset;
5942 method = cfg->orig_method;
5944 method_index = get_method_index (acfg, method);
5946 /* Sort relocations */
5947 patches = g_ptr_array_new ();
5948 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5949 g_ptr_array_add (patches, patch_info);
5950 g_ptr_array_sort (patches, compare_patches);
5952 first_got_offset = acfg->cfgs [method_index]->got_offset;
5954 /**********************/
5955 /* Encode method info */
5956 /**********************/
5958 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5959 p = buf = (guint8 *)g_malloc (buf_size);
5961 if (mono_class_get_cctor (method->klass)) {
5962 encode_value (1, p, &p);
5963 encode_klass_ref (acfg, method->klass, p, &p);
5965 /* Not needed when loading the method */
5966 encode_value (0, p, &p);
5969 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5972 for (pindex = 0; pindex < patches->len; ++pindex) {
5973 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5975 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5976 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5977 patch_info->type = MONO_PATCH_INFO_NONE;
5982 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5983 /* Stored in a GOT slot initialized at module load time */
5984 patch_info->type = MONO_PATCH_INFO_NONE;
5988 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5989 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5990 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5991 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5992 /* Stored in a GOT slot initialized at module load time */
5993 patch_info->type = MONO_PATCH_INFO_NONE;
5997 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5998 /* Calls are made through the PLT */
5999 patch_info->type = MONO_PATCH_INFO_NONE;
6007 g_assert (cfg->has_got_slots);
6009 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6011 g_ptr_array_free (patches, TRUE);
6013 acfg->stats.info_size += p - buf;
6015 g_assert (p - buf < buf_size);
6017 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6022 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6024 guint32 cache_index;
6027 /* Reuse the unwind module to canonize and store unwind info entries */
6028 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6030 /* Use +/- 1 to distinguish 0s from missing entries */
6031 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6039 * It would be easier to use assembler symbols, but the caller needs an
6042 offset = acfg->unwind_info_offset;
6043 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6044 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6047 encode_value (encoded_len, p, &p);
6049 acfg->unwind_info_offset += encoded_len + (p - buf);
6055 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6058 guint32 debug_info_size, seq_points_size;
6060 MonoMethodHeader *header;
6061 guint8 *p, *buf, *debug_info;
6062 MonoJitInfo *jinfo = cfg->jit_info;
6064 gboolean use_unwind_ops = FALSE;
6065 MonoSeqPointInfo *seq_points;
6067 code = cfg->native_code;
6068 header = cfg->header;
6070 if (!acfg->aot_opts.nodebug) {
6071 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6074 debug_info_size = 0;
6077 seq_points = cfg->seq_point_info;
6078 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6080 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6082 p = buf = (guint8 *)g_malloc (buf_size);
6084 use_unwind_ops = cfg->unwind_ops != NULL;
6086 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);
6088 encode_value (flags, p, &p);
6090 if (use_unwind_ops) {
6091 guint32 encoded_len;
6093 guint32 unwind_desc;
6095 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6097 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6098 encode_value (unwind_desc, p, &p);
6102 encode_value (jinfo->unwind_info, p, &p);
6105 /*Encode the number of holes before the number of clauses to make decoding easier*/
6106 if (jinfo->has_try_block_holes) {
6107 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6108 encode_value (table->num_holes, p, &p);
6111 if (jinfo->has_arch_eh_info) {
6113 * In AOT mode, the code length is calculated from the address of the previous method,
6114 * which could include alignment padding, so calculating the start of the epilog as
6115 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6117 encode_value (jinfo->code_size, p, &p);
6120 /* Exception table */
6121 if (cfg->compile_llvm) {
6123 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6124 * since the information is only available to llc. Instead, we let llc save the data
6125 * into the LSDA, and read it from there at runtime.
6127 /* The assembly might be CIL stripped so emit the data ourselves */
6128 if (header->num_clauses)
6129 encode_value (header->num_clauses, p, &p);
6131 for (k = 0; k < header->num_clauses; ++k) {
6132 MonoExceptionClause *clause;
6134 clause = &header->clauses [k];
6136 encode_value (clause->flags, p, &p);
6137 if (clause->data.catch_class) {
6138 encode_value (1, p, &p);
6139 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6141 encode_value (0, p, &p);
6144 /* Emit the IL ranges too, since they might not be available at runtime */
6145 encode_value (clause->try_offset, p, &p);
6146 encode_value (clause->try_len, p, &p);
6147 encode_value (clause->handler_offset, p, &p);
6148 encode_value (clause->handler_len, p, &p);
6150 /* Emit a list of nesting clauses */
6151 for (i = 0; i < header->num_clauses; ++i) {
6153 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6155 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6157 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6158 encode_value (i, p, &p);
6160 encode_value (-1, p, &p);
6163 if (jinfo->num_clauses)
6164 encode_value (jinfo->num_clauses, p, &p);
6166 for (k = 0; k < jinfo->num_clauses; ++k) {
6167 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6169 encode_value (ei->flags, p, &p);
6170 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6171 /* Not used for catch clauses */
6172 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6173 encode_value (ei->exvar_offset, p, &p);
6175 encode_value (ei->exvar_offset, p, &p);
6178 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6179 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6181 if (ei->data.catch_class) {
6185 buf2 = (guint8 *)g_malloc (4096);
6187 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6189 g_assert (len < 4096);
6190 encode_value (len, p, &p);
6191 memcpy (p, buf2, len);
6195 encode_value (0, p, &p);
6199 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6200 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6201 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6205 if (jinfo->has_try_block_holes) {
6206 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6207 for (i = 0; i < table->num_holes; ++i) {
6208 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6209 encode_value (hole->clause, p, &p);
6210 encode_value (hole->length, p, &p);
6211 encode_value (hole->offset, p, &p);
6215 if (jinfo->has_arch_eh_info) {
6216 MonoArchEHJitInfo *eh_info;
6218 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6219 encode_value (eh_info->stack_size, p, &p);
6220 encode_value (eh_info->epilog_size, p, &p);
6223 if (jinfo->has_generic_jit_info) {
6224 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6225 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6229 encode_value (gi->nlocs, p, &p);
6231 for (i = 0; i < gi->nlocs; ++i) {
6232 MonoDwarfLocListEntry *entry = &gi->locations [i];
6234 encode_value (entry->is_reg ? 1 : 0, p, &p);
6235 encode_value (entry->reg, p, &p);
6237 encode_value (entry->offset, p, &p);
6239 g_assert (entry->from == 0);
6241 encode_value (entry->from, p, &p);
6242 encode_value (entry->to, p, &p);
6245 if (!cfg->compile_llvm) {
6246 encode_value (gi->has_this ? 1 : 0, p, &p);
6247 encode_value (gi->this_reg, p, &p);
6248 encode_value (gi->this_offset, p, &p);
6253 * Need to encode jinfo->method too, since it is not equal to 'method'
6254 * when using generic sharing.
6256 buf2 = (guint8 *)g_malloc (4096);
6258 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6260 g_assert (len < 4096);
6261 encode_value (len, p, &p);
6262 memcpy (p, buf2, len);
6266 if (gsctx && gsctx->is_gsharedvt) {
6267 encode_value (1, p, &p);
6269 encode_value (0, p, &p);
6273 if (seq_points_size)
6274 p += mono_seq_point_info_write (seq_points, p);
6276 g_assert (debug_info_size < buf_size);
6278 encode_value (debug_info_size, p, &p);
6279 if (debug_info_size) {
6280 memcpy (p, debug_info, debug_info_size);
6281 p += debug_info_size;
6282 g_free (debug_info);
6287 encode_value (cfg->gc_map_size, p, &p);
6288 /* The GC map requires 4 bytes of alignment */
6289 while ((gsize)p % 4)
6291 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6292 p += cfg->gc_map_size;
6295 acfg->stats.ex_info_size += p - buf;
6297 g_assert (p - buf < buf_size);
6300 /* The GC Map requires 4 byte alignment */
6301 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6306 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6309 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6311 int i, buf_size, res;
6312 gboolean no_special_static, cant_encode;
6313 gpointer iter = NULL;
6316 mono_error_cleanup (&error);
6320 p = buf = (guint8 *)g_malloc (buf_size);
6322 /* Mark as unusable */
6323 encode_value (-1, p, &p);
6325 res = add_to_blob (acfg, buf, p - buf);
6331 buf_size = 10240 + (klass->vtable_size * 16);
6332 p = buf = (guint8 *)g_malloc (buf_size);
6336 mono_class_init (klass);
6338 mono_class_get_nested_types (klass, &iter);
6339 g_assert (klass->nested_classes_inited);
6341 mono_class_setup_vtable (klass);
6344 * Emit all the information which is required for creating vtables so
6345 * the runtime does not need to create the MonoMethod structures which
6346 * take up a lot of space.
6349 no_special_static = !mono_class_has_special_static_fields (klass);
6351 /* Check whenever we have enough info to encode the vtable */
6352 cant_encode = FALSE;
6353 for (i = 0; i < klass->vtable_size; ++i) {
6354 MonoMethod *cm = klass->vtable [i];
6356 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6360 mono_class_has_finalizer (klass);
6361 if (mono_class_has_failure (klass))
6364 if (mono_class_is_gtd (klass) || cant_encode) {
6365 encode_value (-1, p, &p);
6367 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6368 encode_value (klass->vtable_size, p, &p);
6369 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);
6370 if (klass->has_cctor)
6371 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6372 if (klass->has_finalize)
6373 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6375 encode_value (klass->instance_size, p, &p);
6376 encode_value (mono_class_data_size (klass), p, &p);
6377 encode_value (klass->packing_size, p, &p);
6378 encode_value (klass->min_align, p, &p);
6380 for (i = 0; i < klass->vtable_size; ++i) {
6381 MonoMethod *cm = klass->vtable [i];
6384 encode_method_ref (acfg, cm, p, &p);
6386 encode_value (0, p, &p);
6390 acfg->stats.class_info_size += p - buf;
6392 g_assert (p - buf < buf_size);
6393 res = add_to_blob (acfg, buf, p - buf);
6400 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6402 char *debug_sym = NULL;
6405 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6406 /* Need to add a prefix to create unique symbols */
6407 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6409 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6410 prefix = mangle_symbol_alloc ("plt_");
6412 prefix = g_strdup ("plt_");
6417 case MONO_PATCH_INFO_METHOD:
6418 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6420 case MONO_PATCH_INFO_INTERNAL_METHOD:
6421 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6423 case MONO_PATCH_INFO_RGCTX_FETCH:
6424 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6426 case MONO_PATCH_INFO_ICALL_ADDR:
6427 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6428 char *s = get_debug_sym (ji->data.method, "", cache);
6430 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6434 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6435 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6443 return sanitize_symbol (acfg, debug_sym);
6447 * Calls made from AOTed code are routed through a table of jumps similar to the
6448 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6449 * control to the AOT runtime through a trampoline.
6452 emit_plt (MonoAotCompile *acfg)
6456 if (acfg->aot_opts.llvm_only) {
6457 g_assert (acfg->plt_offset == 1);
6463 emit_section_change (acfg, ".text", 0);
6464 emit_alignment_code (acfg, 16);
6465 emit_info_symbol (acfg, "plt");
6466 emit_label (acfg, acfg->plt_symbol);
6468 for (i = 0; i < acfg->plt_offset; ++i) {
6469 char *debug_sym = NULL;
6470 MonoPltEntry *plt_entry = NULL;
6474 * The first plt entry is unused.
6478 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6480 debug_sym = plt_entry->debug_sym;
6482 if (acfg->thumb_mixed && !plt_entry->jit_used)
6483 /* Emit only a thumb version */
6486 /* Skip plt entries not actually called */
6487 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6490 if (acfg->llvm && !acfg->thumb_mixed) {
6491 emit_label (acfg, plt_entry->llvm_symbol);
6493 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6494 #if defined(TARGET_MACH)
6495 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6501 if (acfg->need_no_dead_strip) {
6502 emit_unset_mode (acfg);
6503 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6505 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6506 emit_label (acfg, debug_sym);
6509 emit_label (acfg, plt_entry->symbol);
6511 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6514 emit_symbol_size (acfg, debug_sym, ".");
6517 if (acfg->thumb_mixed) {
6518 /* Make sure the ARM symbols don't alias the thumb ones */
6519 emit_zero_bytes (acfg, 16);
6522 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6525 for (i = 0; i < acfg->plt_offset; ++i) {
6526 char *debug_sym = NULL;
6527 MonoPltEntry *plt_entry = NULL;
6532 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6534 /* Skip plt entries not actually called by LLVM code */
6535 if (!plt_entry->llvm_used)
6538 if (acfg->aot_opts.write_symbols) {
6539 if (plt_entry->debug_sym)
6540 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6544 #if defined(TARGET_MACH)
6545 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6546 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6548 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6549 emit_label (acfg, debug_sym);
6551 fprintf (acfg->fp, "\n.thumb_func\n");
6553 emit_label (acfg, plt_entry->llvm_symbol);
6556 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6558 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6561 emit_symbol_size (acfg, debug_sym, ".");
6567 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6569 emit_info_symbol (acfg, "plt_end");
6573 * emit_trampoline_full:
6575 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6576 * create_jit_info_for_trampoline ().
6578 static G_GNUC_UNUSED void
6579 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6581 char start_symbol [MAX_SYMBOL_SIZE];
6582 char end_symbol [MAX_SYMBOL_SIZE];
6583 char symbol [MAX_SYMBOL_SIZE];
6584 guint32 buf_size, info_offset;
6585 MonoJumpInfo *patch_info;
6598 code_size = info->code_size;
6600 unwind_ops = info->unwind_ops;
6604 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6606 emit_section_change (acfg, ".text", 0);
6607 emit_global (acfg, start_symbol, TRUE);
6608 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6609 emit_label (acfg, start_symbol);
6611 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6612 emit_label (acfg, symbol);
6615 * The code should access everything through the GOT, so we pass
6618 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6620 emit_symbol_size (acfg, start_symbol, ".");
6623 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6624 emit_label (acfg, end_symbol);
6629 /* Sort relocations */
6630 patches = g_ptr_array_new ();
6631 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6632 if (patch_info->type != MONO_PATCH_INFO_NONE)
6633 g_ptr_array_add (patches, patch_info);
6634 g_ptr_array_sort (patches, compare_patches);
6636 buf_size = patches->len * 128 + 128;
6637 buf = (guint8 *)g_malloc (buf_size);
6640 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6641 g_assert (p - buf < buf_size);
6642 g_ptr_array_free (patches, TRUE);
6644 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6646 info_offset = add_to_blob (acfg, buf, p - buf);
6648 emit_section_change (acfg, RODATA_SECT, 0);
6649 emit_global (acfg, symbol, FALSE);
6650 emit_label (acfg, symbol);
6652 emit_int32 (acfg, info_offset);
6656 guint32 encoded_len;
6660 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6662 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6663 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6666 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6667 emit_int32 (acfg, uw_offset);
6670 /* Emit debug info */
6672 char symbol2 [MAX_SYMBOL_SIZE];
6674 sprintf (symbol, "%s", name);
6675 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6678 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6684 static G_GNUC_UNUSED void
6685 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6687 emit_trampoline_full (acfg, got_offset, info, TRUE);
6691 emit_trampolines (MonoAotCompile *acfg)
6693 char symbol [MAX_SYMBOL_SIZE];
6694 char end_symbol [MAX_SYMBOL_SIZE];
6695 int i, tramp_got_offset;
6697 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6701 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6704 g_assert (acfg->image->assembly);
6706 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6707 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6708 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6709 MonoTrampInfo *info;
6712 * Emit the generic trampolines.
6714 * We could save some code by treating the generic trampolines as a wrapper
6715 * method, but that approach has its own complexities, so we choose the simpler
6718 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6719 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6720 #ifdef DISABLE_REMOTING
6721 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6724 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6725 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6728 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6729 emit_trampoline (acfg, acfg->got_offset, info);
6732 /* Emit the exception related code pieces */
6733 mono_arch_get_restore_context (&info, TRUE);
6734 emit_trampoline (acfg, acfg->got_offset, info);
6735 mono_arch_get_call_filter (&info, TRUE);
6736 emit_trampoline (acfg, acfg->got_offset, info);
6737 mono_arch_get_throw_exception (&info, TRUE);
6738 emit_trampoline (acfg, acfg->got_offset, info);
6739 mono_arch_get_rethrow_exception (&info, TRUE);
6740 emit_trampoline (acfg, acfg->got_offset, info);
6741 mono_arch_get_throw_corlib_exception (&info, TRUE);
6742 emit_trampoline (acfg, acfg->got_offset, info);
6744 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6745 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6746 emit_trampoline (acfg, acfg->got_offset, info);
6747 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6748 emit_trampoline (acfg, acfg->got_offset, info);
6751 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6752 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6754 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6756 /* Create a separate out trampoline for more information in stack traces */
6757 info->name = g_strdup ("gsharedvt_out_trampoline");
6758 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6762 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6764 GSList *l = mono_arch_get_trampolines (TRUE);
6767 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6769 emit_trampoline (acfg, acfg->got_offset, info);
6775 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6778 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6779 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6780 emit_trampoline (acfg, acfg->got_offset, info);
6783 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6784 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6785 emit_trampoline (acfg, acfg->got_offset, info);
6789 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6790 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6791 emit_trampoline (acfg, acfg->got_offset, info);
6797 /* delegate_invoke_impl trampolines */
6798 l = mono_arch_get_delegate_invoke_impls ();
6800 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6802 emit_trampoline (acfg, acfg->got_offset, info);
6807 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6808 mono_arch_create_handler_block_trampoline (&info, TRUE);
6809 emit_trampoline (acfg, acfg->got_offset, info);
6812 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6814 /* Emit trampolines which are numerous */
6817 * These include the following:
6818 * - specific trampolines
6819 * - static rgctx invoke trampolines
6821 * These trampolines have the same code, they are parameterized by GOT
6823 * They are defined in this file, in the arch_... routines instead of
6824 * in tramp-<ARCH>.c, since it is easier to do it this way.
6828 * When running in aot-only mode, we can't create specific trampolines at
6829 * runtime, so we create a few, and save them in the AOT file.
6830 * Normal trampolines embed their argument as a literal inside the
6831 * trampoline code, we can't do that here, so instead we embed an offset
6832 * which needs to be added to the trampoline address to get the address of
6833 * the GOT slot which contains the argument value.
6834 * The generated trampolines jump to the generic trampolines using another
6835 * GOT slot, which will be setup by the AOT loader to point to the
6836 * generic trampoline code of the given type.
6840 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6844 emit_section_change (acfg, ".text", 0);
6846 tramp_got_offset = acfg->got_offset;
6848 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6850 case MONO_AOT_TRAMP_SPECIFIC:
6851 sprintf (symbol, "specific_trampolines");
6853 case MONO_AOT_TRAMP_STATIC_RGCTX:
6854 sprintf (symbol, "static_rgctx_trampolines");
6856 case MONO_AOT_TRAMP_IMT:
6857 sprintf (symbol, "imt_trampolines");
6859 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6860 sprintf (symbol, "gsharedvt_arg_trampolines");
6863 g_assert_not_reached ();
6866 sprintf (end_symbol, "%s_e", symbol);
6868 if (acfg->aot_opts.write_symbols)
6869 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6871 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6872 emit_info_symbol (acfg, symbol);
6874 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6876 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6880 case MONO_AOT_TRAMP_SPECIFIC:
6881 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6882 tramp_got_offset += 2;
6884 case MONO_AOT_TRAMP_STATIC_RGCTX:
6885 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6886 tramp_got_offset += 2;
6888 case MONO_AOT_TRAMP_IMT:
6889 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6890 tramp_got_offset += 1;
6892 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6893 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6894 tramp_got_offset += 2;
6897 g_assert_not_reached ();
6899 if (!acfg->trampoline_size [ntype]) {
6900 g_assert (tramp_size);
6901 acfg->trampoline_size [ntype] = tramp_size;
6905 emit_label (acfg, end_symbol);
6906 emit_int32 (acfg, 0);
6909 arch_emit_specific_trampoline_pages (acfg);
6911 /* Reserve some entries at the end of the GOT for our use */
6912 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6915 acfg->got_offset += acfg->num_trampoline_got_entries;
6919 str_begins_with (const char *str1, const char *str2)
6921 int len = strlen (str2);
6922 return strncmp (str1, str2, len) == 0;
6926 mono_aot_readonly_field_override (MonoClassField *field)
6929 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6930 char *p = rdv->name;
6932 len = strlen (field->parent->name_space);
6933 if (strncmp (p, field->parent->name_space, len))
6938 len = strlen (field->parent->name);
6939 if (strncmp (p, field->parent->name, len))
6944 if (strcmp (p, field->name))
6946 switch (rdv->type) {
6948 return &rdv->value.i1;
6950 return &rdv->value.i2;
6952 return &rdv->value.i4;
6961 add_readonly_value (MonoAotOptions *opts, const char *val)
6966 /* the format of val is:
6967 * namespace.typename.fieldname=type/value
6968 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6970 fval = strrchr (val, '/');
6972 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6975 tval = strrchr (val, '=');
6977 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6980 rdv = g_new0 (ReadOnlyValue, 1);
6981 rdv->name = (char *)g_malloc0 (tval - val + 1);
6982 memcpy (rdv->name, val, tval - val);
6985 if (strncmp (tval, "i1", 2) == 0) {
6986 rdv->value.i1 = atoi (fval);
6987 rdv->type = MONO_TYPE_I1;
6988 } else if (strncmp (tval, "i2", 2) == 0) {
6989 rdv->value.i2 = atoi (fval);
6990 rdv->type = MONO_TYPE_I2;
6991 } else if (strncmp (tval, "i4", 2) == 0) {
6992 rdv->value.i4 = atoi (fval);
6993 rdv->type = MONO_TYPE_I4;
6995 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6998 rdv->next = readonly_values;
6999 readonly_values = rdv;
7003 clean_path (gchar * path)
7008 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7011 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7018 wrap_path (gchar * path)
7024 // If the string contains no spaces, just return the original string.
7025 if (strstr (path, " ") == NULL)
7028 // If the string is already wrapped in quotes, return it.
7029 len = strlen (path);
7030 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7033 // If the string contains spaces, then wrap it in quotes.
7034 gchar *clean = g_strdup_printf ("\"%s\"", path);
7039 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7041 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7043 ptrdiff_t len = end-start;
7045 g_ptr_array_add (args, g_strndup (start, len));
7049 mono_aot_split_options (const char *aot_options)
7051 enum MonoAotOptionState {
7052 MONO_AOT_OPTION_STATE_DEFAULT,
7053 MONO_AOT_OPTION_STATE_STRING,
7054 MONO_AOT_OPTION_STATE_ESCAPE,
7057 GPtrArray *args = g_ptr_array_new ();
7058 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7059 gchar const *opt_start = aot_options;
7060 gboolean end_of_string = FALSE;
7063 g_return_val_if_fail (aot_options != NULL, NULL);
7065 while ((cur = *aot_options) != '\0') {
7066 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7071 // If we find a quote, then if we're in the default case then
7072 // it means we've found the start of a string, if not then it
7073 // means we've found the end of the string and should switch
7074 // back to the default case.
7076 case MONO_AOT_OPTION_STATE_DEFAULT:
7077 state = MONO_AOT_OPTION_STATE_STRING;
7079 case MONO_AOT_OPTION_STATE_STRING:
7080 state = MONO_AOT_OPTION_STATE_DEFAULT;
7082 case MONO_AOT_OPTION_STATE_ESCAPE:
7083 g_assert_not_reached ();
7088 // If we've found an escaping operator, then this means we
7089 // should not process the next character if inside a string.
7090 if (state == MONO_AOT_OPTION_STATE_STRING)
7091 state = MONO_AOT_OPTION_STATE_ESCAPE;
7094 // If we're in the default state then this means we've found
7095 // an option, store it for later processing.
7096 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7104 // If the next character is end of string, then process the last option.
7105 if (*(aot_options) == '\0') {
7106 end_of_string = TRUE;
7112 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7113 opt_start = ++aot_options;
7116 goto restart; // Check for null and continue loop
7123 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7127 args = mono_aot_split_options (aot_options ? aot_options : "");
7128 for (int i = 0; i < args->len; ++i) {
7129 const char *arg = (const char *)g_ptr_array_index (args, i);
7131 if (str_begins_with (arg, "outfile=")) {
7132 opts->outfile = g_strdup (arg + strlen ("outfile="));
7133 } else if (str_begins_with (arg, "llvm-outfile=")) {
7134 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7135 } else if (str_begins_with (arg, "temp-path=")) {
7136 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7137 } else if (str_begins_with (arg, "save-temps")) {
7138 opts->save_temps = TRUE;
7139 } else if (str_begins_with (arg, "keep-temps")) {
7140 opts->save_temps = TRUE;
7141 } else if (str_begins_with (arg, "write-symbols")) {
7142 opts->write_symbols = TRUE;
7143 } else if (str_begins_with (arg, "no-write-symbols")) {
7144 opts->write_symbols = FALSE;
7145 // Intentionally undocumented -- one-off experiment
7146 } else if (str_begins_with (arg, "metadata-only")) {
7147 opts->metadata_only = TRUE;
7148 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7149 opts->bind_to_runtime_version = TRUE;
7150 } else if (str_begins_with (arg, "full")) {
7151 opts->mode = MONO_AOT_MODE_FULL;
7152 } else if (str_begins_with (arg, "hybrid")) {
7153 opts->mode = MONO_AOT_MODE_HYBRID;
7154 } else if (str_begins_with (arg, "threads=")) {
7155 opts->nthreads = atoi (arg + strlen ("threads="));
7156 } else if (str_begins_with (arg, "static")) {
7157 opts->static_link = TRUE;
7158 opts->no_dlsym = TRUE;
7159 } else if (str_begins_with (arg, "asmonly")) {
7160 opts->asm_only = TRUE;
7161 } else if (str_begins_with (arg, "asmwriter")) {
7162 opts->asm_writer = TRUE;
7163 } else if (str_begins_with (arg, "nodebug")) {
7164 opts->nodebug = TRUE;
7165 } else if (str_begins_with (arg, "dwarfdebug")) {
7166 opts->dwarf_debug = TRUE;
7167 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7168 } else if (str_begins_with (arg, "nopagetrampolines")) {
7169 opts->use_trampolines_page = FALSE;
7170 } else if (str_begins_with (arg, "ntrampolines=")) {
7171 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7172 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7173 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7174 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7175 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7176 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7177 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7178 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7179 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7180 } else if (str_begins_with (arg, "tool-prefix=")) {
7181 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7182 } else if (str_begins_with (arg, "ld-flags=")) {
7183 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7184 } else if (str_begins_with (arg, "soft-debug")) {
7185 opts->soft_debug = TRUE;
7186 // Intentionally undocumented x2-- deprecated
7187 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7188 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7189 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7190 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7191 } else if (str_begins_with (arg, "msym-dir=")) {
7192 debug_options.no_seq_points_compact_data = FALSE;
7193 opts->gen_msym_dir = TRUE;
7194 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7195 } else if (str_begins_with (arg, "direct-pinvoke")) {
7196 opts->direct_pinvoke = TRUE;
7197 } else if (str_begins_with (arg, "direct-icalls")) {
7198 opts->direct_icalls = TRUE;
7199 } else if (str_begins_with (arg, "no-direct-calls")) {
7200 opts->no_direct_calls = TRUE;
7201 } else if (str_begins_with (arg, "print-skipped")) {
7202 opts->print_skipped_methods = TRUE;
7203 } else if (str_begins_with (arg, "stats")) {
7205 // Intentionally undocumented-- has no known function other than to debug the compiler
7206 } else if (str_begins_with (arg, "no-instances")) {
7207 opts->no_instances = TRUE;
7208 // Intentionally undocumented x4-- Used for internal debugging of compiler
7209 } else if (str_begins_with (arg, "log-generics")) {
7210 opts->log_generics = TRUE;
7211 } else if (str_begins_with (arg, "log-instances=")) {
7212 opts->log_instances = TRUE;
7213 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7214 } else if (str_begins_with (arg, "log-instances")) {
7215 opts->log_instances = TRUE;
7216 } else if (str_begins_with (arg, "internal-logfile=")) {
7217 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7218 } else if (str_begins_with (arg, "mtriple=")) {
7219 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7220 } else if (str_begins_with (arg, "llvm-path=")) {
7221 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7222 } else if (!strcmp (arg, "llvm")) {
7224 } else if (str_begins_with (arg, "readonly-value=")) {
7225 add_readonly_value (opts, arg + strlen ("readonly-value="));
7226 } else if (str_begins_with (arg, "info")) {
7227 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7229 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7230 } else if (str_begins_with (arg, "gc-maps")) {
7231 mini_gc_enable_gc_maps_for_aot ();
7232 // Intentionally undocumented: Used for internal debugging
7233 } else if (str_begins_with (arg, "dump")) {
7234 opts->dump_json = TRUE;
7235 } else if (str_begins_with (arg, "llvmonly")) {
7236 opts->mode = MONO_AOT_MODE_FULL;
7238 opts->llvm_only = TRUE;
7239 } else if (str_begins_with (arg, "data-outfile=")) {
7240 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7241 } else if (str_begins_with (arg, "profile=")) {
7242 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7243 } else if (!strcmp (arg, "profile-only")) {
7244 opts->profile_only = TRUE;
7245 } else if (!strcmp (arg, "verbose")) {
7246 opts->verbose = TRUE;
7247 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7248 printf ("Supported options for --aot:\n");
7249 printf (" asmonly\n");
7250 printf (" bind-to-runtime-version\n");
7251 printf (" bitcode\n");
7252 printf (" data-outfile=\n");
7253 printf (" direct-icalls\n");
7254 printf (" direct-pinvoke\n");
7255 printf (" dwarfdebug\n");
7257 printf (" hybrid\n");
7259 printf (" keep-temps\n");
7261 printf (" llvmonly\n");
7262 printf (" llvm-outfile=\n");
7263 printf (" llvm-path=\n");
7264 printf (" msym-dir=\n");
7265 printf (" mtriple\n");
7266 printf (" nimt-trampolines=\n");
7267 printf (" nodebug\n");
7268 printf (" no-direct-calls\n");
7269 printf (" no-write-symbols\n");
7270 printf (" nrgctx-trampolines=\n");
7271 printf (" nrgctx-fetch-trampolines=\n");
7272 printf (" ngsharedvt-trampolines=\n");
7273 printf (" ntrampolines=\n");
7274 printf (" outfile=\n");
7275 printf (" profile=\n");
7276 printf (" profile-only\n");
7277 printf (" print-skipped-methods\n");
7278 printf (" readonly-value=\n");
7279 printf (" save-temps\n");
7280 printf (" soft-debug\n");
7281 printf (" static\n");
7282 printf (" stats\n");
7283 printf (" temp-path=\n");
7284 printf (" tool-prefix=\n");
7285 printf (" threads=\n");
7286 printf (" write-symbols\n");
7287 printf (" verbose\n");
7288 printf (" help/?\n");
7291 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7295 g_free ((gpointer) arg);
7298 if (opts->use_trampolines_page) {
7299 opts->ntrampolines = 0;
7300 opts->nrgctx_trampolines = 0;
7301 opts->nimt_trampolines = 0;
7302 opts->ngsharedvt_arg_trampolines = 0;
7305 g_ptr_array_free (args, /*free_seg=*/TRUE);
7309 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7311 MonoMethod *method = (MonoMethod*)key;
7312 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7313 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7314 MonoJumpInfoToken *new_ji;
7316 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7317 new_ji->image = ji->image;
7318 new_ji->token = ji->token;
7319 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7323 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7325 if (klass->type_token)
7327 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7330 return can_encode_class (acfg, klass->element_class);
7335 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7337 if (method->wrapper_type) {
7338 switch (method->wrapper_type) {
7339 case MONO_WRAPPER_NONE:
7340 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7341 case MONO_WRAPPER_XDOMAIN_INVOKE:
7342 case MONO_WRAPPER_STFLD:
7343 case MONO_WRAPPER_LDFLD:
7344 case MONO_WRAPPER_LDFLDA:
7345 case MONO_WRAPPER_STELEMREF:
7346 case MONO_WRAPPER_PROXY_ISINST:
7347 case MONO_WRAPPER_ALLOC:
7348 case MONO_WRAPPER_REMOTING_INVOKE:
7349 case MONO_WRAPPER_UNKNOWN:
7350 case MONO_WRAPPER_WRITE_BARRIER:
7351 case MONO_WRAPPER_DELEGATE_INVOKE:
7352 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7353 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7354 case MONO_WRAPPER_SYNCHRONIZED:
7356 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7357 case MONO_WRAPPER_CASTCLASS: {
7358 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7367 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7371 if (!method->token) {
7372 /* The method is part of a constructed type like Int[,].Set (). */
7373 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7374 if (method->klass->rank)
7384 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7386 switch (patch_info->type) {
7387 case MONO_PATCH_INFO_METHOD:
7388 case MONO_PATCH_INFO_METHODCONST:
7389 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7390 MonoMethod *method = patch_info->data.method;
7392 return can_encode_method (acfg, method);
7394 case MONO_PATCH_INFO_VTABLE:
7395 case MONO_PATCH_INFO_CLASS:
7396 case MONO_PATCH_INFO_IID:
7397 case MONO_PATCH_INFO_ADJUSTED_IID:
7398 if (!can_encode_class (acfg, patch_info->data.klass)) {
7399 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7403 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7404 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7405 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7410 case MONO_PATCH_INFO_RGCTX_FETCH:
7411 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7412 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7414 if (!can_encode_method (acfg, entry->method))
7416 if (!can_encode_patch (acfg, entry->data))
7428 is_concrete_type (MonoType *t)
7433 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7435 if (t->type == MONO_TYPE_GENERICINST) {
7436 MonoGenericContext *orig_ctx;
7437 MonoGenericInst *inst;
7440 if (!MONO_TYPE_ISSTRUCT (t))
7442 klass = mono_class_from_mono_type (t);
7443 orig_ctx = &mono_class_get_generic_class (klass)->context;
7445 inst = orig_ctx->class_inst;
7447 for (i = 0; i < inst->type_argc; ++i) {
7448 arg = mini_get_underlying_type (inst->type_argv [i]);
7449 if (!is_concrete_type (arg))
7453 inst = orig_ctx->method_inst;
7455 for (i = 0; i < inst->type_argc; ++i) {
7456 arg = mini_get_underlying_type (inst->type_argv [i]);
7457 if (!is_concrete_type (arg))
7465 /* LOCKING: Assumes the loader lock is held */
7467 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7469 MonoMethod *wrapper;
7470 gboolean concrete = TRUE;
7471 gboolean add_in = gsharedvt_in;
7472 gboolean add_out = gsharedvt_out;
7474 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7476 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7479 if (!add_in && !add_out)
7482 if (mini_is_gsharedvt_variable_signature (sig))
7486 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7488 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7490 if (!sig->has_type_parameters) {
7491 //printf ("%s\n", mono_signature_full_name (sig));
7494 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7495 add_extra_method (acfg, wrapper);
7497 if (gsharedvt_out) {
7498 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7499 add_extra_method (acfg, wrapper);
7502 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7503 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7506 //printf ("%s\n", mono_signature_full_name (sig));
7508 copy->ret = mini_get_underlying_type (sig->ret);
7509 if (!is_concrete_type (copy->ret))
7511 for (i = 0; i < sig->param_count; ++i) {
7512 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7513 if (!is_concrete_type (copy->params [i]))
7517 copy->has_type_parameters = 0;
7520 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7521 add_extra_method (acfg, wrapper);
7524 if (gsharedvt_out) {
7525 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7526 add_extra_method (acfg, wrapper);
7529 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7537 * AOT compile a given method.
7538 * This function might be called by multiple threads, so it must be thread-safe.
7541 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7544 MonoJumpInfo *patch_info;
7547 MonoMethod *wrapped;
7551 if (acfg->aot_opts.metadata_only)
7554 mono_acfg_lock (acfg);
7555 index = get_method_index (acfg, method);
7556 mono_acfg_unlock (acfg);
7558 /* fixme: maybe we can also precompile wrapper methods */
7559 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7560 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7561 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7562 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7566 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7569 wrapped = mono_marshal_method_from_wrapper (method);
7570 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7571 // FIXME: The wrapper should be generic too, but it is not
7574 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7577 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7580 InterlockedIncrement (&acfg->stats.mcount);
7583 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7584 InterlockedIncrement (&acfg->stats.genericcount);
7589 //acfg->aot_opts.print_skipped_methods = TRUE;
7592 * Since these methods are the only ones which are compiled with
7593 * AOT support, and they are not used by runtime startup/shutdown code,
7594 * the runtime will not see AOT methods during AOT compilation,so it
7595 * does not need to support them by creating a fake GOT etc.
7597 flags = JIT_FLAG_AOT;
7598 if (mono_aot_mode_is_full (&acfg->aot_opts))
7599 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7601 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7602 if (acfg->aot_opts.llvm_only)
7603 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7604 if (acfg->aot_opts.no_direct_calls)
7605 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7606 if (acfg->aot_opts.direct_pinvoke)
7607 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7609 jit_timer = mono_time_track_start ();
7610 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7611 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7613 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7614 if (acfg->aot_opts.print_skipped_methods)
7615 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7616 InterlockedIncrement (&acfg->stats.genericcount);
7619 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7620 /* Some instances cannot be JITted due to constraints etc. */
7621 if (!method->is_inflated)
7622 report_loader_error (acfg, &cfg->error, "Unable to compile method '%s' due to: '%s'.\n", mono_method_get_full_name (method), mono_error_get_message (&cfg->error));
7623 /* Let the exception happen at runtime */
7627 if (cfg->disable_aot) {
7628 if (acfg->aot_opts.print_skipped_methods)
7629 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7630 InterlockedIncrement (&acfg->stats.ocount);
7633 cfg->method_index = index;
7635 /* Nullify patches which need no aot processing */
7636 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7637 switch (patch_info->type) {
7638 case MONO_PATCH_INFO_LABEL:
7639 case MONO_PATCH_INFO_BB:
7640 patch_info->type = MONO_PATCH_INFO_NONE;
7647 /* Collect method->token associations from the cfg */
7648 mono_acfg_lock (acfg);
7649 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7650 mono_acfg_unlock (acfg);
7651 g_hash_table_destroy (cfg->token_info_hash);
7652 cfg->token_info_hash = NULL;
7655 * Check for absolute addresses.
7658 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7659 switch (patch_info->type) {
7660 case MONO_PATCH_INFO_ABS:
7661 /* unable to handle this */
7670 if (acfg->aot_opts.print_skipped_methods)
7671 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7672 InterlockedIncrement (&acfg->stats.abscount);
7676 /* Lock for the rest of the code */
7677 mono_acfg_lock (acfg);
7680 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7681 else if (cfg->gshared)
7682 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7683 else if (cfg->method->wrapper_type)
7684 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7686 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7689 * Check for methods/klasses we can't encode.
7692 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7693 if (!can_encode_patch (acfg, patch_info))
7698 if (acfg->aot_opts.print_skipped_methods)
7699 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7700 acfg->stats.ocount++;
7701 mono_acfg_unlock (acfg);
7705 if (!cfg->compile_llvm)
7706 acfg->has_jitted_code = TRUE;
7708 if (method->is_inflated && acfg->aot_opts.log_instances) {
7709 if (acfg->instances_logfile)
7710 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7712 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7715 /* Adds generic instances referenced by this method */
7717 * The depth is used to avoid infinite loops when generic virtual recursion is
7720 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7721 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7722 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7723 switch (patch_info->type) {
7724 case MONO_PATCH_INFO_RGCTX_FETCH:
7725 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7726 case MONO_PATCH_INFO_METHOD: {
7727 MonoMethod *m = NULL;
7729 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7730 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7732 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7733 m = e->data->data.method;
7735 m = patch_info->data.method;
7740 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7741 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7742 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7743 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7744 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7745 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7746 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7748 add_extra_method_with_depth (acfg, m, depth + 1);
7749 add_types_from_method_header (acfg, m);
7752 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7754 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7755 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7757 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7758 add_extra_method_with_depth (acfg, m, depth + 1);
7762 case MONO_PATCH_INFO_VTABLE: {
7763 MonoClass *klass = patch_info->data.klass;
7765 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7766 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7769 case MONO_PATCH_INFO_SFLDA: {
7770 MonoClass *klass = patch_info->data.field->parent;
7772 /* The .cctor needs to run at runtime. */
7773 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))
7774 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7783 /* Determine whenever the method has GOT slots */
7784 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7785 switch (patch_info->type) {
7786 case MONO_PATCH_INFO_GOT_OFFSET:
7787 case MONO_PATCH_INFO_NONE:
7788 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7789 case MONO_PATCH_INFO_GC_NURSERY_START:
7790 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7792 case MONO_PATCH_INFO_IMAGE:
7793 /* The assembly is stored in GOT slot 0 */
7794 if (patch_info->data.image != acfg->image)
7795 cfg->has_got_slots = TRUE;
7798 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7799 cfg->has_got_slots = TRUE;
7804 if (!cfg->has_got_slots)
7805 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7807 /* Add gsharedvt wrappers for signatures used by the method */
7808 if (acfg->aot_opts.llvm_only) {
7811 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7812 /* These only need out wrappers */
7813 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7815 for (l = cfg->signatures; l; l = l->next) {
7816 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7818 /* These only need in wrappers */
7819 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7824 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7826 /* Make a copy of the patch info which is in the mempool */
7828 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7830 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7831 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7834 patches = new_patch_info;
7836 patches_end->next = new_patch_info;
7837 patches_end = new_patch_info;
7839 cfg->patch_info = patches;
7841 /* Make a copy of the unwind info */
7843 GSList *l, *unwind_ops;
7847 for (l = cfg->unwind_ops; l; l = l->next) {
7848 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7849 memcpy (op, l->data, sizeof (MonoUnwindOp));
7850 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7852 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7854 /* Make a copy of the argument/local info */
7857 MonoInst **args, **locals;
7858 MonoMethodSignature *sig;
7859 MonoMethodHeader *header;
7862 sig = mono_method_signature (method);
7863 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7864 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7865 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7866 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7870 header = mono_method_get_header_checked (method, &error);
7871 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7872 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7873 for (i = 0; i < header->num_locals; ++i) {
7874 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7875 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7877 mono_metadata_free_mh (header);
7878 cfg->locals = locals;
7881 /* Free some fields used by cfg to conserve memory */
7882 mono_empty_compile (cfg);
7884 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7886 while (index >= acfg->cfgs_size) {
7887 MonoCompile **new_cfgs;
7890 new_size = acfg->cfgs_size * 2;
7891 new_cfgs = g_new0 (MonoCompile*, new_size);
7892 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7893 g_free (acfg->cfgs);
7894 acfg->cfgs = new_cfgs;
7895 acfg->cfgs_size = new_size;
7897 acfg->cfgs [index] = cfg;
7899 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7901 mono_update_jit_stats (cfg);
7904 if (cfg->orig_method->wrapper_type)
7905 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7908 mono_acfg_unlock (acfg);
7910 InterlockedIncrement (&acfg->stats.ccount);
7913 static mono_thread_start_return_t WINAPI
7914 compile_thread_main (gpointer user_data)
7916 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7917 GPtrArray *methods = ((GPtrArray **)user_data) [1];
7921 MonoInternalThread *internal = mono_thread_internal_current ();
7922 mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "AOT compiler"), TRUE, FALSE, &error);
7923 mono_error_assert_ok (&error);
7925 for (i = 0; i < methods->len; ++i)
7926 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7931 /* Used by the LLVM backend */
7933 mono_aot_get_got_offset (MonoJumpInfo *ji)
7935 return get_got_offset (llvm_acfg, TRUE, ji);
7939 * mono_aot_is_shared_got_offset:
7941 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7942 * when the AOT image is loaded.
7945 mono_aot_is_shared_got_offset (int offset)
7947 return offset < llvm_acfg->nshared_got_entries;
7951 mono_aot_get_method_name (MonoCompile *cfg)
7953 if (llvm_acfg->aot_opts.static_link)
7954 /* Include the assembly name too to avoid duplicate symbol errors */
7955 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7957 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7961 * mono_aot_is_linkonce_method:
7963 * Return whenever METHOD should be emitted with linkonce linkage,
7964 * eliminating duplicate copies when compiling in static mode.
7967 mono_aot_is_linkonce_method (MonoMethod *method)
7973 // FIXME: Add more cases
7974 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7976 info = mono_marshal_get_wrapper_info (method);
7977 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7984 append_mangled_type (GString *s, MonoType *t)
7987 g_string_append_printf (s, "b");
7989 case MONO_TYPE_VOID:
7990 g_string_append_printf (s, "void_");
7993 g_string_append_printf (s, "i1");
7996 g_string_append_printf (s, "u1");
7999 g_string_append_printf (s, "i2");
8002 g_string_append_printf (s, "u2");
8005 g_string_append_printf (s, "i4");
8008 g_string_append_printf (s, "u4");
8011 g_string_append_printf (s, "i8");
8014 g_string_append_printf (s, "u8");
8017 g_string_append_printf (s, "ii");
8020 g_string_append_printf (s, "ui");
8023 g_string_append_printf (s, "fl");
8026 g_string_append_printf (s, "do");
8029 char *fullname = mono_type_full_name (t);
8035 * Have to create a mangled name which is:
8039 temp = g_string_new ("");
8040 len = strlen (fullname);
8041 for (i = 0; i < len; ++i) {
8042 char c = fullname [i];
8044 g_string_append_c (temp, c);
8045 } else if (c == '_') {
8046 g_string_append_c (temp, '_');
8047 g_string_append_c (temp, '_');
8049 g_string_append_c (temp, '_');
8050 g_string_append_printf (temp, "%x", (int)c);
8053 temps = g_string_free (temp, FALSE);
8054 /* Include the length to avoid different length type names aliasing each other */
8055 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8064 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8069 supported = append_mangled_type (s, sig->ret);
8073 g_string_append_printf (s, "this_");
8074 for (i = 0; i < sig->param_count; ++i) {
8075 supported = append_mangled_type (s, sig->params [i]);
8084 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8088 switch (wrapper_type) {
8089 case MONO_WRAPPER_REMOTING_INVOKE:
8090 label = "remoting_invoke";
8092 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8093 label = "remoting_invoke_check";
8095 case MONO_WRAPPER_XDOMAIN_INVOKE:
8096 label = "remoting_invoke_xdomain";
8098 case MONO_WRAPPER_PROXY_ISINST:
8099 label = "proxy_isinst";
8101 case MONO_WRAPPER_LDFLD:
8104 case MONO_WRAPPER_LDFLDA:
8107 case MONO_WRAPPER_STFLD:
8110 case MONO_WRAPPER_ALLOC:
8113 case MONO_WRAPPER_WRITE_BARRIER:
8114 label = "write_barrier";
8116 case MONO_WRAPPER_STELEMREF:
8117 label = "stelemref";
8119 case MONO_WRAPPER_UNKNOWN:
8122 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8123 label = "man2native";
8125 case MONO_WRAPPER_SYNCHRONIZED:
8128 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8131 case MONO_WRAPPER_CASTCLASS:
8132 label = "castclass";
8134 case MONO_WRAPPER_RUNTIME_INVOKE:
8135 label = "run_invoke";
8137 case MONO_WRAPPER_DELEGATE_INVOKE:
8140 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8141 label = "del_beg_inv";
8143 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8144 label = "del_end_inv";
8146 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8147 label = "native2man";
8150 g_assert_not_reached ();
8153 g_string_append_printf (s, "%s_", label);
8157 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8163 case WRAPPER_SUBTYPE_NONE:
8165 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8166 label = "elem_addr";
8168 case WRAPPER_SUBTYPE_STRING_CTOR:
8171 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8172 label = "virt_stelem";
8174 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8175 label = "fast_mon_enter";
8177 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8178 label = "fast_mon_enter_4";
8180 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8181 label = "fast_monitor_exit";
8183 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8184 label = "ptr2struct";
8186 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8187 label = "struct2ptr";
8189 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8190 label = "castclass_w_cache";
8192 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8193 label = "isinst_w_cache";
8195 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8196 label = "run_inv_norm";
8198 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8199 label = "run_inv_dyn";
8201 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8202 label = "run_inv_dir";
8204 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8205 label = "run_inv_vir";
8207 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8210 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8211 label = "native_func_aot";
8213 case WRAPPER_SUBTYPE_PINVOKE:
8216 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8217 label = "synch_inner";
8219 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8220 label = "gshared_in";
8222 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8223 label = "gshared_out";
8225 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8226 label = "array_acc";
8228 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8229 label = "generic_arry_help";
8231 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8232 label = "del_inv_virt";
8234 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8235 label = "del_inv_bound";
8237 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8238 label = "gsharedvt_in_sig";
8240 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8241 label = "gsharedvt_out_sig";
8244 g_assert_not_reached ();
8247 g_string_append_printf (s, "%s_", label);
8251 sanitize_mangled_string (const char *input)
8253 GString *s = g_string_new ("");
8255 for (int i=0; input [i] != '\0'; i++) {
8259 g_string_append (s, "_dot_");
8262 g_string_append (s, "_");
8265 g_string_append (s, "_bt_");
8268 g_string_append (s, "_le_");
8271 g_string_append (s, "_gt_");
8274 g_string_append (s, "_sl_");
8277 g_string_append (s, "_lbrack_");
8280 g_string_append (s, "_rbrack_");
8283 g_string_append (s, "_lparen_");
8286 g_string_append (s, "_dash_");
8289 g_string_append (s, "_rparen_");
8292 g_string_append (s, "_comma_");
8295 g_string_append_c (s, c);
8299 return g_string_free (s, FALSE);
8303 append_mangled_klass (GString *s, MonoClass *klass)
8305 char *klass_desc = mono_class_full_name (klass);
8306 g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8307 g_free (klass_desc);
8314 append_mangled_method (GString *s, MonoMethod *method);
8317 append_mangled_wrapper (GString *s, MonoMethod *method)
8319 gboolean success = TRUE;
8320 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8321 g_string_append_printf (s, "wrapper_");
8323 append_mangled_wrapper_type (s, method->wrapper_type);
8325 switch (method->wrapper_type) {
8326 case MONO_WRAPPER_REMOTING_INVOKE:
8327 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8328 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8329 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8331 success = success && append_mangled_method (s, m);
8334 case MONO_WRAPPER_PROXY_ISINST:
8335 case MONO_WRAPPER_LDFLD:
8336 case MONO_WRAPPER_LDFLDA:
8337 case MONO_WRAPPER_STFLD: {
8339 success = success && append_mangled_klass (s, info->d.proxy.klass);
8342 case MONO_WRAPPER_ALLOC: {
8343 /* The GC name is saved once in MonoAotFileInfo */
8344 g_assert (info->d.alloc.alloc_type != -1);
8345 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8347 g_string_append_printf (s, "%s_", method->name);
8350 case MONO_WRAPPER_WRITE_BARRIER: {
8353 case MONO_WRAPPER_STELEMREF: {
8354 append_mangled_wrapper_subtype (s, info->subtype);
8355 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8356 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8359 case MONO_WRAPPER_UNKNOWN: {
8360 append_mangled_wrapper_subtype (s, info->subtype);
8361 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8362 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8363 success = success && append_mangled_klass (s, method->klass);
8364 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8365 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8366 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8367 success = success && append_mangled_method (s, info->d.array_accessor.method);
8368 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8369 append_mangled_signature (s, info->d.gsharedvt.sig);
8370 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8371 append_mangled_signature (s, info->d.gsharedvt.sig);
8374 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8375 append_mangled_wrapper_subtype (s, info->subtype);
8376 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8377 g_string_append_printf (s, "%s", method->name);
8378 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8379 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8381 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8382 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8386 case MONO_WRAPPER_SYNCHRONIZED: {
8389 m = mono_marshal_method_from_wrapper (method);
8391 g_assert (m != method);
8392 success = success && append_mangled_method (s, m);
8395 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8396 append_mangled_wrapper_subtype (s, info->subtype);
8398 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8399 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8400 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8401 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8402 success = success && append_mangled_method (s, info->d.string_ctor.method);
8404 g_assert_not_reached ();
8408 case MONO_WRAPPER_CASTCLASS: {
8409 append_mangled_wrapper_subtype (s, info->subtype);
8412 case MONO_WRAPPER_RUNTIME_INVOKE: {
8413 append_mangled_wrapper_subtype (s, info->subtype);
8414 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8415 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8416 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8417 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8420 case MONO_WRAPPER_DELEGATE_INVOKE:
8421 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8422 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8423 if (method->is_inflated) {
8424 /* These wrappers are identified by their class */
8425 g_string_append_printf (s, "i_");
8426 success = success && append_mangled_klass (s, method->klass);
8428 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8430 g_string_append_printf (s, "u_");
8431 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8432 append_mangled_wrapper_subtype (s, info->subtype);
8433 g_string_append_printf (s, "u_sigstart");
8437 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8439 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8440 success = success && append_mangled_klass (s, method->klass);
8444 g_assert_not_reached ();
8446 return success && append_mangled_signature (s, mono_method_signature (method));
8450 append_mangled_context (GString *str, MonoGenericContext *context)
8452 GString *res = g_string_new ("");
8454 g_string_append_printf (res, "gens_");
8455 g_string_append (res, "00");
8457 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8458 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8461 if (context->class_inst)
8462 mono_ginst_get_desc (res, context->class_inst);
8463 if (context->method_inst) {
8464 if (context->class_inst)
8465 g_string_append (res, "11");
8466 mono_ginst_get_desc (res, context->method_inst);
8468 g_string_append_printf (str, "gens_%s", res->str);
8472 append_mangled_method (GString *s, MonoMethod *method)
8474 if (method->wrapper_type)
8475 return append_mangled_wrapper (s, method);
8477 g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8479 if (method->is_inflated) {
8480 g_string_append_printf (s, "inflated_");
8481 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8482 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8484 append_mangled_context (s, &imethod->context);
8485 g_string_append_printf (s, "_declared_by_");
8486 append_mangled_method (s, imethod->declaring);
8487 } else if (method->is_generic) {
8488 g_string_append_printf (s, "generic_");
8489 append_mangled_klass (s, method->klass);
8490 g_string_append_printf (s, "_%s_", method->name);
8492 MonoGenericContainer *container = mono_method_get_generic_container (method);
8493 g_string_append_printf (s, "_%s");
8494 append_mangled_context (s, &container->context);
8496 return append_mangled_signature (s, mono_method_signature (method));
8498 g_string_append_printf (s, "_");
8499 append_mangled_klass (s, method->klass);
8500 g_string_append_printf (s, "_%s_", method->name);
8501 if (!append_mangled_signature (s, mono_method_signature (method))) {
8502 g_string_free (s, TRUE);
8511 * mono_aot_get_mangled_method_name:
8513 * Return a unique mangled name for METHOD, or NULL.
8516 mono_aot_get_mangled_method_name (MonoMethod *method)
8518 GString *s = g_string_new ("aot_");
8519 if (!append_mangled_method (s, method)) {
8520 g_string_free (s, TRUE);
8523 char *out = g_string_free (s, FALSE);
8524 // Scrub method and class names
8525 char *cleaned = sanitize_mangled_string (out);
8532 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8534 return is_direct_callable (llvm_acfg, NULL, patch_info);
8538 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8540 MonoPltEntry *plt_entry;
8542 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8543 plt_entry->llvm_used = FALSE;
8547 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8549 const char *sym = NULL;
8551 if (llvm_acfg->aot_opts.direct_icalls) {
8552 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8553 /* Call to a C function implementing a jit icall */
8554 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8555 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8556 MonoMethod *method = (MonoMethod *)data;
8557 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8558 sym = mono_lookup_icall_symbol (method);
8559 else if (llvm_acfg->aot_opts.direct_pinvoke)
8560 sym = get_pinvoke_import (llvm_acfg, method);
8563 return g_strdup (sym);
8569 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8571 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8572 MonoPltEntry *plt_entry;
8573 const char *sym = NULL;
8576 ji->data.target = data;
8578 if (!can_encode_patch (llvm_acfg, ji))
8581 if (llvm_acfg->aot_opts.direct_icalls) {
8582 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8583 /* Call to a C function implementing a jit icall */
8584 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8585 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8586 MonoMethod *method = (MonoMethod *)data;
8587 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8588 sym = mono_lookup_icall_symbol (method);
8591 return g_strdup (sym);
8594 plt_entry = get_plt_entry (llvm_acfg, ji);
8595 plt_entry->llvm_used = TRUE;
8597 #if defined(TARGET_MACH)
8598 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8600 return g_strdup_printf (plt_entry->llvm_symbol);
8605 mono_aot_get_method_index (MonoMethod *method)
8607 g_assert (llvm_acfg);
8608 return get_method_index (llvm_acfg, method);
8612 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8616 mono_acfg_lock (llvm_acfg);
8617 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8618 mono_acfg_unlock (llvm_acfg);
8624 execute_system (const char * command)
8628 #if defined(HOST_WIN32) && defined(HAVE_SYSTEM)
8629 // We need an extra set of quotes around the whole command to properly handle commands
8630 // with spaces since internally the command is called through "cmd /c.
8631 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8633 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8634 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8635 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8636 status = _wsystem (wstr);
8639 g_free (quoted_command);
8640 #elif defined (HAVE_SYSTEM)
8641 status = system (command);
8643 g_assert_not_reached ();
8654 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8658 emit_llvm_file (MonoAotCompile *acfg)
8660 char *command, *opts, *tempbc, *optbc, *output_fname;
8662 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8663 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8664 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8666 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8667 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8670 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8673 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8674 * a lot of time, and doesn't seem to save much space.
8675 * The following optimizations cannot be enabled:
8677 * - 'jump-threading' changes our blockaddress references to int constants.
8678 * - 'basiccg' fails because it contains:
8679 * if (CS && !isa<IntrinsicInst>(II)) {
8680 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8681 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8682 * The opt list below was produced by taking the output of:
8683 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8684 * then removing tailcallelim + the global opts.
8685 * strip-dead-prototypes deletes unused intrinsics definitions.
8687 /* The dse pass is disabled because of #13734 and #17616 */
8689 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8690 * // If we have no DataLayout information around, then the size of the store
8691 * // is inferrable from the pointee type. If they are the same type, then
8692 * // we know that the store is safe.
8693 * if (AA.getDataLayout() == 0 &&
8694 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8695 * return OverwriteComplete;
8696 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8698 if (acfg->aot_opts.llvm_only)
8699 // FIXME: This doesn't work yet
8700 opts = g_strdup ("");
8702 #if LLVM_API_VERSION > 100
8703 opts = g_strdup ("-O2 -disable-tail-calls");
8705 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");
8707 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8708 aot_printf (acfg, "Executing opt: %s\n", command);
8709 if (execute_system (command) != 0)
8713 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8714 /* Nothing else to do */
8717 if (acfg->aot_opts.llvm_only) {
8718 /* Use the stock clang from xcode */
8720 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);
8722 aot_printf (acfg, "Executing clang: %s\n", command);
8723 if (execute_system (command) != 0)
8728 if (!acfg->llc_args)
8729 acfg->llc_args = g_string_new ("");
8731 /* Verbose asm slows down llc greatly */
8732 g_string_append (acfg->llc_args, " -asm-verbose=false");
8734 if (acfg->aot_opts.mtriple)
8735 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8737 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8739 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8741 #if LLVM_API_VERSION > 100
8742 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8745 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8746 /* ios requires PIC code now */
8747 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8749 if (llvm_acfg->aot_opts.static_link)
8750 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8752 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8755 if (acfg->llvm_owriter) {
8756 /* Emit an object file directly */
8757 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8758 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8760 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8762 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8763 g_free (output_fname);
8765 aot_printf (acfg, "Executing llc: %s\n", command);
8767 if (execute_system (command) != 0)
8774 emit_code (MonoAotCompile *acfg)
8776 int oindex, i, prev_index;
8777 gboolean saved_unbox_info = FALSE;
8778 char symbol [MAX_SYMBOL_SIZE];
8780 if (acfg->aot_opts.llvm_only)
8783 #if defined(TARGET_POWERPC64)
8784 sprintf (symbol, ".Lgot_addr");
8785 emit_section_change (acfg, ".text", 0);
8786 emit_alignment (acfg, 8);
8787 emit_label (acfg, symbol);
8788 emit_pointer (acfg, acfg->got_symbol);
8792 * This global symbol is used to compute the address of each method using the
8793 * code_offsets array. It is also used to compute the memory ranges occupied by
8794 * AOT code, so it must be equal to the address of the first emitted method.
8796 emit_section_change (acfg, ".text", 0);
8797 emit_alignment_code (acfg, 8);
8798 emit_info_symbol (acfg, "jit_code_start");
8801 * Emit some padding so the local symbol for the first method doesn't have the
8802 * same address as 'methods'.
8804 emit_padding (acfg, 16);
8806 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8810 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8812 cfg = acfg->cfgs [i];
8817 method = cfg->orig_method;
8819 /* Emit unbox trampoline */
8820 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8821 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8823 emit_section_change (acfg, ".text", 0);
8825 if (acfg->thumb_mixed && cfg->compile_llvm) {
8826 emit_set_thumb_mode (acfg);
8827 fprintf (acfg->fp, "\n.thumb_func\n");
8830 emit_label (acfg, symbol);
8832 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8834 if (acfg->thumb_mixed && cfg->compile_llvm)
8835 emit_set_arm_mode (acfg);
8837 if (!saved_unbox_info) {
8838 char user_symbol [128];
8840 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8842 emit_label (acfg, "ut_end");
8844 unwind_ops = mono_unwind_get_cie_program ();
8845 save_unwind_info (acfg, user_symbol, unwind_ops);
8846 mono_free_unwind_info (unwind_ops);
8848 /* Save the unbox trampoline size */
8849 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8851 saved_unbox_info = TRUE;
8855 if (cfg->compile_llvm)
8856 acfg->stats.llvm_count ++;
8858 emit_method_code (acfg, cfg);
8861 emit_section_change (acfg, ".text", 0);
8862 emit_alignment_code (acfg, 8);
8863 emit_info_symbol (acfg, "jit_code_end");
8865 /* To distinguish it from the next symbol */
8866 emit_padding (acfg, 4);
8869 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8870 * from optimizing them away, since it doesn't see that code_offsets references them.
8871 * JITted methods don't need this since they are referenced using assembler local
8873 * FIXME: This is why write-symbols doesn't work on OSX ?
8875 if (acfg->llvm && acfg->need_no_dead_strip) {
8876 fprintf (acfg->fp, "\n");
8877 for (i = 0; i < acfg->nmethods; ++i) {
8878 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8879 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8884 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8885 * This is PIE code, and the linker can update it if needed.
8888 sprintf (symbol, "method_addresses");
8889 emit_section_change (acfg, ".text", 1);
8890 emit_alignment_code (acfg, 8);
8891 emit_info_symbol (acfg, symbol);
8892 if (acfg->aot_opts.write_symbols)
8893 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8894 emit_unset_mode (acfg);
8895 if (acfg->need_no_dead_strip)
8896 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8898 for (i = 0; i < acfg->nmethods; ++i) {
8899 #ifdef MONO_ARCH_AOT_SUPPORTED
8902 if (acfg->cfgs [i]) {
8903 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8905 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8910 sprintf (symbol, "method_addresses_end");
8911 emit_label (acfg, symbol);
8914 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8915 sprintf (symbol, "unbox_trampolines");
8916 emit_section_change (acfg, RODATA_SECT, 0);
8917 emit_alignment (acfg, 8);
8918 emit_info_symbol (acfg, symbol);
8921 for (i = 0; i < acfg->nmethods; ++i) {
8926 cfg = acfg->cfgs [i];
8930 method = cfg->orig_method;
8932 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8933 index = get_method_index (acfg, method);
8935 emit_int32 (acfg, index);
8936 /* Make sure the table is sorted by index */
8937 g_assert (index > prev_index);
8941 sprintf (symbol, "unbox_trampolines_end");
8942 emit_info_symbol (acfg, symbol);
8943 emit_int32 (acfg, 0);
8945 /* Emit a separate table with the trampoline addresses/offsets */
8946 sprintf (symbol, "unbox_trampoline_addresses");
8947 emit_section_change (acfg, ".text", 0);
8948 emit_alignment_code (acfg, 8);
8949 emit_info_symbol (acfg, symbol);
8951 for (i = 0; i < acfg->nmethods; ++i) {
8956 cfg = acfg->cfgs [i];
8960 method = cfg->orig_method;
8962 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8963 #ifdef MONO_ARCH_AOT_SUPPORTED
8966 index = get_method_index (acfg, method);
8967 sprintf (symbol, "ut_%d", index);
8969 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8973 emit_int32 (acfg, 0);
8977 emit_info (MonoAotCompile *acfg)
8982 offsets = g_new0 (gint32, acfg->nmethods);
8984 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8985 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8987 if (acfg->cfgs [i]) {
8988 emit_method_info (acfg, acfg->cfgs [i]);
8989 offsets [i] = acfg->cfgs [i]->method_info_offset;
8995 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9000 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9002 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9003 #define mix(a,b,c) { \
9004 a -= c; a ^= rot(c, 4); c += b; \
9005 b -= a; b ^= rot(a, 6); a += c; \
9006 c -= b; c ^= rot(b, 8); b += a; \
9007 a -= c; a ^= rot(c,16); c += b; \
9008 b -= a; b ^= rot(a,19); a += c; \
9009 c -= b; c ^= rot(b, 4); b += a; \
9011 #define final(a,b,c) { \
9012 c ^= b; c -= rot(b,14); \
9013 a ^= c; a -= rot(c,11); \
9014 b ^= a; b -= rot(a,25); \
9015 c ^= b; c -= rot(b,16); \
9016 a ^= c; a -= rot(c,4); \
9017 b ^= a; b -= rot(a,14); \
9018 c ^= b; c -= rot(b,24); \
9022 mono_aot_type_hash (MonoType *t1)
9024 guint hash = t1->type;
9026 hash |= t1->byref << 6; /* do not collide with t1->type values */
9028 case MONO_TYPE_VALUETYPE:
9029 case MONO_TYPE_CLASS:
9030 case MONO_TYPE_SZARRAY:
9031 /* check if the distribution is good enough */
9032 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9034 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9035 case MONO_TYPE_ARRAY:
9036 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9037 case MONO_TYPE_GENERICINST:
9038 return ((hash << 5) - hash) ^ 0;
9045 * mono_aot_method_hash:
9047 * Return a hash code for methods which only depends on metadata.
9050 mono_aot_method_hash (MonoMethod *method)
9052 MonoMethodSignature *sig;
9056 guint32 *hashes_start, *hashes;
9058 MonoGenericInst *class_ginst = NULL;
9059 MonoGenericInst *ginst = NULL;
9061 /* Similar to the hash in mono_method_get_imt_slot () */
9063 sig = mono_method_signature (method);
9065 if (mono_class_is_ginst (method->klass))
9066 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9067 if (method->is_inflated)
9068 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9070 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9071 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9072 hashes = hashes_start;
9074 /* Some wrappers are assigned to random classes */
9075 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9076 klass = method->klass;
9078 klass = mono_defaults.object_class;
9080 if (!method->wrapper_type) {
9083 if (mono_class_is_ginst (klass))
9084 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9086 full_name = mono_type_full_name (&klass->byval_arg);
9088 hashes [0] = mono_metadata_str_hash (full_name);
9092 hashes [0] = mono_metadata_str_hash (klass->name);
9093 hashes [1] = mono_metadata_str_hash (klass->name_space);
9095 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9096 /* The method name includes a stringified pointer */
9099 hashes [2] = mono_metadata_str_hash (method->name);
9100 hashes [3] = method->wrapper_type;
9101 hashes [4] = mono_aot_type_hash (sig->ret);
9103 for (i = 0; i < sig->param_count; i++) {
9104 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9107 for (i = 0; i < class_ginst->type_argc; ++i)
9108 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9111 for (i = 0; i < ginst->type_argc; ++i)
9112 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9114 g_assert (hindex == hashes_count);
9116 /* Setup internal state */
9117 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9119 /* Handle most of the hashes */
9120 while (hashes_count > 3) {
9129 /* Handle the last 3 hashes (all the case statements fall through) */
9130 switch (hashes_count) {
9131 case 3 : c += hashes [2];
9132 case 2 : b += hashes [1];
9133 case 1 : a += hashes [0];
9135 case 0: /* nothing left to add */
9139 g_free (hashes_start);
9148 * mono_aot_get_array_helper_from_wrapper;
9150 * Get the helper method in Array called by an array wrapper method.
9153 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9157 MonoGenericContext ctx;
9158 MonoType *args [16];
9159 char *mname, *iname, *s, *s2, *helper_name = NULL;
9161 prefix = "System.Collections.Generic";
9162 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9163 s2 = strstr (s, "`1.");
9169 //printf ("X: %s %s\n", iname, mname);
9171 if (!strcmp (iname, "IList"))
9172 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9174 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9175 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9177 g_free (helper_name);
9180 if (m->is_generic) {
9182 memset (&ctx, 0, sizeof (ctx));
9183 args [0] = &method->klass->element_class->byval_arg;
9184 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9185 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
9186 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9192 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9194 typedef struct HashEntry {
9195 guint32 key, value, index;
9196 struct HashEntry *next;
9200 * emit_extra_methods:
9202 * Emit methods which are not in the METHOD table, like wrappers.
9205 emit_extra_methods (MonoAotCompile *acfg)
9207 int i, table_size, buf_size;
9209 guint32 *info_offsets;
9212 HashEntry *entry, *new_entry;
9213 int nmethods, max_chain_length;
9216 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9218 /* Emit method info */
9220 for (i = 0; i < acfg->extra_methods->len; ++i) {
9221 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9222 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9228 p = buf = (guint8 *)g_malloc (buf_size);
9232 method = cfg->method_to_register;
9234 encode_method_ref (acfg, method, p, &p);
9236 g_assert ((p - buf) < buf_size);
9238 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9243 * Construct a chained hash table for mapping indexes in extra_method_info to
9246 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9247 table = g_ptr_array_sized_new (table_size);
9248 for (i = 0; i < table_size; ++i)
9249 g_ptr_array_add (table, NULL);
9250 chain_lengths = g_new0 (int, table_size);
9251 max_chain_length = 0;
9252 for (i = 0; i < acfg->extra_methods->len; ++i) {
9253 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9254 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9260 key = info_offsets [i];
9261 value = get_method_index (acfg, method);
9263 hash = mono_aot_method_hash (method) % table_size;
9264 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9266 chain_lengths [hash] ++;
9267 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9269 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9270 new_entry->key = key;
9271 new_entry->value = value;
9273 entry = (HashEntry *)g_ptr_array_index (table, hash);
9274 if (entry == NULL) {
9275 new_entry->index = hash;
9276 g_ptr_array_index (table, hash) = new_entry;
9279 entry = entry->next;
9281 entry->next = new_entry;
9282 new_entry->index = table->len;
9283 g_ptr_array_add (table, new_entry);
9286 g_free (chain_lengths);
9288 //printf ("MAX: %d\n", max_chain_length);
9290 buf_size = table->len * 12 + 4;
9291 p = buf = (guint8 *)g_malloc (buf_size);
9292 encode_int (table_size, p, &p);
9294 for (i = 0; i < table->len; ++i) {
9295 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9297 if (entry == NULL) {
9298 encode_int (0, p, &p);
9299 encode_int (0, p, &p);
9300 encode_int (0, p, &p);
9302 //g_assert (entry->key > 0);
9303 encode_int (entry->key, p, &p);
9304 encode_int (entry->value, p, &p);
9306 encode_int (entry->next->index, p, &p);
9308 encode_int (0, p, &p);
9311 g_assert (p - buf <= buf_size);
9313 /* Emit the table */
9314 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9319 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9320 * This is used by mono_aot_find_jit_info ().
9322 buf_size = acfg->extra_methods->len * 8 + 4;
9323 p = buf = (guint8 *)g_malloc (buf_size);
9324 encode_int (acfg->extra_methods->len, p, &p);
9325 for (i = 0; i < acfg->extra_methods->len; ++i) {
9326 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9328 encode_int (get_method_index (acfg, method), p, &p);
9329 encode_int (info_offsets [i], p, &p);
9331 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9334 g_free (info_offsets);
9335 g_ptr_array_free (table, TRUE);
9339 generate_aotid (guint8* aotid)
9341 gpointer rand_handle;
9345 rand_handle = mono_rand_init (NULL, 0);
9347 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
9348 mono_error_assert_ok (&error);
9350 mono_rand_close (rand_handle);
9354 emit_exception_info (MonoAotCompile *acfg)
9358 SeqPointData sp_data;
9359 gboolean seq_points_to_file = FALSE;
9361 offsets = g_new0 (gint32, acfg->nmethods);
9362 for (i = 0; i < acfg->nmethods; ++i) {
9363 if (acfg->cfgs [i]) {
9364 MonoCompile *cfg = acfg->cfgs [i];
9366 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9367 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9368 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9369 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9370 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9372 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9373 offsets [i] = cfg->ex_info_offset;
9375 if (method_seq_points_to_file) {
9376 if (!seq_points_to_file) {
9377 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9378 seq_points_to_file = TRUE;
9380 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9387 if (seq_points_to_file) {
9388 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9389 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9390 char *image_basename = g_path_get_basename (acfg->image->name);
9391 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9392 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9394 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9395 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9399 mono_seq_point_data_write (&sp_data, aot_file_path);
9400 mono_seq_point_data_free (&sp_data);
9404 g_free (image_basename);
9406 g_free (aot_file_path);
9409 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9414 emit_unwind_info (MonoAotCompile *acfg)
9419 if (acfg->aot_opts.llvm_only) {
9420 g_assert (acfg->unwind_ops->len == 0);
9425 * The unwind info contains a lot of duplicates so we emit each unique
9426 * entry once, and only store the offset from the start of the table in the
9430 sprintf (symbol, "unwind_info");
9431 emit_section_change (acfg, RODATA_SECT, 1);
9432 emit_alignment (acfg, 8);
9433 emit_info_symbol (acfg, symbol);
9435 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9436 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9437 guint8 *unwind_info;
9438 guint32 unwind_info_len;
9442 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9445 encode_value (unwind_info_len, p, &p);
9446 emit_bytes (acfg, buf, p - buf);
9447 emit_bytes (acfg, unwind_info, unwind_info_len);
9449 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9454 emit_class_info (MonoAotCompile *acfg)
9459 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9460 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9461 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9463 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);
9467 typedef struct ClassNameTableEntry {
9468 guint32 token, index;
9469 struct ClassNameTableEntry *next;
9470 } ClassNameTableEntry;
9473 emit_class_name_table (MonoAotCompile *acfg)
9475 int i, table_size, buf_size;
9476 guint32 token, hash;
9481 ClassNameTableEntry *entry, *new_entry;
9484 * Construct a chained hash table for mapping class names to typedef tokens.
9486 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9487 table = g_ptr_array_sized_new (table_size);
9488 for (i = 0; i < table_size; ++i)
9489 g_ptr_array_add (table, NULL);
9490 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9492 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9493 klass = mono_class_get_checked (acfg->image, token, &error);
9495 mono_error_cleanup (&error);
9498 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9499 hash = mono_metadata_str_hash (full_name) % table_size;
9502 /* FIXME: Allocate from the mempool */
9503 new_entry = g_new0 (ClassNameTableEntry, 1);
9504 new_entry->token = token;
9506 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9507 if (entry == NULL) {
9508 new_entry->index = hash;
9509 g_ptr_array_index (table, hash) = new_entry;
9512 entry = entry->next;
9514 entry->next = new_entry;
9515 new_entry->index = table->len;
9516 g_ptr_array_add (table, new_entry);
9520 /* Emit the table */
9521 buf_size = table->len * 4 + 4;
9522 p = buf = (guint8 *)g_malloc0 (buf_size);
9524 /* FIXME: Optimize memory usage */
9525 g_assert (table_size < 65000);
9526 encode_int16 (table_size, p, &p);
9527 g_assert (table->len < 65000);
9528 for (i = 0; i < table->len; ++i) {
9529 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9531 if (entry == NULL) {
9532 encode_int16 (0, p, &p);
9533 encode_int16 (0, p, &p);
9535 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9537 encode_int16 (entry->next->index, p, &p);
9539 encode_int16 (0, p, &p);
9543 g_assert (p - buf <= buf_size);
9544 g_ptr_array_free (table, TRUE);
9546 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9552 emit_image_table (MonoAotCompile *acfg)
9558 * The image table is small but referenced in a lot of places.
9559 * So we emit it at once, and reference its elements by an index.
9561 buf_size = acfg->image_table->len * 28 + 4;
9562 for (i = 0; i < acfg->image_table->len; i++) {
9563 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9564 MonoAssemblyName *aname = &image->assembly->aname;
9566 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9569 buf = p = (guint8 *)g_malloc0 (buf_size);
9570 encode_int (acfg->image_table->len, p, &p);
9571 for (i = 0; i < acfg->image_table->len; i++) {
9572 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9573 MonoAssemblyName *aname = &image->assembly->aname;
9575 /* FIXME: Support multi-module assemblies */
9576 g_assert (image->assembly->image == image);
9578 encode_string (image->assembly_name, p, &p);
9579 encode_string (image->guid, p, &p);
9580 encode_string (aname->culture ? aname->culture : "", p, &p);
9581 encode_string ((const char*)aname->public_key_token, p, &p);
9583 while (GPOINTER_TO_UINT (p) % 8 != 0)
9586 encode_int (aname->flags, p, &p);
9587 encode_int (aname->major, p, &p);
9588 encode_int (aname->minor, p, &p);
9589 encode_int (aname->build, p, &p);
9590 encode_int (aname->revision, p, &p);
9592 g_assert (p - buf <= buf_size);
9594 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9600 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9602 int i, first_plt_got_patch = 0, buf_size;
9604 guint32 *got_info_offsets;
9605 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9607 /* Add the patches needed by the PLT to the GOT */
9609 acfg->plt_got_offset_base = acfg->got_offset;
9610 first_plt_got_patch = info->got_patches->len;
9611 for (i = 1; i < acfg->plt_offset; ++i) {
9612 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9614 g_ptr_array_add (info->got_patches, plt_entry->ji);
9616 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9619 acfg->got_offset += acfg->plt_offset;
9624 * - optimize offsets table.
9625 * - reduce number of exported symbols.
9626 * - emit info for a klass only once.
9627 * - determine when a method uses a GOT slot which is guaranteed to be already
9629 * - clean up and document the code.
9630 * - use String.Empty in class libs.
9633 /* Encode info required to decode shared GOT entries */
9634 buf_size = info->got_patches->len * 128;
9635 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9636 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9638 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9640 if (acfg->plt_offset)
9641 acfg->plt_got_info_offsets [0] = 0;
9643 for (i = 0; i < info->got_patches->len; ++i) {
9644 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9649 encode_value (ji->type, p, &p);
9651 encode_patch (acfg, ji, p, &p);
9652 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9653 g_assert (p - buf <= buf_size);
9654 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9656 if (!llvm && i >= first_plt_got_patch)
9657 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9658 acfg->stats.got_info_size += p - buf;
9661 /* Emit got_info_offsets table */
9663 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9664 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);
9668 emit_got (MonoAotCompile *acfg)
9670 char symbol [MAX_SYMBOL_SIZE];
9672 if (acfg->aot_opts.llvm_only)
9675 /* Don't make GOT global so accesses to it don't need relocations */
9676 sprintf (symbol, "%s", acfg->got_symbol);
9679 emit_unset_mode (acfg);
9680 fprintf (acfg->fp, ".section __DATA, __bss\n");
9681 emit_alignment (acfg, 8);
9683 emit_info_symbol (acfg, "jit_got");
9684 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9686 emit_section_change (acfg, ".bss", 0);
9687 emit_alignment (acfg, 8);
9688 if (acfg->aot_opts.write_symbols)
9689 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9690 emit_label (acfg, symbol);
9692 emit_info_symbol (acfg, "jit_got");
9693 if (acfg->got_offset > 0)
9694 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9697 sprintf (symbol, "got_end");
9698 emit_label (acfg, symbol);
9701 typedef struct GlobalsTableEntry {
9702 guint32 value, index;
9703 struct GlobalsTableEntry *next;
9704 } GlobalsTableEntry;
9706 #ifdef TARGET_WIN32_MSVC
9707 #define DLL_ENTRY_POINT "DllMain"
9710 emit_library_info (MonoAotCompile *acfg)
9712 // Only include for shared libraries linked directly from generated object.
9713 if (link_shared_library (acfg)) {
9715 char symbol [MAX_SYMBOL_SIZE];
9717 // Ask linker to export all global symbols.
9718 emit_section_change (acfg, ".drectve", 0);
9719 for (guint i = 0; i < acfg->globals->len; ++i) {
9720 name = (char *)g_ptr_array_index (acfg->globals, i);
9721 g_assert (name != NULL);
9722 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9723 emit_string (acfg, symbol);
9726 // Emit DLLMain function, needed by MSVC linker for DLL's.
9727 // NOTE, DllMain should not go into exports above.
9728 emit_section_change (acfg, ".text", 0);
9729 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9730 emit_label (acfg, DLL_ENTRY_POINT);
9732 // Simple implementation of DLLMain, just returning TRUE.
9733 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9734 fprintf (acfg->fp, "movl $1, %%eax\n");
9735 fprintf (acfg->fp, "ret\n");
9737 // Inform linker about our dll entry function.
9738 emit_section_change (acfg, ".drectve", 0);
9739 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9747 emit_library_info (MonoAotCompile *acfg)
9754 emit_globals (MonoAotCompile *acfg)
9760 GlobalsTableEntry *entry, *new_entry;
9762 if (!acfg->aot_opts.static_link)
9765 if (acfg->aot_opts.llvm_only) {
9766 g_assert (acfg->globals->len == 0);
9771 * When static linking, we emit a table containing our globals.
9775 * Construct a chained hash table for mapping global names to their index in
9776 * the globals table.
9778 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9779 table = g_ptr_array_sized_new (table_size);
9780 for (i = 0; i < table_size; ++i)
9781 g_ptr_array_add (table, NULL);
9782 for (i = 0; i < acfg->globals->len; ++i) {
9783 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9785 hash = mono_metadata_str_hash (name) % table_size;
9787 /* FIXME: Allocate from the mempool */
9788 new_entry = g_new0 (GlobalsTableEntry, 1);
9789 new_entry->value = i;
9791 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9792 if (entry == NULL) {
9793 new_entry->index = hash;
9794 g_ptr_array_index (table, hash) = new_entry;
9797 entry = entry->next;
9799 entry->next = new_entry;
9800 new_entry->index = table->len;
9801 g_ptr_array_add (table, new_entry);
9805 /* Emit the table */
9806 sprintf (symbol, ".Lglobals_hash");
9807 emit_section_change (acfg, RODATA_SECT, 0);
9808 emit_alignment (acfg, 8);
9809 emit_label (acfg, symbol);
9811 /* FIXME: Optimize memory usage */
9812 g_assert (table_size < 65000);
9813 emit_int16 (acfg, table_size);
9814 for (i = 0; i < table->len; ++i) {
9815 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9817 if (entry == NULL) {
9818 emit_int16 (acfg, 0);
9819 emit_int16 (acfg, 0);
9821 emit_int16 (acfg, entry->value + 1);
9823 emit_int16 (acfg, entry->next->index);
9825 emit_int16 (acfg, 0);
9829 /* Emit the names */
9830 for (i = 0; i < acfg->globals->len; ++i) {
9831 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9833 sprintf (symbol, "name_%d", i);
9834 emit_section_change (acfg, RODATA_SECT, 1);
9836 emit_alignment (acfg, 4);
9838 emit_label (acfg, symbol);
9839 emit_string (acfg, name);
9842 /* Emit the globals table */
9843 sprintf (symbol, "globals");
9844 emit_section_change (acfg, ".data", 0);
9845 /* This is not a global, since it is accessed by the init function */
9846 emit_alignment (acfg, 8);
9847 emit_info_symbol (acfg, symbol);
9849 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9850 emit_pointer (acfg, symbol);
9852 for (i = 0; i < acfg->globals->len; ++i) {
9853 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9855 sprintf (symbol, "name_%d", i);
9856 emit_pointer (acfg, symbol);
9858 g_assert (strlen (name) < sizeof (symbol));
9859 sprintf (symbol, "%s", name);
9860 emit_pointer (acfg, symbol);
9862 /* Null terminate the table */
9863 emit_int32 (acfg, 0);
9864 emit_int32 (acfg, 0);
9868 emit_mem_end (MonoAotCompile *acfg)
9872 if (acfg->aot_opts.llvm_only)
9875 sprintf (symbol, "mem_end");
9876 emit_section_change (acfg, ".text", 1);
9877 emit_alignment_code (acfg, 8);
9878 emit_label (acfg, symbol);
9882 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9886 info->version = MONO_AOT_FILE_VERSION;
9887 info->plt_got_offset_base = acfg->plt_got_offset_base;
9888 info->got_size = acfg->got_offset * sizeof (gpointer);
9889 info->plt_size = acfg->plt_offset;
9890 info->nmethods = acfg->nmethods;
9891 info->flags = acfg->flags;
9892 info->opts = acfg->opts;
9893 info->simd_opts = acfg->simd_opts;
9894 info->gc_name_index = acfg->gc_name_offset;
9895 info->datafile_size = acfg->datafile_offset;
9896 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9897 info->table_offsets [i] = acfg->table_offsets [i];
9898 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9899 info->num_trampolines [i] = acfg->num_trampolines [i];
9900 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9901 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9902 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9903 info->trampoline_size [i] = acfg->trampoline_size [i];
9904 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9906 info->double_align = MONO_ABI_ALIGNOF (double);
9907 info->long_align = MONO_ABI_ALIGNOF (gint64);
9908 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9909 info->tramp_page_size = acfg->tramp_page_size;
9910 info->nshared_got_entries = acfg->nshared_got_entries;
9911 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9912 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9914 memcpy(&info->aotid, acfg->image->aotid, 16);
9918 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9920 char symbol [MAX_SYMBOL_SIZE];
9922 const char **symbols;
9924 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9926 symbols [sindex ++] = acfg->got_symbol;
9928 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9929 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9931 symbols [sindex ++] = NULL;
9932 symbols [sindex ++] = NULL;
9934 /* llvm_get_method */
9935 symbols [sindex ++] = NULL;
9936 /* llvm_get_unbox_tramp */
9937 symbols [sindex ++] = NULL;
9938 if (!acfg->aot_opts.llvm_only) {
9939 symbols [sindex ++] = "jit_code_start";
9940 symbols [sindex ++] = "jit_code_end";
9941 symbols [sindex ++] = "method_addresses";
9943 symbols [sindex ++] = NULL;
9944 symbols [sindex ++] = NULL;
9945 symbols [sindex ++] = NULL;
9947 if (acfg->data_outfile) {
9948 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9949 symbols [sindex ++] = NULL;
9951 symbols [sindex ++] = "blob";
9952 symbols [sindex ++] = "class_name_table";
9953 symbols [sindex ++] = "class_info_offsets";
9954 symbols [sindex ++] = "method_info_offsets";
9955 symbols [sindex ++] = "ex_info_offsets";
9956 symbols [sindex ++] = "extra_method_info_offsets";
9957 symbols [sindex ++] = "extra_method_table";
9958 symbols [sindex ++] = "got_info_offsets";
9960 symbols [sindex ++] = "llvm_got_info_offsets";
9962 symbols [sindex ++] = NULL;
9963 symbols [sindex ++] = "image_table";
9965 symbols [sindex ++] = "mem_end";
9966 symbols [sindex ++] = "assembly_guid";
9967 symbols [sindex ++] = "runtime_version";
9968 if (acfg->num_trampoline_got_entries) {
9969 symbols [sindex ++] = "specific_trampolines";
9970 symbols [sindex ++] = "static_rgctx_trampolines";
9971 symbols [sindex ++] = "imt_trampolines";
9972 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9974 symbols [sindex ++] = NULL;
9975 symbols [sindex ++] = NULL;
9976 symbols [sindex ++] = NULL;
9977 symbols [sindex ++] = NULL;
9979 if (acfg->aot_opts.static_link) {
9980 symbols [sindex ++] = "globals";
9982 symbols [sindex ++] = NULL;
9984 symbols [sindex ++] = "assembly_name";
9985 symbols [sindex ++] = "plt";
9986 symbols [sindex ++] = "plt_end";
9987 symbols [sindex ++] = "unwind_info";
9988 if (!acfg->aot_opts.llvm_only) {
9989 symbols [sindex ++] = "unbox_trampolines";
9990 symbols [sindex ++] = "unbox_trampolines_end";
9991 symbols [sindex ++] = "unbox_trampoline_addresses";
9993 symbols [sindex ++] = NULL;
9994 symbols [sindex ++] = NULL;
9995 symbols [sindex ++] = NULL;
9998 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10000 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10001 emit_section_change (acfg, ".data", 0);
10002 emit_alignment (acfg, 8);
10003 emit_label (acfg, symbol);
10004 if (!acfg->aot_opts.static_link)
10005 emit_global (acfg, symbol, FALSE);
10007 /* The data emitted here must match MonoAotFileInfo. */
10009 emit_int32 (acfg, info->version);
10010 emit_int32 (acfg, info->dummy);
10013 * We emit pointers to our data structures instead of emitting global symbols which
10014 * point to them, to reduce the number of globals, and because using globals leads to
10015 * various problems (i.e. arm/thumb).
10017 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10018 emit_pointer (acfg, symbols [i]);
10020 emit_int32 (acfg, info->plt_got_offset_base);
10021 emit_int32 (acfg, info->got_size);
10022 emit_int32 (acfg, info->plt_size);
10023 emit_int32 (acfg, info->nmethods);
10024 emit_int32 (acfg, info->flags);
10025 emit_int32 (acfg, info->opts);
10026 emit_int32 (acfg, info->simd_opts);
10027 emit_int32 (acfg, info->gc_name_index);
10028 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10029 emit_int32 (acfg, info->double_align);
10030 emit_int32 (acfg, info->long_align);
10031 emit_int32 (acfg, info->generic_tramp_num);
10032 emit_int32 (acfg, info->tramp_page_size);
10033 emit_int32 (acfg, info->nshared_got_entries);
10034 emit_int32 (acfg, info->datafile_size);
10036 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10037 emit_int32 (acfg, info->table_offsets [i]);
10038 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10039 emit_int32 (acfg, info->num_trampolines [i]);
10040 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10041 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10042 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10043 emit_int32 (acfg, info->trampoline_size [i]);
10044 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10045 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10047 emit_bytes (acfg, info->aotid, 16);
10049 if (acfg->aot_opts.static_link) {
10050 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10051 emit_alignment (acfg, sizeof (gpointer));
10052 emit_label (acfg, acfg->static_linking_symbol);
10053 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10058 * Emit a structure containing all the information not stored elsewhere.
10061 emit_file_info (MonoAotCompile *acfg)
10064 MonoAotFileInfo *info;
10066 if (acfg->aot_opts.bind_to_runtime_version) {
10067 build_info = mono_get_runtime_build_info ();
10068 emit_string_symbol (acfg, "runtime_version", build_info);
10069 g_free (build_info);
10071 emit_string_symbol (acfg, "runtime_version", "");
10074 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10076 /* Emit a string holding the assembly name */
10077 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10079 info = g_new0 (MonoAotFileInfo, 1);
10080 init_aot_file_info (acfg, info);
10082 if (acfg->aot_opts.static_link) {
10083 char symbol [MAX_SYMBOL_SIZE];
10087 * Emit a global symbol which can be passed by an embedding app to
10088 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10091 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10093 /* Get rid of characters which cannot occur in symbols */
10095 for (p = symbol; *p; ++p) {
10096 if (!(isalnum (*p) || *p == '_'))
10099 acfg->static_linking_symbol = g_strdup (symbol);
10103 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10105 emit_aot_file_info (acfg, info);
10109 emit_blob (MonoAotCompile *acfg)
10111 acfg->blob_closed = TRUE;
10113 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10117 emit_objc_selectors (MonoAotCompile *acfg)
10122 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10127 * cat > foo.m << EOF
10130 * return @selector(print:);
10135 mono_img_writer_emit_unset_mode (acfg->w);
10136 g_assert (acfg->fp);
10137 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10138 fprintf (acfg->fp, ".align 3\n");
10139 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10140 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10141 emit_label (acfg, symbol);
10142 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10143 emit_pointer (acfg, symbol);
10146 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10147 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10148 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10149 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10152 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10153 fprintf (acfg->fp, ".align 3\n");
10154 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10155 fprintf (acfg->fp, ".long 0\n");
10156 fprintf (acfg->fp, ".long 16\n");
10160 emit_dwarf_info (MonoAotCompile *acfg)
10162 #ifdef EMIT_DWARF_INFO
10164 char symbol2 [128];
10166 /* DIEs for methods */
10167 for (i = 0; i < acfg->nmethods; ++i) {
10168 MonoCompile *cfg = acfg->cfgs [i];
10173 // FIXME: LLVM doesn't define .Lme_...
10174 if (cfg->compile_llvm)
10177 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10179 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 ()));
10185 collect_methods (MonoAotCompile *acfg)
10188 MonoImage *image = acfg->image;
10190 /* Collect methods */
10191 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10193 MonoMethod *method;
10194 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10196 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10199 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
10200 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10201 mono_error_cleanup (&error);
10205 /* Load all methods eagerly to skip the slower lazy loading code */
10206 mono_class_setup_methods (method->klass);
10208 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10209 /* Compile the wrapper instead */
10210 /* We do this here instead of add_wrappers () because it is easy to do it here */
10211 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10215 /* FIXME: Some mscorlib methods don't have debug info */
10217 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10218 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10219 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10220 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10221 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10222 if (!mono_debug_lookup_method (method)) {
10223 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10230 if (method->is_generic || mono_class_is_gtd (method->klass))
10231 /* Compile the ref shared version instead */
10232 method = mini_get_shared_method (method);
10234 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10235 add_method_with_index (acfg, method, i, FALSE);
10236 acfg->method_index ++;
10239 /* gsharedvt methods */
10240 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10242 MonoMethod *method;
10243 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10245 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10248 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10249 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
10251 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10252 MonoMethod *gshared;
10254 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10255 add_extra_method (acfg, gshared);
10259 if (mono_aot_mode_is_full (&acfg->aot_opts))
10260 add_generic_instances (acfg);
10262 if (mono_aot_mode_is_full (&acfg->aot_opts))
10263 add_wrappers (acfg);
10268 compile_methods (MonoAotCompile *acfg)
10270 int i, methods_len;
10272 if (acfg->aot_opts.nthreads > 0) {
10275 GPtrArray *threads;
10276 MonoThreadHandle *thread_handle;
10277 gpointer *user_data;
10278 MonoMethod **methods;
10280 methods_len = acfg->methods->len;
10282 len = acfg->methods->len / acfg->aot_opts.nthreads;
10283 g_assert (len > 0);
10285 * Partition the list of methods into fragments, and hand it to threads to
10288 threads = g_ptr_array_new ();
10289 /* Make a copy since acfg->methods is modified by compile_method () */
10290 methods = g_new0 (MonoMethod*, methods_len);
10291 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
10292 for (i = 0; i < methods_len; ++i)
10293 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
10295 while (i < methods_len) {
10297 MonoInternalThread *thread;
10299 frag = g_ptr_array_new ();
10300 for (j = 0; j < len; ++j) {
10301 if (i < methods_len) {
10302 g_ptr_array_add (frag, methods [i]);
10307 user_data = g_new0 (gpointer, 3);
10308 user_data [0] = acfg;
10309 user_data [1] = frag;
10311 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
10312 mono_error_assert_ok (&error);
10314 thread_handle = mono_threads_open_thread_handle (thread->handle);
10315 g_ptr_array_add (threads, thread_handle);
10319 for (i = 0; i < threads->len; ++i) {
10320 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
10321 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
10327 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
10328 for (i = methods_len; i < acfg->methods->len; ++i) {
10329 /* This can add new methods to acfg->methods */
10330 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
10335 compile_asm (MonoAotCompile *acfg)
10337 char *command, *objfile;
10338 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
10339 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
10340 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
10342 #ifdef TARGET_WIN32_MSVC
10343 #define AS_OPTIONS "-c -x assembler"
10344 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
10345 #define AS_OPTIONS "--64"
10346 #elif defined(TARGET_POWERPC64)
10347 #define AS_OPTIONS "-a64 -mppc64"
10348 #elif defined(sparc) && SIZEOF_VOID_P == 8
10349 #define AS_OPTIONS "-xarch=v9"
10350 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10351 #define AS_OPTIONS "-arch i386"
10353 #define AS_OPTIONS ""
10356 #ifdef __native_client_codegen__
10357 #if defined(TARGET_AMD64)
10358 #define AS_NAME "nacl64-as"
10360 #define AS_NAME "nacl-as"
10362 #elif defined(TARGET_OSX)
10363 #define AS_NAME "clang"
10364 #elif defined(TARGET_WIN32_MSVC)
10365 #define AS_NAME "clang.exe"
10367 #define AS_NAME "as"
10370 #ifdef TARGET_WIN32_MSVC
10371 #define AS_OBJECT_FILE_SUFFIX "obj"
10373 #define AS_OBJECT_FILE_SUFFIX "o"
10377 #define LD_NAME "ld"
10378 #define LD_OPTIONS "-shared -G"
10379 #elif defined(__ppc__) && defined(TARGET_MACH)
10380 #define LD_NAME "gcc"
10381 #define LD_OPTIONS "-dynamiclib"
10382 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10383 #define LD_NAME "clang"
10384 #define LD_OPTIONS "--shared"
10385 #elif defined(TARGET_WIN32_MSVC)
10386 #define LD_NAME "link.exe"
10387 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
10388 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10389 #define LD_NAME "gcc"
10390 #define LD_OPTIONS "-shared"
10391 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10392 #define LD_NAME "clang"
10393 #define LD_OPTIONS "-m32 -dynamiclib"
10394 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10395 #define LD_NAME "gcc"
10396 #define LD_OPTIONS "--shared"
10397 #elif defined(TARGET_POWERPC64)
10398 #define LD_OPTIONS "-m elf64ppc"
10402 #define LD_OPTIONS ""
10405 if (acfg->aot_opts.asm_only) {
10406 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10407 if (acfg->aot_opts.static_link)
10408 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10410 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10414 if (acfg->aot_opts.static_link) {
10415 if (acfg->aot_opts.outfile)
10416 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10418 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
10420 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
10424 g_string_append (acfg->as_args, "-c -x assembler");
10427 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10428 acfg->as_args ? acfg->as_args->str : "",
10429 wrap_path (objfile), wrap_path (acfg->tmpfname));
10430 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10431 if (execute_system (command) != 0) {
10437 if (acfg->llvm && !acfg->llvm_owriter) {
10438 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10439 acfg->as_args ? acfg->as_args->str : "",
10440 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10441 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10442 if (execute_system (command) != 0) {
10451 if (acfg->aot_opts.static_link) {
10452 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10453 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10458 if (acfg->aot_opts.outfile)
10459 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10461 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10463 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10466 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10468 llvm_ofile = g_strdup ("");
10471 /* replace the ; flags separators with spaces */
10472 g_strdelimit (ld_flags, ";", ' ');
10474 if (acfg->aot_opts.llvm_only)
10475 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10477 #ifdef TARGET_WIN32_MSVC
10478 g_assert (tmp_outfile_name != NULL);
10479 g_assert (objfile != NULL);
10480 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10481 ld_flags, tmp_outfile_name, objfile);
10482 #elif defined(LD_NAME)
10483 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10484 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10485 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10488 if (acfg->aot_opts.tool_prefix) {
10489 /* Cross compiling */
10490 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10491 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10492 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10494 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10495 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10496 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10498 if (acfg->aot_opts.llvm_only) {
10499 command = g_strdup_printf ("clang++ %s", args);
10501 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10506 aot_printf (acfg, "Executing the native linker: %s\n", command);
10507 if (execute_system (command) != 0) {
10508 g_free (tmp_outfile_name);
10509 g_free (outfile_name);
10518 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10519 printf ("Stripping the binary: %s\n", com);
10520 execute_system (com);
10523 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10525 * gas generates 'mapping symbols' each time code and data is mixed, which
10526 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10528 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10529 aot_printf (acfg, "Stripping the binary: %s\n", command);
10530 if (execute_system (command) != 0) {
10531 g_free (tmp_outfile_name);
10532 g_free (outfile_name);
10539 if (0 != rename (tmp_outfile_name, outfile_name)) {
10540 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10541 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10542 unlink (outfile_name);
10543 rename (tmp_outfile_name, outfile_name);
10547 #if defined(TARGET_MACH)
10548 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10549 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10550 if (execute_system (command) != 0) {
10555 if (!acfg->aot_opts.save_temps)
10558 g_free (tmp_outfile_name);
10559 g_free (outfile_name);
10562 if (acfg->aot_opts.save_temps)
10563 aot_printf (acfg, "Retained input file.\n");
10565 unlink (acfg->tmpfname);
10571 profread_byte (FILE *infile)
10576 res = fread (&i, 1, 1, infile);
10577 g_assert (res == 1);
10582 profread_int (FILE *infile)
10586 res = fread (&i, 4, 1, infile);
10587 g_assert (res == 1);
10592 profread_string (FILE *infile)
10598 len = profread_int (infile);
10599 if (len + 1 > 1024)
10600 pbuf = g_malloc (len + 1);
10603 res = fread (pbuf, 1, len, infile);
10604 g_assert (res == len);
10607 return g_strdup (buf);
10613 load_profile_file (MonoAotCompile *acfg, char *filename)
10617 int res, len, version;
10620 infile = fopen (filename, "r");
10622 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10626 printf ("Using profile data file '%s'\n", filename);
10628 sprintf (magic, AOT_PROFILER_MAGIC);
10629 len = strlen (magic);
10630 res = fread (buf, 1, len, infile);
10631 magic [len] = '\0';
10633 if ((res != len) || strcmp (buf, magic) != 0) {
10634 printf ("Profile file has wrong header: '%s'.\n", buf);
10638 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10639 version = profread_int (infile);
10640 if (version != expected_version) {
10641 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10646 ProfileData *data = g_new0 (ProfileData, 1);
10647 data->images = g_hash_table_new (NULL, NULL);
10648 data->classes = g_hash_table_new (NULL, NULL);
10649 data->ginsts = g_hash_table_new (NULL, NULL);
10650 data->methods = g_hash_table_new (NULL, NULL);
10653 int type = profread_byte (infile);
10654 int id = profread_int (infile);
10656 if (type == AOTPROF_RECORD_NONE)
10660 case AOTPROF_RECORD_IMAGE: {
10661 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10662 idata->name = profread_string (infile);
10663 char *mvid = profread_string (infile);
10665 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10668 case AOTPROF_RECORD_GINST: {
10670 int len = profread_int (infile);
10672 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10674 gdata->argv = g_new0 (ClassProfileData*, len);
10676 for (i = 0; i < len; ++i) {
10677 int class_id = profread_int (infile);
10679 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10680 g_assert (gdata->argv [i]);
10682 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10685 case AOTPROF_RECORD_TYPE: {
10686 int type = profread_byte (infile);
10689 case MONO_TYPE_CLASS: {
10690 int image_id = profread_int (infile);
10691 int ginst_id = profread_int (infile);
10692 char *class_name = profread_string (infile);
10694 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10697 char *p = strrchr (class_name, '.');
10701 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10702 cdata->image = image;
10703 cdata->ns = g_strdup (class_name);
10704 cdata->name = g_strdup (p + 1);
10706 if (ginst_id != -1) {
10707 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10708 g_assert (cdata->inst);
10710 g_free (class_name);
10712 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10716 case MONO_TYPE_SZARRAY: {
10717 int elem_id = profread_int (infile);
10723 g_assert_not_reached ();
10728 case AOTPROF_RECORD_METHOD: {
10729 int class_id = profread_int (infile);
10730 int ginst_id = profread_int (infile);
10731 int param_count = profread_int (infile);
10732 char *method_name = profread_string (infile);
10733 char *sig = profread_string (infile);
10735 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10738 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10740 mdata->klass = klass;
10741 mdata->name = method_name;
10742 mdata->signature = sig;
10743 mdata->param_count = param_count;
10745 if (ginst_id != -1) {
10746 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10747 g_assert (mdata->inst);
10749 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10753 printf ("%d\n", type);
10754 g_assert_not_reached ();
10760 acfg->profile_data = g_list_append (acfg->profile_data, data);
10764 resolve_class (ClassProfileData *cdata);
10767 resolve_ginst (GInstProfileData *inst_data)
10771 if (inst_data->inst)
10774 for (i = 0; i < inst_data->argc; ++i) {
10775 resolve_class (inst_data->argv [i]);
10776 if (!inst_data->argv [i]->klass)
10779 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10780 for (i = 0; i < inst_data->argc; ++i)
10781 args [i] = &inst_data->argv [i]->klass->byval_arg;
10783 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10787 resolve_class (ClassProfileData *cdata)
10792 if (!cdata->image->image)
10795 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10797 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10801 resolve_ginst (cdata->inst);
10802 if (!cdata->inst->inst)
10804 MonoGenericContext ctx;
10806 memset (&ctx, 0, sizeof (ctx));
10807 ctx.class_inst = cdata->inst->inst;
10808 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10810 cdata->klass = klass;
10815 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10818 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10820 GHashTableIter iter;
10821 gpointer key, value;
10828 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10829 g_hash_table_iter_init (&iter, data->images);
10830 while (g_hash_table_iter_next (&iter, &key, &value)) {
10831 ImageProfileData *idata = (ImageProfileData*)value;
10833 for (i = 0; i < assemblies->len; ++i) {
10834 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10836 if (!strcmp (ass->aname.name, idata->name)) {
10837 idata->image = ass->image;
10842 g_ptr_array_free (assemblies, TRUE);
10845 g_hash_table_iter_init (&iter, data->classes);
10846 while (g_hash_table_iter_next (&iter, &key, &value)) {
10847 ClassProfileData *cdata = (ClassProfileData*)value;
10849 if (!cdata->image->image) {
10850 if (acfg->aot_opts.verbose)
10851 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10855 resolve_class (cdata);
10858 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10863 g_hash_table_iter_init (&iter, data->methods);
10864 while (g_hash_table_iter_next (&iter, &key, &value)) {
10865 MethodProfileData *mdata = (MethodProfileData*)value;
10870 resolve_class (mdata->klass);
10871 klass = mdata->klass->klass;
10873 if (acfg->aot_opts.verbose)
10874 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10878 while ((m = mono_class_get_methods (klass, &miter))) {
10881 if (strcmp (m->name, mdata->name))
10883 MonoMethodSignature *sig = mono_method_signature (m);
10886 if (sig->param_count != mdata->param_count)
10889 resolve_ginst (mdata->inst);
10890 if (!mdata->inst->inst)
10892 MonoGenericContext ctx;
10894 memset (&ctx, 0, sizeof (ctx));
10895 ctx.method_inst = mdata->inst->inst;
10897 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10900 sig = mono_method_signature_checked (m, &error);
10901 if (!is_ok (&error)) {
10902 mono_error_cleanup (&error);
10906 char *sig_str = mono_signature_full_name (sig);
10907 gboolean match = !strcmp (sig_str, mdata->signature);
10912 //printf ("%s\n", mono_method_full_name (m, 1));
10916 if (!mdata->method) {
10917 if (acfg->aot_opts.verbose)
10918 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10924 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10928 for (i = 0; i < inst->type_argc; ++i) {
10929 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10930 if (k->image == image)
10932 if (mono_class_is_ginst (k)) {
10933 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10934 if (inst_references_image (kinst, image))
10942 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10946 for (i = 0; i < inst->type_argc; ++i) {
10947 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10948 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10955 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10957 GHashTableIter iter;
10958 gpointer key, value;
10964 if (acfg->aot_opts.profile_only) {
10965 /* Add methods referenced by the profile */
10966 g_hash_table_iter_init (&iter, data->methods);
10967 while (g_hash_table_iter_next (&iter, &key, &value)) {
10968 MethodProfileData *mdata = (MethodProfileData*)value;
10969 MonoMethod *m = mdata->method;
10973 if (m->is_inflated)
10975 add_extra_method (acfg, m);
10976 g_hash_table_insert (acfg->profile_methods, m, m);
10982 * Add method instances 'related' to this assembly to the AOT image.
10984 g_hash_table_iter_init (&iter, data->methods);
10985 while (g_hash_table_iter_next (&iter, &key, &value)) {
10986 MethodProfileData *mdata = (MethodProfileData*)value;
10987 MonoMethod *m = mdata->method;
10988 MonoGenericContext *ctx;
10992 if (!m->is_inflated)
10995 ctx = mono_method_get_context (m);
10996 /* For simplicity, add instances which reference the assembly we are compiling */
10997 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10998 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10999 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11000 //printf ("%s\n", mono_method_full_name (m, TRUE));
11001 add_extra_method (acfg, m);
11003 } else if (m->klass->image == acfg->image &&
11004 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11005 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11006 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11007 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11008 //printf ("%s\n", mono_method_full_name (m, TRUE));
11009 add_extra_method (acfg, m);
11013 * FIXME: We might skip some instances, for example:
11014 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11015 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11019 printf ("Added %d methods from profile.\n", count);
11023 init_got_info (GotInfo *info)
11027 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11028 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11029 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11030 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11031 info->got_patches = g_ptr_array_new ();
11034 static MonoAotCompile*
11035 acfg_create (MonoAssembly *ass, guint32 opts)
11037 MonoImage *image = ass->image;
11038 MonoAotCompile *acfg;
11040 acfg = g_new0 (MonoAotCompile, 1);
11041 acfg->methods = g_ptr_array_new ();
11042 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11043 acfg->method_depth = g_hash_table_new (NULL, NULL);
11044 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11045 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11046 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11047 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11048 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11049 acfg->image_hash = g_hash_table_new (NULL, NULL);
11050 acfg->image_table = g_ptr_array_new ();
11051 acfg->globals = g_ptr_array_new ();
11052 acfg->image = image;
11054 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11055 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11056 acfg->mempool = mono_mempool_new ();
11057 acfg->extra_methods = g_ptr_array_new ();
11058 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11059 acfg->unwind_ops = g_ptr_array_new ();
11060 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11061 acfg->method_order = g_ptr_array_new ();
11062 acfg->export_names = g_hash_table_new (NULL, NULL);
11063 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11064 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11065 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11066 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11067 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11068 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11069 mono_os_mutex_init_recursive (&acfg->mutex);
11071 init_got_info (&acfg->got_info);
11072 init_got_info (&acfg->llvm_got_info);
11078 got_info_free (GotInfo *info)
11082 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11083 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11084 g_free (info->patch_to_got_offset_by_type);
11085 g_hash_table_destroy (info->patch_to_got_offset);
11086 g_ptr_array_free (info->got_patches, TRUE);
11090 acfg_free (MonoAotCompile *acfg)
11094 mono_img_writer_destroy (acfg->w);
11095 for (i = 0; i < acfg->nmethods; ++i)
11096 if (acfg->cfgs [i])
11097 mono_destroy_compile (acfg->cfgs [i]);
11099 g_free (acfg->cfgs);
11101 g_free (acfg->static_linking_symbol);
11102 g_free (acfg->got_symbol);
11103 g_free (acfg->plt_symbol);
11104 g_ptr_array_free (acfg->methods, TRUE);
11105 g_ptr_array_free (acfg->image_table, TRUE);
11106 g_ptr_array_free (acfg->globals, TRUE);
11107 g_ptr_array_free (acfg->unwind_ops, TRUE);
11108 g_hash_table_destroy (acfg->method_indexes);
11109 g_hash_table_destroy (acfg->method_depth);
11110 g_hash_table_destroy (acfg->plt_offset_to_entry);
11111 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11112 if (acfg->patch_to_plt_entry [i])
11113 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11115 g_free (acfg->patch_to_plt_entry);
11116 g_hash_table_destroy (acfg->method_to_cfg);
11117 g_hash_table_destroy (acfg->token_info_hash);
11118 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11119 g_hash_table_destroy (acfg->image_hash);
11120 g_hash_table_destroy (acfg->unwind_info_offsets);
11121 g_hash_table_destroy (acfg->method_label_hash);
11122 if (acfg->typespec_classes)
11123 g_hash_table_destroy (acfg->typespec_classes);
11124 g_hash_table_destroy (acfg->export_names);
11125 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11126 g_hash_table_destroy (acfg->klass_blob_hash);
11127 g_hash_table_destroy (acfg->method_blob_hash);
11128 got_info_free (&acfg->got_info);
11129 got_info_free (&acfg->llvm_got_info);
11130 mono_mempool_destroy (acfg->mempool);
11134 #define WRAPPER(e,n) n,
11135 static const char* const
11136 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11137 #include "mono/metadata/wrapper-types.h"
11141 static G_GNUC_UNUSED const char*
11142 get_wrapper_type_name (int type)
11144 return wrapper_type_names [type];
11150 static void aot_dump (MonoAotCompile *acfg)
11156 mono_json_writer_init (&writer);
11158 mono_json_writer_object_begin(&writer);
11161 mono_json_writer_indent (&writer);
11162 mono_json_writer_object_key(&writer, "methods");
11163 mono_json_writer_array_begin (&writer);
11166 for (i = 0; i < acfg->nmethods; ++i) {
11168 MonoMethod *method;
11171 cfg = acfg->cfgs [i];
11175 method = cfg->orig_method;
11177 mono_json_writer_indent (&writer);
11178 mono_json_writer_object_begin(&writer);
11180 mono_json_writer_indent (&writer);
11181 mono_json_writer_object_key(&writer, "name");
11182 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11184 mono_json_writer_indent (&writer);
11185 mono_json_writer_object_key(&writer, "signature");
11186 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11188 mono_json_writer_indent (&writer);
11189 mono_json_writer_object_key(&writer, "code_size");
11190 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11192 klass = method->klass;
11194 mono_json_writer_indent (&writer);
11195 mono_json_writer_object_key(&writer, "class");
11196 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11198 mono_json_writer_indent (&writer);
11199 mono_json_writer_object_key(&writer, "namespace");
11200 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11202 mono_json_writer_indent (&writer);
11203 mono_json_writer_object_key(&writer, "wrapper_type");
11204 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11206 mono_json_writer_indent_pop (&writer);
11207 mono_json_writer_indent (&writer);
11208 mono_json_writer_object_end (&writer);
11209 mono_json_writer_printf (&writer, ",\n");
11212 mono_json_writer_indent_pop (&writer);
11213 mono_json_writer_indent (&writer);
11214 mono_json_writer_array_end (&writer);
11215 mono_json_writer_printf (&writer, ",\n");
11219 mono_json_writer_indent_push (&writer);
11220 mono_json_writer_indent (&writer);
11221 mono_json_writer_object_key(&writer, "plt");
11222 mono_json_writer_array_begin (&writer);
11224 for (i = 0; i < acfg->plt_offset; ++i) {
11225 MonoPltEntry *plt_entry = NULL;
11230 * The first plt entry is unused.
11234 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11235 ji = plt_entry->ji;
11237 mono_json_writer_indent (&writer);
11238 mono_json_writer_printf (&writer, "{ ");
11239 mono_json_writer_object_key(&writer, "symbol");
11240 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11243 mono_json_writer_indent_pop (&writer);
11244 mono_json_writer_indent (&writer);
11245 mono_json_writer_array_end (&writer);
11246 mono_json_writer_printf (&writer, ",\n");
11251 mono_json_writer_indent_push (&writer);
11252 mono_json_writer_indent (&writer);
11253 mono_json_writer_object_key(&writer, "got");
11254 mono_json_writer_array_begin (&writer);
11256 mono_json_writer_indent_push (&writer);
11257 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11258 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11260 mono_json_writer_indent (&writer);
11261 mono_json_writer_printf (&writer, "{ ");
11262 mono_json_writer_object_key(&writer, "patch_name");
11263 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11266 mono_json_writer_indent_pop (&writer);
11267 mono_json_writer_indent (&writer);
11268 mono_json_writer_array_end (&writer);
11269 mono_json_writer_printf (&writer, ",\n");
11272 mono_json_writer_indent_pop (&writer);
11273 mono_json_writer_indent (&writer);
11274 mono_json_writer_object_end (&writer);
11276 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11277 dumpfile = fopen (dumpname, "w+");
11280 fprintf (dumpfile, "%s", writer.text->str);
11283 mono_json_writer_destroy (&writer);
11286 static const char *preinited_jit_icalls[] = {
11287 "mono_aot_init_llvm_method",
11288 "mono_aot_init_gshared_method_this",
11289 "mono_aot_init_gshared_method_mrgctx",
11290 "mono_aot_init_gshared_method_vtable",
11291 "mono_llvm_throw_corlib_exception",
11292 "mono_init_vtable_slot",
11293 "mono_helper_ldstr_mscorlib"
11297 add_preinit_got_slots (MonoAotCompile *acfg)
11303 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
11304 * during method initialization etc.
11307 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11308 ji->type = MONO_PATCH_INFO_IMAGE;
11309 ji->data.image = acfg->image;
11310 get_got_offset (acfg, FALSE, ji);
11311 get_got_offset (acfg, TRUE, ji);
11313 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11314 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
11315 get_got_offset (acfg, FALSE, ji);
11316 get_got_offset (acfg, TRUE, ji);
11318 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11319 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
11320 get_got_offset (acfg, FALSE, ji);
11321 get_got_offset (acfg, TRUE, ji);
11323 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11324 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
11325 get_got_offset (acfg, FALSE, ji);
11326 get_got_offset (acfg, TRUE, ji);
11328 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11329 ji->type = MONO_PATCH_INFO_AOT_MODULE;
11330 get_got_offset (acfg, FALSE, ji);
11331 get_got_offset (acfg, TRUE, ji);
11333 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11334 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
11335 get_got_offset (acfg, FALSE, ji);
11336 get_got_offset (acfg, TRUE, ji);
11338 for (i = 0; i < TLS_KEY_NUM; i++) {
11339 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11340 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
11341 ji->data.index = i;
11342 get_got_offset (acfg, FALSE, ji);
11343 get_got_offset (acfg, TRUE, ji);
11345 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11346 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
11347 ji->data.index = i;
11348 get_got_offset (acfg, FALSE, ji);
11349 get_got_offset (acfg, TRUE, ji);
11352 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11353 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
11354 get_got_offset (acfg, FALSE, ji);
11355 get_got_offset (acfg, TRUE, ji);
11357 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
11358 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
11359 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11360 ji->data.name = preinited_jit_icalls [i];
11361 get_got_offset (acfg, FALSE, ji);
11362 get_got_offset (acfg, TRUE, ji);
11365 acfg->nshared_got_entries = acfg->got_offset;
11369 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11371 MonoImage *image = ass->image;
11374 MonoAotCompile *acfg;
11375 char *outfile_name, *tmp_outfile_name, *p;
11376 char llvm_stats_msg [256];
11380 acfg = acfg_create (ass, opts);
11382 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
11383 acfg->aot_opts.write_symbols = TRUE;
11384 acfg->aot_opts.ntrampolines = 4096;
11385 acfg->aot_opts.nrgctx_trampolines = 4096;
11386 acfg->aot_opts.nimt_trampolines = 512;
11387 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
11388 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
11389 acfg->aot_opts.llvm_path = g_strdup ("");
11390 acfg->aot_opts.temp_path = g_strdup ("");
11392 acfg->aot_opts.use_trampolines_page = TRUE;
11395 mono_aot_parse_options (aot_options, &acfg->aot_opts);
11397 if (acfg->aot_opts.logfile) {
11398 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
11401 if (acfg->aot_opts.data_outfile) {
11402 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
11403 if (!acfg->data_outfile) {
11404 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
11407 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
11410 //acfg->aot_opts.print_skipped_methods = TRUE;
11412 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
11413 if (acfg->opts & MONO_OPT_GSHAREDVT) {
11414 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
11417 if (acfg->aot_opts.llvm_only) {
11418 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
11422 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11423 acfg->opts |= MONO_OPT_GSHAREDVT;
11426 #if !defined(ENABLE_LLVM)
11427 if (acfg->aot_opts.llvm_only) {
11428 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11433 if (acfg->opts & MONO_OPT_GSHAREDVT)
11434 mono_set_generic_sharing_vt_supported (TRUE);
11436 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11438 generate_aotid ((guint8*) &acfg->image->aotid);
11440 char *aotid = mono_guid_to_string (acfg->image->aotid);
11441 aot_printf (acfg, "AOTID %s\n", aotid);
11444 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11445 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11446 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11451 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11452 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11456 if (acfg->aot_opts.static_link)
11457 acfg->aot_opts.asm_writer = TRUE;
11459 if (acfg->aot_opts.soft_debug) {
11460 MonoDebugOptions *opt = mini_get_debug_options ();
11462 opt->mdb_optimizations = TRUE;
11463 opt->gen_sdb_seq_points = TRUE;
11465 if (!mono_debug_enabled ()) {
11466 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11469 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11472 if (mono_use_llvm || acfg->aot_opts.llvm) {
11474 acfg->aot_opts.asm_writer = TRUE;
11475 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11477 if (acfg->aot_opts.soft_debug) {
11478 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11484 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11485 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11490 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11491 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11492 acfg->is_full_aot = TRUE;
11495 if (mono_threads_is_coop_enabled ())
11496 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11498 if (acfg->aot_opts.instances_logfile_path) {
11499 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11500 if (!acfg->instances_logfile) {
11501 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11506 if (acfg->aot_opts.profile_files) {
11509 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11510 load_profile_file (acfg, (char*)l->data);
11517 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11518 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11522 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11523 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11524 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11526 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11527 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11528 if (acfg->opts & MONO_OPT_GSHAREDVT)
11529 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11532 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11536 if (mono_use_llvm || acfg->aot_opts.llvm) {
11539 * Emit all LLVM code into a separate assembly/object file and link with it
11542 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11543 acfg->llvm_owriter = TRUE;
11544 } else if (acfg->aot_opts.llvm_outfile) {
11545 int len = strlen (acfg->aot_opts.llvm_outfile);
11547 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11548 acfg->llvm_owriter = TRUE;
11552 if (acfg->llvm && acfg->thumb_mixed)
11553 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11554 if (acfg->aot_opts.llvm_only)
11555 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11557 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11558 /* Get rid of characters which cannot occur in symbols */
11559 for (p = acfg->assembly_name_sym; *p; ++p) {
11560 if (!(isalnum (*p) || *p == '_'))
11564 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11565 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11566 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11568 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11569 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11572 acfg->method_index = 1;
11574 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11575 mono_set_partial_sharing_supported (TRUE);
11577 res = collect_methods (acfg);
11584 for (l = acfg->profile_data; l; l = l->next)
11585 resolve_profile_data (acfg, (ProfileData*)l->data);
11586 for (l = acfg->profile_data; l; l = l->next)
11587 add_profile_instances (acfg, (ProfileData*)l->data);
11590 acfg->cfgs_size = acfg->methods->len + 32;
11591 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11593 /* PLT offset 0 is reserved for the PLT trampoline */
11594 acfg->plt_offset = 1;
11595 add_preinit_got_slots (acfg);
11600 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11606 compile_methods (acfg);
11610 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11616 if (acfg->aot_opts.asm_only) {
11617 if (acfg->aot_opts.outfile) {
11618 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11619 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11621 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11622 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11624 g_assert (acfg->aot_opts.llvm_outfile);
11625 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11626 if (acfg->llvm_owriter)
11627 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11629 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11631 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11632 g_strdup_printf ("%s", "temp") :
11633 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11635 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11636 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11637 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11642 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11643 if (acfg->aot_opts.outfile)
11644 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11646 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11647 acfg->fp = fopen (acfg->tmpfname, "w+");
11649 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11650 acfg->fp = fdopen (i, "w+");
11652 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11653 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11657 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11659 tmp_outfile_name = NULL;
11660 outfile_name = NULL;
11662 /* Compute symbols for methods */
11663 for (i = 0; i < acfg->nmethods; ++i) {
11664 if (acfg->cfgs [i]) {
11665 MonoCompile *cfg = acfg->cfgs [i];
11666 int method_index = get_method_index (acfg, cfg->orig_method);
11668 if (COMPILE_LLVM (cfg))
11669 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11670 else if (acfg->global_symbols || acfg->llvm)
11671 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11673 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11674 cfg->asm_debug_symbol = cfg->asm_symbol;
11678 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11680 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11682 acfg->gas_line_numbers = TRUE;
11685 #ifdef EMIT_DWARF_INFO
11686 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11687 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11688 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11691 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11693 #endif /* EMIT_DWARF_INFO */
11696 mono_img_writer_emit_start (acfg->w);
11699 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11705 emit_extra_methods (acfg);
11707 emit_trampolines (acfg);
11709 emit_class_name_table (acfg);
11711 emit_got_info (acfg, FALSE);
11713 emit_got_info (acfg, TRUE);
11715 emit_exception_info (acfg);
11717 emit_unwind_info (acfg);
11719 emit_class_info (acfg);
11723 emit_image_table (acfg);
11729 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11732 const char *gc_name = mono_gc_get_gc_name ();
11733 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11738 emit_objc_selectors (acfg);
11740 emit_globals (acfg);
11742 emit_file_info (acfg);
11744 emit_library_info (acfg);
11747 emit_dwarf_info (acfg);
11748 mono_dwarf_writer_close (acfg->dwarf);
11751 emit_mem_end (acfg);
11753 if (acfg->need_pt_gnu_stack) {
11754 /* This is required so the .so doesn't have an executable stack */
11755 /* The bin writer already emits this */
11756 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11759 if (acfg->aot_opts.data_outfile)
11760 fclose (acfg->data_outfile);
11766 res = emit_llvm_file (acfg);
11774 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11777 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11779 strcpy (llvm_stats_msg, "");
11781 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;
11783 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",
11784 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11785 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11786 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11787 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11788 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11789 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,
11790 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11791 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11792 (int)(acfg->got_offset * sizeof (gpointer)));
11793 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11794 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11796 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11797 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11798 if (acfg->stats.genericcount)
11799 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11800 if (acfg->stats.abscount)
11801 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11802 if (acfg->stats.lmfcount)
11803 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11804 if (acfg->stats.ocount)
11805 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11809 res = mono_img_writer_emit_writeout (acfg->w);
11814 res = compile_asm (acfg);
11821 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11823 if (acfg->aot_opts.stats) {
11826 aot_printf (acfg, "GOT slot distribution:\n");
11827 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11828 if (acfg->stats.got_slot_types [i])
11829 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]);
11830 aot_printf (acfg, "\nMethod stats:\n");
11831 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11832 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11833 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11834 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11837 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);
11839 if (acfg->aot_opts.dump_json)
11852 mono_aot_readonly_field_override (MonoClassField *field)
11858 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11864 mono_aot_is_shared_got_offset (int offset)