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/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->flags == MONO_EXCEPTION_CLAUSE_FILTER || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)) {
6138 if (clause->data.catch_class) {
6142 buf2 = (guint8 *)g_malloc (4096);
6144 encode_klass_ref (acfg, clause->data.catch_class, p2, &p2);
6146 g_assert (len < 4096);
6147 encode_value (len, p, &p);
6148 memcpy (p, buf2, len);
6152 encode_value (0, p, &p);
6156 /* Emit the IL ranges too, since they might not be available at runtime */
6157 encode_value (clause->try_offset, p, &p);
6158 encode_value (clause->try_len, p, &p);
6159 encode_value (clause->handler_offset, p, &p);
6160 encode_value (clause->handler_len, p, &p);
6162 /* Emit a list of nesting clauses */
6163 for (i = 0; i < header->num_clauses; ++i) {
6165 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6167 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6169 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6170 encode_value (i, p, &p);
6172 encode_value (-1, p, &p);
6175 if (jinfo->num_clauses)
6176 encode_value (jinfo->num_clauses, p, &p);
6178 for (k = 0; k < jinfo->num_clauses; ++k) {
6179 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6181 encode_value (ei->flags, p, &p);
6182 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6183 /* Not used for catch clauses */
6184 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6185 encode_value (ei->exvar_offset, p, &p);
6187 encode_value (ei->exvar_offset, p, &p);
6190 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6191 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6193 if (ei->data.catch_class) {
6197 buf2 = (guint8 *)g_malloc (4096);
6199 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6201 g_assert (len < 4096);
6202 encode_value (len, p, &p);
6203 memcpy (p, buf2, len);
6207 encode_value (0, p, &p);
6211 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6212 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6213 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6217 if (jinfo->has_try_block_holes) {
6218 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6219 for (i = 0; i < table->num_holes; ++i) {
6220 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6221 encode_value (hole->clause, p, &p);
6222 encode_value (hole->length, p, &p);
6223 encode_value (hole->offset, p, &p);
6227 if (jinfo->has_arch_eh_info) {
6228 MonoArchEHJitInfo *eh_info;
6230 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6231 encode_value (eh_info->stack_size, p, &p);
6232 encode_value (eh_info->epilog_size, p, &p);
6235 if (jinfo->has_generic_jit_info) {
6236 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6237 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6241 encode_value (gi->nlocs, p, &p);
6243 for (i = 0; i < gi->nlocs; ++i) {
6244 MonoDwarfLocListEntry *entry = &gi->locations [i];
6246 encode_value (entry->is_reg ? 1 : 0, p, &p);
6247 encode_value (entry->reg, p, &p);
6249 encode_value (entry->offset, p, &p);
6251 g_assert (entry->from == 0);
6253 encode_value (entry->from, p, &p);
6254 encode_value (entry->to, p, &p);
6257 if (!cfg->compile_llvm) {
6258 encode_value (gi->has_this ? 1 : 0, p, &p);
6259 encode_value (gi->this_reg, p, &p);
6260 encode_value (gi->this_offset, p, &p);
6265 * Need to encode jinfo->method too, since it is not equal to 'method'
6266 * when using generic sharing.
6268 buf2 = (guint8 *)g_malloc (4096);
6270 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6272 g_assert (len < 4096);
6273 encode_value (len, p, &p);
6274 memcpy (p, buf2, len);
6278 if (gsctx && gsctx->is_gsharedvt) {
6279 encode_value (1, p, &p);
6281 encode_value (0, p, &p);
6285 if (seq_points_size)
6286 p += mono_seq_point_info_write (seq_points, p);
6288 g_assert (debug_info_size < buf_size);
6290 encode_value (debug_info_size, p, &p);
6291 if (debug_info_size) {
6292 memcpy (p, debug_info, debug_info_size);
6293 p += debug_info_size;
6294 g_free (debug_info);
6299 encode_value (cfg->gc_map_size, p, &p);
6300 /* The GC map requires 4 bytes of alignment */
6301 while ((gsize)p % 4)
6303 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6304 p += cfg->gc_map_size;
6307 acfg->stats.ex_info_size += p - buf;
6309 g_assert (p - buf < buf_size);
6312 /* The GC Map requires 4 byte alignment */
6313 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6318 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6321 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6323 int i, buf_size, res;
6324 gboolean no_special_static, cant_encode;
6325 gpointer iter = NULL;
6328 mono_error_cleanup (&error);
6332 p = buf = (guint8 *)g_malloc (buf_size);
6334 /* Mark as unusable */
6335 encode_value (-1, p, &p);
6337 res = add_to_blob (acfg, buf, p - buf);
6343 buf_size = 10240 + (klass->vtable_size * 16);
6344 p = buf = (guint8 *)g_malloc (buf_size);
6348 mono_class_init (klass);
6350 mono_class_get_nested_types (klass, &iter);
6351 g_assert (klass->nested_classes_inited);
6353 mono_class_setup_vtable (klass);
6356 * Emit all the information which is required for creating vtables so
6357 * the runtime does not need to create the MonoMethod structures which
6358 * take up a lot of space.
6361 no_special_static = !mono_class_has_special_static_fields (klass);
6363 /* Check whenever we have enough info to encode the vtable */
6364 cant_encode = FALSE;
6365 for (i = 0; i < klass->vtable_size; ++i) {
6366 MonoMethod *cm = klass->vtable [i];
6368 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6372 mono_class_has_finalizer (klass);
6373 if (mono_class_has_failure (klass))
6376 if (mono_class_is_gtd (klass) || cant_encode) {
6377 encode_value (-1, p, &p);
6379 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6380 encode_value (klass->vtable_size, p, &p);
6381 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);
6382 if (klass->has_cctor)
6383 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6384 if (klass->has_finalize)
6385 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6387 encode_value (klass->instance_size, p, &p);
6388 encode_value (mono_class_data_size (klass), p, &p);
6389 encode_value (klass->packing_size, p, &p);
6390 encode_value (klass->min_align, p, &p);
6392 for (i = 0; i < klass->vtable_size; ++i) {
6393 MonoMethod *cm = klass->vtable [i];
6396 encode_method_ref (acfg, cm, p, &p);
6398 encode_value (0, p, &p);
6402 acfg->stats.class_info_size += p - buf;
6404 g_assert (p - buf < buf_size);
6405 res = add_to_blob (acfg, buf, p - buf);
6412 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6414 char *debug_sym = NULL;
6417 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6418 /* Need to add a prefix to create unique symbols */
6419 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6421 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6422 prefix = mangle_symbol_alloc ("plt_");
6424 prefix = g_strdup ("plt_");
6429 case MONO_PATCH_INFO_METHOD:
6430 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6432 case MONO_PATCH_INFO_INTERNAL_METHOD:
6433 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6435 case MONO_PATCH_INFO_RGCTX_FETCH:
6436 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6438 case MONO_PATCH_INFO_ICALL_ADDR:
6439 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6440 char *s = get_debug_sym (ji->data.method, "", cache);
6442 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6446 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6447 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6455 return sanitize_symbol (acfg, debug_sym);
6459 * Calls made from AOTed code are routed through a table of jumps similar to the
6460 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6461 * control to the AOT runtime through a trampoline.
6464 emit_plt (MonoAotCompile *acfg)
6468 if (acfg->aot_opts.llvm_only) {
6469 g_assert (acfg->plt_offset == 1);
6475 emit_section_change (acfg, ".text", 0);
6476 emit_alignment_code (acfg, 16);
6477 emit_info_symbol (acfg, "plt");
6478 emit_label (acfg, acfg->plt_symbol);
6480 for (i = 0; i < acfg->plt_offset; ++i) {
6481 char *debug_sym = NULL;
6482 MonoPltEntry *plt_entry = NULL;
6486 * The first plt entry is unused.
6490 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6492 debug_sym = plt_entry->debug_sym;
6494 if (acfg->thumb_mixed && !plt_entry->jit_used)
6495 /* Emit only a thumb version */
6498 /* Skip plt entries not actually called */
6499 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6502 if (acfg->llvm && !acfg->thumb_mixed) {
6503 emit_label (acfg, plt_entry->llvm_symbol);
6505 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6506 #if defined(TARGET_MACH)
6507 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6513 if (acfg->need_no_dead_strip) {
6514 emit_unset_mode (acfg);
6515 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6517 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6518 emit_label (acfg, debug_sym);
6521 emit_label (acfg, plt_entry->symbol);
6523 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6526 emit_symbol_size (acfg, debug_sym, ".");
6529 if (acfg->thumb_mixed) {
6530 /* Make sure the ARM symbols don't alias the thumb ones */
6531 emit_zero_bytes (acfg, 16);
6534 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6537 for (i = 0; i < acfg->plt_offset; ++i) {
6538 char *debug_sym = NULL;
6539 MonoPltEntry *plt_entry = NULL;
6544 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6546 /* Skip plt entries not actually called by LLVM code */
6547 if (!plt_entry->llvm_used)
6550 if (acfg->aot_opts.write_symbols) {
6551 if (plt_entry->debug_sym)
6552 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6556 #if defined(TARGET_MACH)
6557 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6558 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6560 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6561 emit_label (acfg, debug_sym);
6563 fprintf (acfg->fp, "\n.thumb_func\n");
6565 emit_label (acfg, plt_entry->llvm_symbol);
6568 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6570 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6573 emit_symbol_size (acfg, debug_sym, ".");
6579 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6581 emit_info_symbol (acfg, "plt_end");
6585 * emit_trampoline_full:
6587 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6588 * create_jit_info_for_trampoline ().
6590 static G_GNUC_UNUSED void
6591 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6593 char start_symbol [MAX_SYMBOL_SIZE];
6594 char end_symbol [MAX_SYMBOL_SIZE];
6595 char symbol [MAX_SYMBOL_SIZE];
6596 guint32 buf_size, info_offset;
6597 MonoJumpInfo *patch_info;
6610 code_size = info->code_size;
6612 unwind_ops = info->unwind_ops;
6616 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6618 emit_section_change (acfg, ".text", 0);
6619 emit_global (acfg, start_symbol, TRUE);
6620 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6621 emit_label (acfg, start_symbol);
6623 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6624 emit_label (acfg, symbol);
6627 * The code should access everything through the GOT, so we pass
6630 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6632 emit_symbol_size (acfg, start_symbol, ".");
6635 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6636 emit_label (acfg, end_symbol);
6641 /* Sort relocations */
6642 patches = g_ptr_array_new ();
6643 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6644 if (patch_info->type != MONO_PATCH_INFO_NONE)
6645 g_ptr_array_add (patches, patch_info);
6646 g_ptr_array_sort (patches, compare_patches);
6648 buf_size = patches->len * 128 + 128;
6649 buf = (guint8 *)g_malloc (buf_size);
6652 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6653 g_assert (p - buf < buf_size);
6654 g_ptr_array_free (patches, TRUE);
6656 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6658 info_offset = add_to_blob (acfg, buf, p - buf);
6660 emit_section_change (acfg, RODATA_SECT, 0);
6661 emit_global (acfg, symbol, FALSE);
6662 emit_label (acfg, symbol);
6664 emit_int32 (acfg, info_offset);
6668 guint32 encoded_len;
6672 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6674 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6675 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6678 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6679 emit_int32 (acfg, uw_offset);
6682 /* Emit debug info */
6684 char symbol2 [MAX_SYMBOL_SIZE];
6686 sprintf (symbol, "%s", name);
6687 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6690 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6696 static G_GNUC_UNUSED void
6697 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6699 emit_trampoline_full (acfg, got_offset, info, TRUE);
6703 emit_trampolines (MonoAotCompile *acfg)
6705 char symbol [MAX_SYMBOL_SIZE];
6706 char end_symbol [MAX_SYMBOL_SIZE];
6707 int i, tramp_got_offset;
6709 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6713 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6716 g_assert (acfg->image->assembly);
6718 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6719 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6720 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6721 MonoTrampInfo *info;
6724 * Emit the generic trampolines.
6726 * We could save some code by treating the generic trampolines as a wrapper
6727 * method, but that approach has its own complexities, so we choose the simpler
6730 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6731 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6732 #ifdef DISABLE_REMOTING
6733 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6736 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6737 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6740 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6741 emit_trampoline (acfg, acfg->got_offset, info);
6744 /* Emit the exception related code pieces */
6745 mono_arch_get_restore_context (&info, TRUE);
6746 emit_trampoline (acfg, acfg->got_offset, info);
6747 mono_arch_get_call_filter (&info, TRUE);
6748 emit_trampoline (acfg, acfg->got_offset, info);
6749 mono_arch_get_throw_exception (&info, TRUE);
6750 emit_trampoline (acfg, acfg->got_offset, info);
6751 mono_arch_get_rethrow_exception (&info, TRUE);
6752 emit_trampoline (acfg, acfg->got_offset, info);
6753 mono_arch_get_throw_corlib_exception (&info, TRUE);
6754 emit_trampoline (acfg, acfg->got_offset, info);
6756 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6757 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6758 emit_trampoline (acfg, acfg->got_offset, info);
6759 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6760 emit_trampoline (acfg, acfg->got_offset, info);
6763 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6764 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6766 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6768 /* Create a separate out trampoline for more information in stack traces */
6769 info->name = g_strdup ("gsharedvt_out_trampoline");
6770 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6774 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6776 GSList *l = mono_arch_get_trampolines (TRUE);
6779 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6781 emit_trampoline (acfg, acfg->got_offset, info);
6787 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6790 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6791 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6792 emit_trampoline (acfg, acfg->got_offset, info);
6795 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6796 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6797 emit_trampoline (acfg, acfg->got_offset, info);
6801 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6802 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6803 emit_trampoline (acfg, acfg->got_offset, info);
6809 /* delegate_invoke_impl trampolines */
6810 l = mono_arch_get_delegate_invoke_impls ();
6812 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6814 emit_trampoline (acfg, acfg->got_offset, info);
6819 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6820 mono_arch_create_handler_block_trampoline (&info, TRUE);
6821 emit_trampoline (acfg, acfg->got_offset, info);
6824 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6826 /* Emit trampolines which are numerous */
6829 * These include the following:
6830 * - specific trampolines
6831 * - static rgctx invoke trampolines
6833 * These trampolines have the same code, they are parameterized by GOT
6835 * They are defined in this file, in the arch_... routines instead of
6836 * in tramp-<ARCH>.c, since it is easier to do it this way.
6840 * When running in aot-only mode, we can't create specific trampolines at
6841 * runtime, so we create a few, and save them in the AOT file.
6842 * Normal trampolines embed their argument as a literal inside the
6843 * trampoline code, we can't do that here, so instead we embed an offset
6844 * which needs to be added to the trampoline address to get the address of
6845 * the GOT slot which contains the argument value.
6846 * The generated trampolines jump to the generic trampolines using another
6847 * GOT slot, which will be setup by the AOT loader to point to the
6848 * generic trampoline code of the given type.
6852 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6856 emit_section_change (acfg, ".text", 0);
6858 tramp_got_offset = acfg->got_offset;
6860 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6862 case MONO_AOT_TRAMP_SPECIFIC:
6863 sprintf (symbol, "specific_trampolines");
6865 case MONO_AOT_TRAMP_STATIC_RGCTX:
6866 sprintf (symbol, "static_rgctx_trampolines");
6868 case MONO_AOT_TRAMP_IMT:
6869 sprintf (symbol, "imt_trampolines");
6871 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6872 sprintf (symbol, "gsharedvt_arg_trampolines");
6875 g_assert_not_reached ();
6878 sprintf (end_symbol, "%s_e", symbol);
6880 if (acfg->aot_opts.write_symbols)
6881 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6883 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6884 emit_info_symbol (acfg, symbol);
6886 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6888 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6892 case MONO_AOT_TRAMP_SPECIFIC:
6893 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6894 tramp_got_offset += 2;
6896 case MONO_AOT_TRAMP_STATIC_RGCTX:
6897 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6898 tramp_got_offset += 2;
6900 case MONO_AOT_TRAMP_IMT:
6901 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6902 tramp_got_offset += 1;
6904 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6905 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6906 tramp_got_offset += 2;
6909 g_assert_not_reached ();
6911 if (!acfg->trampoline_size [ntype]) {
6912 g_assert (tramp_size);
6913 acfg->trampoline_size [ntype] = tramp_size;
6917 emit_label (acfg, end_symbol);
6918 emit_int32 (acfg, 0);
6921 arch_emit_specific_trampoline_pages (acfg);
6923 /* Reserve some entries at the end of the GOT for our use */
6924 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6927 acfg->got_offset += acfg->num_trampoline_got_entries;
6931 str_begins_with (const char *str1, const char *str2)
6933 int len = strlen (str2);
6934 return strncmp (str1, str2, len) == 0;
6938 mono_aot_readonly_field_override (MonoClassField *field)
6941 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6942 char *p = rdv->name;
6944 len = strlen (field->parent->name_space);
6945 if (strncmp (p, field->parent->name_space, len))
6950 len = strlen (field->parent->name);
6951 if (strncmp (p, field->parent->name, len))
6956 if (strcmp (p, field->name))
6958 switch (rdv->type) {
6960 return &rdv->value.i1;
6962 return &rdv->value.i2;
6964 return &rdv->value.i4;
6973 add_readonly_value (MonoAotOptions *opts, const char *val)
6978 /* the format of val is:
6979 * namespace.typename.fieldname=type/value
6980 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6982 fval = strrchr (val, '/');
6984 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6987 tval = strrchr (val, '=');
6989 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6992 rdv = g_new0 (ReadOnlyValue, 1);
6993 rdv->name = (char *)g_malloc0 (tval - val + 1);
6994 memcpy (rdv->name, val, tval - val);
6997 if (strncmp (tval, "i1", 2) == 0) {
6998 rdv->value.i1 = atoi (fval);
6999 rdv->type = MONO_TYPE_I1;
7000 } else if (strncmp (tval, "i2", 2) == 0) {
7001 rdv->value.i2 = atoi (fval);
7002 rdv->type = MONO_TYPE_I2;
7003 } else if (strncmp (tval, "i4", 2) == 0) {
7004 rdv->value.i4 = atoi (fval);
7005 rdv->type = MONO_TYPE_I4;
7007 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
7010 rdv->next = readonly_values;
7011 readonly_values = rdv;
7015 clean_path (gchar * path)
7020 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7023 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7030 wrap_path (gchar * path)
7036 // If the string contains no spaces, just return the original string.
7037 if (strstr (path, " ") == NULL)
7040 // If the string is already wrapped in quotes, return it.
7041 len = strlen (path);
7042 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7045 // If the string contains spaces, then wrap it in quotes.
7046 gchar *clean = g_strdup_printf ("\"%s\"", path);
7051 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7053 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7055 ptrdiff_t len = end-start;
7057 g_ptr_array_add (args, g_strndup (start, len));
7061 mono_aot_split_options (const char *aot_options)
7063 enum MonoAotOptionState {
7064 MONO_AOT_OPTION_STATE_DEFAULT,
7065 MONO_AOT_OPTION_STATE_STRING,
7066 MONO_AOT_OPTION_STATE_ESCAPE,
7069 GPtrArray *args = g_ptr_array_new ();
7070 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7071 gchar const *opt_start = aot_options;
7072 gboolean end_of_string = FALSE;
7075 g_return_val_if_fail (aot_options != NULL, NULL);
7077 while ((cur = *aot_options) != '\0') {
7078 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7083 // If we find a quote, then if we're in the default case then
7084 // it means we've found the start of a string, if not then it
7085 // means we've found the end of the string and should switch
7086 // back to the default case.
7088 case MONO_AOT_OPTION_STATE_DEFAULT:
7089 state = MONO_AOT_OPTION_STATE_STRING;
7091 case MONO_AOT_OPTION_STATE_STRING:
7092 state = MONO_AOT_OPTION_STATE_DEFAULT;
7094 case MONO_AOT_OPTION_STATE_ESCAPE:
7095 g_assert_not_reached ();
7100 // If we've found an escaping operator, then this means we
7101 // should not process the next character if inside a string.
7102 if (state == MONO_AOT_OPTION_STATE_STRING)
7103 state = MONO_AOT_OPTION_STATE_ESCAPE;
7106 // If we're in the default state then this means we've found
7107 // an option, store it for later processing.
7108 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7116 // If the next character is end of string, then process the last option.
7117 if (*(aot_options) == '\0') {
7118 end_of_string = TRUE;
7124 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7125 opt_start = ++aot_options;
7128 goto restart; // Check for null and continue loop
7135 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7139 args = mono_aot_split_options (aot_options ? aot_options : "");
7140 for (int i = 0; i < args->len; ++i) {
7141 const char *arg = (const char *)g_ptr_array_index (args, i);
7143 if (str_begins_with (arg, "outfile=")) {
7144 opts->outfile = g_strdup (arg + strlen ("outfile="));
7145 } else if (str_begins_with (arg, "llvm-outfile=")) {
7146 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7147 } else if (str_begins_with (arg, "temp-path=")) {
7148 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7149 } else if (str_begins_with (arg, "save-temps")) {
7150 opts->save_temps = TRUE;
7151 } else if (str_begins_with (arg, "keep-temps")) {
7152 opts->save_temps = TRUE;
7153 } else if (str_begins_with (arg, "write-symbols")) {
7154 opts->write_symbols = TRUE;
7155 } else if (str_begins_with (arg, "no-write-symbols")) {
7156 opts->write_symbols = FALSE;
7157 // Intentionally undocumented -- one-off experiment
7158 } else if (str_begins_with (arg, "metadata-only")) {
7159 opts->metadata_only = TRUE;
7160 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7161 opts->bind_to_runtime_version = TRUE;
7162 } else if (str_begins_with (arg, "full")) {
7163 opts->mode = MONO_AOT_MODE_FULL;
7164 } else if (str_begins_with (arg, "hybrid")) {
7165 opts->mode = MONO_AOT_MODE_HYBRID;
7166 } else if (str_begins_with (arg, "threads=")) {
7167 opts->nthreads = atoi (arg + strlen ("threads="));
7168 } else if (str_begins_with (arg, "static")) {
7169 opts->static_link = TRUE;
7170 opts->no_dlsym = TRUE;
7171 } else if (str_begins_with (arg, "asmonly")) {
7172 opts->asm_only = TRUE;
7173 } else if (str_begins_with (arg, "asmwriter")) {
7174 opts->asm_writer = TRUE;
7175 } else if (str_begins_with (arg, "nodebug")) {
7176 opts->nodebug = TRUE;
7177 } else if (str_begins_with (arg, "dwarfdebug")) {
7178 opts->dwarf_debug = TRUE;
7179 // Intentionally undocumented -- No one remembers what this does. It appears to be ARM-only
7180 } else if (str_begins_with (arg, "nopagetrampolines")) {
7181 opts->use_trampolines_page = FALSE;
7182 } else if (str_begins_with (arg, "ntrampolines=")) {
7183 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7184 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7185 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7186 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7187 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7188 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7189 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7190 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7191 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7192 } else if (str_begins_with (arg, "tool-prefix=")) {
7193 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7194 } else if (str_begins_with (arg, "ld-flags=")) {
7195 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7196 } else if (str_begins_with (arg, "soft-debug")) {
7197 opts->soft_debug = TRUE;
7198 // Intentionally undocumented x2-- deprecated
7199 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7200 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7201 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7202 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7203 } else if (str_begins_with (arg, "msym-dir=")) {
7204 debug_options.no_seq_points_compact_data = FALSE;
7205 opts->gen_msym_dir = TRUE;
7206 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7207 } else if (str_begins_with (arg, "direct-pinvoke")) {
7208 opts->direct_pinvoke = TRUE;
7209 } else if (str_begins_with (arg, "direct-icalls")) {
7210 opts->direct_icalls = TRUE;
7211 } else if (str_begins_with (arg, "no-direct-calls")) {
7212 opts->no_direct_calls = TRUE;
7213 } else if (str_begins_with (arg, "print-skipped")) {
7214 opts->print_skipped_methods = TRUE;
7215 } else if (str_begins_with (arg, "stats")) {
7217 // Intentionally undocumented-- has no known function other than to debug the compiler
7218 } else if (str_begins_with (arg, "no-instances")) {
7219 opts->no_instances = TRUE;
7220 // Intentionally undocumented x4-- Used for internal debugging of compiler
7221 } else if (str_begins_with (arg, "log-generics")) {
7222 opts->log_generics = TRUE;
7223 } else if (str_begins_with (arg, "log-instances=")) {
7224 opts->log_instances = TRUE;
7225 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7226 } else if (str_begins_with (arg, "log-instances")) {
7227 opts->log_instances = TRUE;
7228 } else if (str_begins_with (arg, "internal-logfile=")) {
7229 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7230 } else if (str_begins_with (arg, "mtriple=")) {
7231 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7232 } else if (str_begins_with (arg, "llvm-path=")) {
7233 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7234 } else if (!strcmp (arg, "llvm")) {
7236 } else if (str_begins_with (arg, "readonly-value=")) {
7237 add_readonly_value (opts, arg + strlen ("readonly-value="));
7238 } else if (str_begins_with (arg, "info")) {
7239 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7241 // Intentionally undocumented: Used for precise stack maps, which are not available yet
7242 } else if (str_begins_with (arg, "gc-maps")) {
7243 mini_gc_enable_gc_maps_for_aot ();
7244 // Intentionally undocumented: Used for internal debugging
7245 } else if (str_begins_with (arg, "dump")) {
7246 opts->dump_json = TRUE;
7247 } else if (str_begins_with (arg, "llvmonly")) {
7248 opts->mode = MONO_AOT_MODE_FULL;
7250 opts->llvm_only = TRUE;
7251 } else if (str_begins_with (arg, "data-outfile=")) {
7252 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7253 } else if (str_begins_with (arg, "profile=")) {
7254 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7255 } else if (!strcmp (arg, "profile-only")) {
7256 opts->profile_only = TRUE;
7257 } else if (!strcmp (arg, "verbose")) {
7258 opts->verbose = TRUE;
7259 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7260 printf ("Supported options for --aot:\n");
7261 printf (" asmonly\n");
7262 printf (" bind-to-runtime-version\n");
7263 printf (" bitcode\n");
7264 printf (" data-outfile=\n");
7265 printf (" direct-icalls\n");
7266 printf (" direct-pinvoke\n");
7267 printf (" dwarfdebug\n");
7269 printf (" hybrid\n");
7271 printf (" keep-temps\n");
7273 printf (" llvmonly\n");
7274 printf (" llvm-outfile=\n");
7275 printf (" llvm-path=\n");
7276 printf (" msym-dir=\n");
7277 printf (" mtriple\n");
7278 printf (" nimt-trampolines=\n");
7279 printf (" nodebug\n");
7280 printf (" no-direct-calls\n");
7281 printf (" no-write-symbols\n");
7282 printf (" nrgctx-trampolines=\n");
7283 printf (" nrgctx-fetch-trampolines=\n");
7284 printf (" ngsharedvt-trampolines=\n");
7285 printf (" ntrampolines=\n");
7286 printf (" outfile=\n");
7287 printf (" profile=\n");
7288 printf (" profile-only\n");
7289 printf (" print-skipped-methods\n");
7290 printf (" readonly-value=\n");
7291 printf (" save-temps\n");
7292 printf (" soft-debug\n");
7293 printf (" static\n");
7294 printf (" stats\n");
7295 printf (" temp-path=\n");
7296 printf (" tool-prefix=\n");
7297 printf (" threads=\n");
7298 printf (" write-symbols\n");
7299 printf (" verbose\n");
7300 printf (" help/?\n");
7303 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7307 g_free ((gpointer) arg);
7310 if (opts->use_trampolines_page) {
7311 opts->ntrampolines = 0;
7312 opts->nrgctx_trampolines = 0;
7313 opts->nimt_trampolines = 0;
7314 opts->ngsharedvt_arg_trampolines = 0;
7317 g_ptr_array_free (args, /*free_seg=*/TRUE);
7321 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7323 MonoMethod *method = (MonoMethod*)key;
7324 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7325 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7326 MonoJumpInfoToken *new_ji;
7328 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7329 new_ji->image = ji->image;
7330 new_ji->token = ji->token;
7331 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7335 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7337 if (klass->type_token)
7339 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7342 return can_encode_class (acfg, klass->element_class);
7347 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7349 if (method->wrapper_type) {
7350 switch (method->wrapper_type) {
7351 case MONO_WRAPPER_NONE:
7352 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7353 case MONO_WRAPPER_XDOMAIN_INVOKE:
7354 case MONO_WRAPPER_STFLD:
7355 case MONO_WRAPPER_LDFLD:
7356 case MONO_WRAPPER_LDFLDA:
7357 case MONO_WRAPPER_STELEMREF:
7358 case MONO_WRAPPER_PROXY_ISINST:
7359 case MONO_WRAPPER_ALLOC:
7360 case MONO_WRAPPER_REMOTING_INVOKE:
7361 case MONO_WRAPPER_UNKNOWN:
7362 case MONO_WRAPPER_WRITE_BARRIER:
7363 case MONO_WRAPPER_DELEGATE_INVOKE:
7364 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7365 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7366 case MONO_WRAPPER_SYNCHRONIZED:
7368 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7369 case MONO_WRAPPER_CASTCLASS: {
7370 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7379 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7383 if (!method->token) {
7384 /* The method is part of a constructed type like Int[,].Set (). */
7385 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7386 if (method->klass->rank)
7396 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7398 switch (patch_info->type) {
7399 case MONO_PATCH_INFO_METHOD:
7400 case MONO_PATCH_INFO_METHODCONST:
7401 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7402 MonoMethod *method = patch_info->data.method;
7404 return can_encode_method (acfg, method);
7406 case MONO_PATCH_INFO_VTABLE:
7407 case MONO_PATCH_INFO_CLASS:
7408 case MONO_PATCH_INFO_IID:
7409 case MONO_PATCH_INFO_ADJUSTED_IID:
7410 if (!can_encode_class (acfg, patch_info->data.klass)) {
7411 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7415 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7416 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7417 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7422 case MONO_PATCH_INFO_RGCTX_FETCH:
7423 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7424 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7426 if (!can_encode_method (acfg, entry->method))
7428 if (!can_encode_patch (acfg, entry->data))
7440 is_concrete_type (MonoType *t)
7445 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7447 if (t->type == MONO_TYPE_GENERICINST) {
7448 MonoGenericContext *orig_ctx;
7449 MonoGenericInst *inst;
7452 if (!MONO_TYPE_ISSTRUCT (t))
7454 klass = mono_class_from_mono_type (t);
7455 orig_ctx = &mono_class_get_generic_class (klass)->context;
7457 inst = orig_ctx->class_inst;
7459 for (i = 0; i < inst->type_argc; ++i) {
7460 arg = mini_get_underlying_type (inst->type_argv [i]);
7461 if (!is_concrete_type (arg))
7465 inst = orig_ctx->method_inst;
7467 for (i = 0; i < inst->type_argc; ++i) {
7468 arg = mini_get_underlying_type (inst->type_argv [i]);
7469 if (!is_concrete_type (arg))
7477 /* LOCKING: Assumes the loader lock is held */
7479 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7481 MonoMethod *wrapper;
7482 gboolean concrete = TRUE;
7483 gboolean add_in = gsharedvt_in;
7484 gboolean add_out = gsharedvt_out;
7486 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7488 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7491 if (!add_in && !add_out)
7494 if (mini_is_gsharedvt_variable_signature (sig))
7498 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7500 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7502 if (!sig->has_type_parameters) {
7503 //printf ("%s\n", mono_signature_full_name (sig));
7506 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7507 add_extra_method (acfg, wrapper);
7509 if (gsharedvt_out) {
7510 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7511 add_extra_method (acfg, wrapper);
7514 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7515 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7518 //printf ("%s\n", mono_signature_full_name (sig));
7520 copy->ret = mini_get_underlying_type (sig->ret);
7521 if (!is_concrete_type (copy->ret))
7523 for (i = 0; i < sig->param_count; ++i) {
7524 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7525 if (!is_concrete_type (copy->params [i]))
7529 copy->has_type_parameters = 0;
7532 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7533 add_extra_method (acfg, wrapper);
7536 if (gsharedvt_out) {
7537 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7538 add_extra_method (acfg, wrapper);
7541 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7549 * AOT compile a given method.
7550 * This function might be called by multiple threads, so it must be thread-safe.
7553 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7556 MonoJumpInfo *patch_info;
7559 MonoMethod *wrapped;
7563 if (acfg->aot_opts.metadata_only)
7566 mono_acfg_lock (acfg);
7567 index = get_method_index (acfg, method);
7568 mono_acfg_unlock (acfg);
7570 /* fixme: maybe we can also precompile wrapper methods */
7571 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7572 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7573 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7574 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7578 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7581 wrapped = mono_marshal_method_from_wrapper (method);
7582 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7583 // FIXME: The wrapper should be generic too, but it is not
7586 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7589 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7592 InterlockedIncrement (&acfg->stats.mcount);
7595 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7596 InterlockedIncrement (&acfg->stats.genericcount);
7601 //acfg->aot_opts.print_skipped_methods = TRUE;
7604 * Since these methods are the only ones which are compiled with
7605 * AOT support, and they are not used by runtime startup/shutdown code,
7606 * the runtime will not see AOT methods during AOT compilation,so it
7607 * does not need to support them by creating a fake GOT etc.
7609 flags = JIT_FLAG_AOT;
7610 if (mono_aot_mode_is_full (&acfg->aot_opts))
7611 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7613 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7614 if (acfg->aot_opts.llvm_only)
7615 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7616 if (acfg->aot_opts.no_direct_calls)
7617 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7618 if (acfg->aot_opts.direct_pinvoke)
7619 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7621 jit_timer = mono_time_track_start ();
7622 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7623 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7625 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7626 if (acfg->aot_opts.print_skipped_methods)
7627 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7628 InterlockedIncrement (&acfg->stats.genericcount);
7631 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7632 /* Some instances cannot be JITted due to constraints etc. */
7633 if (!method->is_inflated)
7634 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));
7635 /* Let the exception happen at runtime */
7639 if (cfg->disable_aot) {
7640 if (acfg->aot_opts.print_skipped_methods)
7641 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7642 InterlockedIncrement (&acfg->stats.ocount);
7645 cfg->method_index = index;
7647 /* Nullify patches which need no aot processing */
7648 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7649 switch (patch_info->type) {
7650 case MONO_PATCH_INFO_LABEL:
7651 case MONO_PATCH_INFO_BB:
7652 patch_info->type = MONO_PATCH_INFO_NONE;
7659 /* Collect method->token associations from the cfg */
7660 mono_acfg_lock (acfg);
7661 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7662 mono_acfg_unlock (acfg);
7663 g_hash_table_destroy (cfg->token_info_hash);
7664 cfg->token_info_hash = NULL;
7667 * Check for absolute addresses.
7670 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7671 switch (patch_info->type) {
7672 case MONO_PATCH_INFO_ABS:
7673 /* unable to handle this */
7682 if (acfg->aot_opts.print_skipped_methods)
7683 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7684 InterlockedIncrement (&acfg->stats.abscount);
7688 /* Lock for the rest of the code */
7689 mono_acfg_lock (acfg);
7692 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7693 else if (cfg->gshared)
7694 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7695 else if (cfg->method->wrapper_type)
7696 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7698 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7701 * Check for methods/klasses we can't encode.
7704 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7705 if (!can_encode_patch (acfg, patch_info))
7710 if (acfg->aot_opts.print_skipped_methods)
7711 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7712 acfg->stats.ocount++;
7713 mono_acfg_unlock (acfg);
7717 if (!cfg->compile_llvm)
7718 acfg->has_jitted_code = TRUE;
7720 if (method->is_inflated && acfg->aot_opts.log_instances) {
7721 if (acfg->instances_logfile)
7722 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7724 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7727 /* Adds generic instances referenced by this method */
7729 * The depth is used to avoid infinite loops when generic virtual recursion is
7732 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7733 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7734 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7735 switch (patch_info->type) {
7736 case MONO_PATCH_INFO_RGCTX_FETCH:
7737 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7738 case MONO_PATCH_INFO_METHOD: {
7739 MonoMethod *m = NULL;
7741 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7742 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7744 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7745 m = e->data->data.method;
7747 m = patch_info->data.method;
7752 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7753 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7754 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7755 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7756 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7757 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7758 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7760 add_extra_method_with_depth (acfg, m, depth + 1);
7761 add_types_from_method_header (acfg, m);
7764 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7766 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7767 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7769 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7770 add_extra_method_with_depth (acfg, m, depth + 1);
7774 case MONO_PATCH_INFO_VTABLE: {
7775 MonoClass *klass = patch_info->data.klass;
7777 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7778 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7781 case MONO_PATCH_INFO_SFLDA: {
7782 MonoClass *klass = patch_info->data.field->parent;
7784 /* The .cctor needs to run at runtime. */
7785 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))
7786 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7795 /* Determine whenever the method has GOT slots */
7796 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7797 switch (patch_info->type) {
7798 case MONO_PATCH_INFO_GOT_OFFSET:
7799 case MONO_PATCH_INFO_NONE:
7800 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7801 case MONO_PATCH_INFO_GC_NURSERY_START:
7802 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7804 case MONO_PATCH_INFO_IMAGE:
7805 /* The assembly is stored in GOT slot 0 */
7806 if (patch_info->data.image != acfg->image)
7807 cfg->has_got_slots = TRUE;
7810 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7811 cfg->has_got_slots = TRUE;
7816 if (!cfg->has_got_slots)
7817 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7819 /* Add gsharedvt wrappers for signatures used by the method */
7820 if (acfg->aot_opts.llvm_only) {
7823 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7824 /* These only need out wrappers */
7825 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7827 for (l = cfg->signatures; l; l = l->next) {
7828 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7830 /* These only need in wrappers */
7831 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7836 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7838 /* Make a copy of the patch info which is in the mempool */
7840 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7842 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7843 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7846 patches = new_patch_info;
7848 patches_end->next = new_patch_info;
7849 patches_end = new_patch_info;
7851 cfg->patch_info = patches;
7853 /* Make a copy of the unwind info */
7855 GSList *l, *unwind_ops;
7859 for (l = cfg->unwind_ops; l; l = l->next) {
7860 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7861 memcpy (op, l->data, sizeof (MonoUnwindOp));
7862 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7864 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7866 /* Make a copy of the argument/local info */
7869 MonoInst **args, **locals;
7870 MonoMethodSignature *sig;
7871 MonoMethodHeader *header;
7874 sig = mono_method_signature (method);
7875 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7876 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7877 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7878 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7882 header = mono_method_get_header_checked (method, &error);
7883 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7884 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7885 for (i = 0; i < header->num_locals; ++i) {
7886 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7887 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7889 mono_metadata_free_mh (header);
7890 cfg->locals = locals;
7893 /* Free some fields used by cfg to conserve memory */
7894 mono_empty_compile (cfg);
7896 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7898 while (index >= acfg->cfgs_size) {
7899 MonoCompile **new_cfgs;
7902 new_size = acfg->cfgs_size * 2;
7903 new_cfgs = g_new0 (MonoCompile*, new_size);
7904 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7905 g_free (acfg->cfgs);
7906 acfg->cfgs = new_cfgs;
7907 acfg->cfgs_size = new_size;
7909 acfg->cfgs [index] = cfg;
7911 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7913 mono_update_jit_stats (cfg);
7916 if (cfg->orig_method->wrapper_type)
7917 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7920 mono_acfg_unlock (acfg);
7922 InterlockedIncrement (&acfg->stats.ccount);
7925 static mono_thread_start_return_t WINAPI
7926 compile_thread_main (gpointer user_data)
7928 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7929 GPtrArray *methods = ((GPtrArray **)user_data) [1];
7933 MonoInternalThread *internal = mono_thread_internal_current ();
7934 MonoString *str = mono_string_new_checked (mono_domain_get (), "AOT compiler", &error);
7935 mono_error_assert_ok (&error);
7936 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
7937 mono_error_assert_ok (&error);
7939 for (i = 0; i < methods->len; ++i)
7940 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7945 /* Used by the LLVM backend */
7947 mono_aot_get_got_offset (MonoJumpInfo *ji)
7949 return get_got_offset (llvm_acfg, TRUE, ji);
7953 * mono_aot_is_shared_got_offset:
7955 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7956 * when the AOT image is loaded.
7959 mono_aot_is_shared_got_offset (int offset)
7961 return offset < llvm_acfg->nshared_got_entries;
7965 mono_aot_get_method_name (MonoCompile *cfg)
7967 if (llvm_acfg->aot_opts.static_link)
7968 /* Include the assembly name too to avoid duplicate symbol errors */
7969 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7971 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7975 * mono_aot_is_linkonce_method:
7977 * Return whenever METHOD should be emitted with linkonce linkage,
7978 * eliminating duplicate copies when compiling in static mode.
7981 mono_aot_is_linkonce_method (MonoMethod *method)
7987 // FIXME: Add more cases
7988 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7990 info = mono_marshal_get_wrapper_info (method);
7991 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7998 append_mangled_type (GString *s, MonoType *t)
8001 g_string_append_printf (s, "b");
8003 case MONO_TYPE_VOID:
8004 g_string_append_printf (s, "void_");
8007 g_string_append_printf (s, "i1");
8010 g_string_append_printf (s, "u1");
8013 g_string_append_printf (s, "i2");
8016 g_string_append_printf (s, "u2");
8019 g_string_append_printf (s, "i4");
8022 g_string_append_printf (s, "u4");
8025 g_string_append_printf (s, "i8");
8028 g_string_append_printf (s, "u8");
8031 g_string_append_printf (s, "ii");
8034 g_string_append_printf (s, "ui");
8037 g_string_append_printf (s, "fl");
8040 g_string_append_printf (s, "do");
8043 char *fullname = mono_type_full_name (t);
8049 * Have to create a mangled name which is:
8053 temp = g_string_new ("");
8054 len = strlen (fullname);
8055 for (i = 0; i < len; ++i) {
8056 char c = fullname [i];
8058 g_string_append_c (temp, c);
8059 } else if (c == '_') {
8060 g_string_append_c (temp, '_');
8061 g_string_append_c (temp, '_');
8063 g_string_append_c (temp, '_');
8064 g_string_append_printf (temp, "%x", (int)c);
8067 temps = g_string_free (temp, FALSE);
8068 /* Include the length to avoid different length type names aliasing each other */
8069 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8078 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8083 supported = append_mangled_type (s, sig->ret);
8087 g_string_append_printf (s, "this_");
8088 for (i = 0; i < sig->param_count; ++i) {
8089 supported = append_mangled_type (s, sig->params [i]);
8098 append_mangled_wrapper_type (GString *s, guint32 wrapper_type)
8102 switch (wrapper_type) {
8103 case MONO_WRAPPER_REMOTING_INVOKE:
8104 label = "remoting_invoke";
8106 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8107 label = "remoting_invoke_check";
8109 case MONO_WRAPPER_XDOMAIN_INVOKE:
8110 label = "remoting_invoke_xdomain";
8112 case MONO_WRAPPER_PROXY_ISINST:
8113 label = "proxy_isinst";
8115 case MONO_WRAPPER_LDFLD:
8118 case MONO_WRAPPER_LDFLDA:
8121 case MONO_WRAPPER_STFLD:
8124 case MONO_WRAPPER_ALLOC:
8127 case MONO_WRAPPER_WRITE_BARRIER:
8128 label = "write_barrier";
8130 case MONO_WRAPPER_STELEMREF:
8131 label = "stelemref";
8133 case MONO_WRAPPER_UNKNOWN:
8136 case MONO_WRAPPER_MANAGED_TO_NATIVE:
8137 label = "man2native";
8139 case MONO_WRAPPER_SYNCHRONIZED:
8142 case MONO_WRAPPER_MANAGED_TO_MANAGED:
8145 case MONO_WRAPPER_CASTCLASS:
8146 label = "castclass";
8148 case MONO_WRAPPER_RUNTIME_INVOKE:
8149 label = "run_invoke";
8151 case MONO_WRAPPER_DELEGATE_INVOKE:
8154 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8155 label = "del_beg_inv";
8157 case MONO_WRAPPER_DELEGATE_END_INVOKE:
8158 label = "del_end_inv";
8160 case MONO_WRAPPER_NATIVE_TO_MANAGED:
8161 label = "native2man";
8164 g_assert_not_reached ();
8167 g_string_append_printf (s, "%s_", label);
8171 append_mangled_wrapper_subtype (GString *s, WrapperSubtype subtype)
8177 case WRAPPER_SUBTYPE_NONE:
8179 case WRAPPER_SUBTYPE_ELEMENT_ADDR:
8180 label = "elem_addr";
8182 case WRAPPER_SUBTYPE_STRING_CTOR:
8185 case WRAPPER_SUBTYPE_VIRTUAL_STELEMREF:
8186 label = "virt_stelem";
8188 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER:
8189 label = "fast_mon_enter";
8191 case WRAPPER_SUBTYPE_FAST_MONITOR_ENTER_V4:
8192 label = "fast_mon_enter_4";
8194 case WRAPPER_SUBTYPE_FAST_MONITOR_EXIT:
8195 label = "fast_monitor_exit";
8197 case WRAPPER_SUBTYPE_PTR_TO_STRUCTURE:
8198 label = "ptr2struct";
8200 case WRAPPER_SUBTYPE_STRUCTURE_TO_PTR:
8201 label = "struct2ptr";
8203 case WRAPPER_SUBTYPE_CASTCLASS_WITH_CACHE:
8204 label = "castclass_w_cache";
8206 case WRAPPER_SUBTYPE_ISINST_WITH_CACHE:
8207 label = "isinst_w_cache";
8209 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL:
8210 label = "run_inv_norm";
8212 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DYNAMIC:
8213 label = "run_inv_dyn";
8215 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT:
8216 label = "run_inv_dir";
8218 case WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL:
8219 label = "run_inv_vir";
8221 case WRAPPER_SUBTYPE_ICALL_WRAPPER:
8224 case WRAPPER_SUBTYPE_NATIVE_FUNC_AOT:
8225 label = "native_func_aot";
8227 case WRAPPER_SUBTYPE_PINVOKE:
8230 case WRAPPER_SUBTYPE_SYNCHRONIZED_INNER:
8231 label = "synch_inner";
8233 case WRAPPER_SUBTYPE_GSHAREDVT_IN:
8234 label = "gshared_in";
8236 case WRAPPER_SUBTYPE_GSHAREDVT_OUT:
8237 label = "gshared_out";
8239 case WRAPPER_SUBTYPE_ARRAY_ACCESSOR:
8240 label = "array_acc";
8242 case WRAPPER_SUBTYPE_GENERIC_ARRAY_HELPER:
8243 label = "generic_arry_help";
8245 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_VIRTUAL:
8246 label = "del_inv_virt";
8248 case WRAPPER_SUBTYPE_DELEGATE_INVOKE_BOUND:
8249 label = "del_inv_bound";
8251 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8252 label = "gsharedvt_in_sig";
8254 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8255 label = "gsharedvt_out_sig";
8258 g_assert_not_reached ();
8261 g_string_append_printf (s, "%s_", label);
8265 sanitize_mangled_string (const char *input)
8267 GString *s = g_string_new ("");
8269 for (int i=0; input [i] != '\0'; i++) {
8273 g_string_append (s, "_dot_");
8276 g_string_append (s, "_");
8279 g_string_append (s, "_bt_");
8282 g_string_append (s, "_le_");
8285 g_string_append (s, "_gt_");
8288 g_string_append (s, "_sl_");
8291 g_string_append (s, "_lbrack_");
8294 g_string_append (s, "_rbrack_");
8297 g_string_append (s, "_lparen_");
8300 g_string_append (s, "_dash_");
8303 g_string_append (s, "_rparen_");
8306 g_string_append (s, "_comma_");
8309 g_string_append_c (s, c);
8313 return g_string_free (s, FALSE);
8317 append_mangled_klass (GString *s, MonoClass *klass)
8319 char *klass_desc = mono_class_full_name (klass);
8320 g_string_append_printf (s, "_%s_%s_", klass->name_space, klass_desc);
8321 g_free (klass_desc);
8328 append_mangled_method (GString *s, MonoMethod *method);
8331 append_mangled_wrapper (GString *s, MonoMethod *method)
8333 gboolean success = TRUE;
8334 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8335 g_string_append_printf (s, "wrapper_");
8337 append_mangled_wrapper_type (s, method->wrapper_type);
8339 switch (method->wrapper_type) {
8340 case MONO_WRAPPER_REMOTING_INVOKE:
8341 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
8342 case MONO_WRAPPER_XDOMAIN_INVOKE: {
8343 MonoMethod *m = mono_marshal_method_from_wrapper (method);
8345 success = success && append_mangled_method (s, m);
8348 case MONO_WRAPPER_PROXY_ISINST:
8349 case MONO_WRAPPER_LDFLD:
8350 case MONO_WRAPPER_LDFLDA:
8351 case MONO_WRAPPER_STFLD: {
8353 success = success && append_mangled_klass (s, info->d.proxy.klass);
8356 case MONO_WRAPPER_ALLOC: {
8357 /* The GC name is saved once in MonoAotFileInfo */
8358 g_assert (info->d.alloc.alloc_type != -1);
8359 g_string_append_printf (s, "%d_", info->d.alloc.alloc_type);
8361 g_string_append_printf (s, "%s_", method->name);
8364 case MONO_WRAPPER_WRITE_BARRIER: {
8367 case MONO_WRAPPER_STELEMREF: {
8368 append_mangled_wrapper_subtype (s, info->subtype);
8369 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
8370 g_string_append_printf (s, "%d", info->d.virtual_stelemref.kind);
8373 case MONO_WRAPPER_UNKNOWN: {
8374 append_mangled_wrapper_subtype (s, info->subtype);
8375 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
8376 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
8377 success = success && append_mangled_klass (s, method->klass);
8378 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
8379 success = success && append_mangled_method (s, info->d.synchronized_inner.method);
8380 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
8381 success = success && append_mangled_method (s, info->d.array_accessor.method);
8382 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
8383 append_mangled_signature (s, info->d.gsharedvt.sig);
8384 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
8385 append_mangled_signature (s, info->d.gsharedvt.sig);
8388 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
8389 append_mangled_wrapper_subtype (s, info->subtype);
8390 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
8391 g_string_append_printf (s, "%s", method->name);
8392 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
8393 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8395 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
8396 success = success && append_mangled_method (s, info->d.managed_to_native.method);
8400 case MONO_WRAPPER_SYNCHRONIZED: {
8403 m = mono_marshal_method_from_wrapper (method);
8405 g_assert (m != method);
8406 success = success && append_mangled_method (s, m);
8409 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
8410 append_mangled_wrapper_subtype (s, info->subtype);
8412 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
8413 g_string_append_printf (s, "%d_", info->d.element_addr.rank);
8414 g_string_append_printf (s, "%d_", info->d.element_addr.elem_size);
8415 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
8416 success = success && append_mangled_method (s, info->d.string_ctor.method);
8418 g_assert_not_reached ();
8422 case MONO_WRAPPER_CASTCLASS: {
8423 append_mangled_wrapper_subtype (s, info->subtype);
8426 case MONO_WRAPPER_RUNTIME_INVOKE: {
8427 append_mangled_wrapper_subtype (s, info->subtype);
8428 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
8429 success = success && append_mangled_method (s, info->d.runtime_invoke.method);
8430 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
8431 success = success && append_mangled_signature (s, info->d.runtime_invoke.sig);
8434 case MONO_WRAPPER_DELEGATE_INVOKE:
8435 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
8436 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
8437 if (method->is_inflated) {
8438 /* These wrappers are identified by their class */
8439 g_string_append_printf (s, "i_");
8440 success = success && append_mangled_klass (s, method->klass);
8442 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
8444 g_string_append_printf (s, "u_");
8445 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
8446 append_mangled_wrapper_subtype (s, info->subtype);
8447 g_string_append_printf (s, "u_sigstart");
8451 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
8453 success = success && append_mangled_method (s, info->d.native_to_managed.method);
8454 success = success && append_mangled_klass (s, method->klass);
8458 g_assert_not_reached ();
8460 return success && append_mangled_signature (s, mono_method_signature (method));
8464 append_mangled_context (GString *str, MonoGenericContext *context)
8466 GString *res = g_string_new ("");
8468 g_string_append_printf (res, "gens_");
8469 g_string_append (res, "00");
8471 gboolean good = context->class_inst && context->class_inst->type_argc > 0;
8472 good = good || (context->method_inst && context->method_inst->type_argc > 0);
8475 if (context->class_inst)
8476 mono_ginst_get_desc (res, context->class_inst);
8477 if (context->method_inst) {
8478 if (context->class_inst)
8479 g_string_append (res, "11");
8480 mono_ginst_get_desc (res, context->method_inst);
8482 g_string_append_printf (str, "gens_%s", res->str);
8486 append_mangled_method (GString *s, MonoMethod *method)
8488 if (method->wrapper_type)
8489 return append_mangled_wrapper (s, method);
8491 g_string_append_printf (s, "%s_", method->klass->image->assembly->aname.name);
8493 if (method->is_inflated) {
8494 g_string_append_printf (s, "inflated_");
8495 MonoMethodInflated *imethod = (MonoMethodInflated*) method;
8496 g_assert (imethod->context.class_inst != NULL || imethod->context.method_inst != NULL);
8498 append_mangled_context (s, &imethod->context);
8499 g_string_append_printf (s, "_declared_by_");
8500 append_mangled_method (s, imethod->declaring);
8501 } else if (method->is_generic) {
8502 g_string_append_printf (s, "generic_");
8503 append_mangled_klass (s, method->klass);
8504 g_string_append_printf (s, "_%s_", method->name);
8506 MonoGenericContainer *container = mono_method_get_generic_container (method);
8507 g_string_append_printf (s, "_%s");
8508 append_mangled_context (s, &container->context);
8510 return append_mangled_signature (s, mono_method_signature (method));
8512 g_string_append_printf (s, "_");
8513 append_mangled_klass (s, method->klass);
8514 g_string_append_printf (s, "_%s_", method->name);
8515 if (!append_mangled_signature (s, mono_method_signature (method))) {
8516 g_string_free (s, TRUE);
8525 * mono_aot_get_mangled_method_name:
8527 * Return a unique mangled name for METHOD, or NULL.
8530 mono_aot_get_mangled_method_name (MonoMethod *method)
8532 GString *s = g_string_new ("aot_");
8533 if (!append_mangled_method (s, method)) {
8534 g_string_free (s, TRUE);
8537 char *out = g_string_free (s, FALSE);
8538 // Scrub method and class names
8539 char *cleaned = sanitize_mangled_string (out);
8546 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8548 return is_direct_callable (llvm_acfg, NULL, patch_info);
8552 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8554 MonoPltEntry *plt_entry;
8556 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8557 plt_entry->llvm_used = FALSE;
8561 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8563 const char *sym = NULL;
8565 if (llvm_acfg->aot_opts.direct_icalls) {
8566 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8567 /* Call to a C function implementing a jit icall */
8568 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8569 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8570 MonoMethod *method = (MonoMethod *)data;
8571 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8572 sym = mono_lookup_icall_symbol (method);
8573 else if (llvm_acfg->aot_opts.direct_pinvoke)
8574 sym = get_pinvoke_import (llvm_acfg, method);
8577 return g_strdup (sym);
8583 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8585 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8586 MonoPltEntry *plt_entry;
8587 const char *sym = NULL;
8590 ji->data.target = data;
8592 if (!can_encode_patch (llvm_acfg, ji))
8595 if (llvm_acfg->aot_opts.direct_icalls) {
8596 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8597 /* Call to a C function implementing a jit icall */
8598 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8599 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8600 MonoMethod *method = (MonoMethod *)data;
8601 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8602 sym = mono_lookup_icall_symbol (method);
8605 return g_strdup (sym);
8608 plt_entry = get_plt_entry (llvm_acfg, ji);
8609 plt_entry->llvm_used = TRUE;
8611 #if defined(TARGET_MACH)
8612 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8614 return g_strdup_printf (plt_entry->llvm_symbol);
8619 mono_aot_get_method_index (MonoMethod *method)
8621 g_assert (llvm_acfg);
8622 return get_method_index (llvm_acfg, method);
8626 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8630 mono_acfg_lock (llvm_acfg);
8631 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8632 mono_acfg_unlock (llvm_acfg);
8638 execute_system (const char * command)
8642 #if defined(HOST_WIN32) && defined(HAVE_SYSTEM)
8643 // We need an extra set of quotes around the whole command to properly handle commands
8644 // with spaces since internally the command is called through "cmd /c.
8645 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8647 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8648 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8649 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8650 status = _wsystem (wstr);
8653 g_free (quoted_command);
8654 #elif defined (HAVE_SYSTEM)
8655 status = system (command);
8657 g_assert_not_reached ();
8668 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8672 emit_llvm_file (MonoAotCompile *acfg)
8674 char *command, *opts, *tempbc, *optbc, *output_fname;
8676 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8677 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8678 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8680 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8681 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8684 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8687 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8688 * a lot of time, and doesn't seem to save much space.
8689 * The following optimizations cannot be enabled:
8691 * - 'jump-threading' changes our blockaddress references to int constants.
8692 * - 'basiccg' fails because it contains:
8693 * if (CS && !isa<IntrinsicInst>(II)) {
8694 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8695 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8696 * The opt list below was produced by taking the output of:
8697 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8698 * then removing tailcallelim + the global opts.
8699 * strip-dead-prototypes deletes unused intrinsics definitions.
8701 /* The dse pass is disabled because of #13734 and #17616 */
8703 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8704 * // If we have no DataLayout information around, then the size of the store
8705 * // is inferrable from the pointee type. If they are the same type, then
8706 * // we know that the store is safe.
8707 * if (AA.getDataLayout() == 0 &&
8708 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8709 * return OverwriteComplete;
8710 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8712 if (acfg->aot_opts.llvm_only)
8713 // FIXME: This doesn't work yet
8714 opts = g_strdup ("");
8716 #if LLVM_API_VERSION > 100
8717 opts = g_strdup ("-O2 -disable-tail-calls");
8719 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");
8721 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8722 aot_printf (acfg, "Executing opt: %s\n", command);
8723 if (execute_system (command) != 0)
8727 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8728 /* Nothing else to do */
8731 if (acfg->aot_opts.llvm_only) {
8732 /* Use the stock clang from xcode */
8734 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);
8736 aot_printf (acfg, "Executing clang: %s\n", command);
8737 if (execute_system (command) != 0)
8742 if (!acfg->llc_args)
8743 acfg->llc_args = g_string_new ("");
8745 /* Verbose asm slows down llc greatly */
8746 g_string_append (acfg->llc_args, " -asm-verbose=false");
8748 if (acfg->aot_opts.mtriple)
8749 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8751 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8753 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8755 #if LLVM_API_VERSION > 100
8756 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8759 #if ( defined(TARGET_MACH) && defined(TARGET_ARM) ) || defined(TARGET_ORBIS)
8760 /* ios requires PIC code now */
8761 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8763 if (llvm_acfg->aot_opts.static_link)
8764 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8766 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8769 if (acfg->llvm_owriter) {
8770 /* Emit an object file directly */
8771 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8772 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8774 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8776 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8777 g_free (output_fname);
8779 aot_printf (acfg, "Executing llc: %s\n", command);
8781 if (execute_system (command) != 0)
8788 emit_code (MonoAotCompile *acfg)
8790 int oindex, i, prev_index;
8791 gboolean saved_unbox_info = FALSE;
8792 char symbol [MAX_SYMBOL_SIZE];
8794 if (acfg->aot_opts.llvm_only)
8797 #if defined(TARGET_POWERPC64)
8798 sprintf (symbol, ".Lgot_addr");
8799 emit_section_change (acfg, ".text", 0);
8800 emit_alignment (acfg, 8);
8801 emit_label (acfg, symbol);
8802 emit_pointer (acfg, acfg->got_symbol);
8806 * This global symbol is used to compute the address of each method using the
8807 * code_offsets array. It is also used to compute the memory ranges occupied by
8808 * AOT code, so it must be equal to the address of the first emitted method.
8810 emit_section_change (acfg, ".text", 0);
8811 emit_alignment_code (acfg, 8);
8812 emit_info_symbol (acfg, "jit_code_start");
8815 * Emit some padding so the local symbol for the first method doesn't have the
8816 * same address as 'methods'.
8818 emit_padding (acfg, 16);
8820 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8824 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8826 cfg = acfg->cfgs [i];
8831 method = cfg->orig_method;
8833 /* Emit unbox trampoline */
8834 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8835 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8837 emit_section_change (acfg, ".text", 0);
8839 if (acfg->thumb_mixed && cfg->compile_llvm) {
8840 emit_set_thumb_mode (acfg);
8841 fprintf (acfg->fp, "\n.thumb_func\n");
8844 emit_label (acfg, symbol);
8846 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8848 if (acfg->thumb_mixed && cfg->compile_llvm)
8849 emit_set_arm_mode (acfg);
8851 if (!saved_unbox_info) {
8852 char user_symbol [128];
8854 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8856 emit_label (acfg, "ut_end");
8858 unwind_ops = mono_unwind_get_cie_program ();
8859 save_unwind_info (acfg, user_symbol, unwind_ops);
8860 mono_free_unwind_info (unwind_ops);
8862 /* Save the unbox trampoline size */
8863 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8865 saved_unbox_info = TRUE;
8869 if (cfg->compile_llvm)
8870 acfg->stats.llvm_count ++;
8872 emit_method_code (acfg, cfg);
8875 emit_section_change (acfg, ".text", 0);
8876 emit_alignment_code (acfg, 8);
8877 emit_info_symbol (acfg, "jit_code_end");
8879 /* To distinguish it from the next symbol */
8880 emit_padding (acfg, 4);
8883 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8884 * from optimizing them away, since it doesn't see that code_offsets references them.
8885 * JITted methods don't need this since they are referenced using assembler local
8887 * FIXME: This is why write-symbols doesn't work on OSX ?
8889 if (acfg->llvm && acfg->need_no_dead_strip) {
8890 fprintf (acfg->fp, "\n");
8891 for (i = 0; i < acfg->nmethods; ++i) {
8892 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8893 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8898 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8899 * This is PIE code, and the linker can update it if needed.
8902 sprintf (symbol, "method_addresses");
8903 emit_section_change (acfg, ".text", 1);
8904 emit_alignment_code (acfg, 8);
8905 emit_info_symbol (acfg, symbol);
8906 if (acfg->aot_opts.write_symbols)
8907 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8908 emit_unset_mode (acfg);
8909 if (acfg->need_no_dead_strip)
8910 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8912 for (i = 0; i < acfg->nmethods; ++i) {
8913 #ifdef MONO_ARCH_AOT_SUPPORTED
8916 if (acfg->cfgs [i]) {
8917 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8919 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8924 sprintf (symbol, "method_addresses_end");
8925 emit_label (acfg, symbol);
8928 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8929 sprintf (symbol, "unbox_trampolines");
8930 emit_section_change (acfg, RODATA_SECT, 0);
8931 emit_alignment (acfg, 8);
8932 emit_info_symbol (acfg, symbol);
8935 for (i = 0; i < acfg->nmethods; ++i) {
8940 cfg = acfg->cfgs [i];
8944 method = cfg->orig_method;
8946 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8947 index = get_method_index (acfg, method);
8949 emit_int32 (acfg, index);
8950 /* Make sure the table is sorted by index */
8951 g_assert (index > prev_index);
8955 sprintf (symbol, "unbox_trampolines_end");
8956 emit_info_symbol (acfg, symbol);
8957 emit_int32 (acfg, 0);
8959 /* Emit a separate table with the trampoline addresses/offsets */
8960 sprintf (symbol, "unbox_trampoline_addresses");
8961 emit_section_change (acfg, ".text", 0);
8962 emit_alignment_code (acfg, 8);
8963 emit_info_symbol (acfg, symbol);
8965 for (i = 0; i < acfg->nmethods; ++i) {
8970 cfg = acfg->cfgs [i];
8974 method = cfg->orig_method;
8976 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8977 #ifdef MONO_ARCH_AOT_SUPPORTED
8980 index = get_method_index (acfg, method);
8981 sprintf (symbol, "ut_%d", index);
8983 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8987 emit_int32 (acfg, 0);
8991 emit_info (MonoAotCompile *acfg)
8996 offsets = g_new0 (gint32, acfg->nmethods);
8998 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8999 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
9001 if (acfg->cfgs [i]) {
9002 emit_method_info (acfg, acfg->cfgs [i]);
9003 offsets [i] = acfg->cfgs [i]->method_info_offset;
9009 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9014 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
9016 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
9017 #define mix(a,b,c) { \
9018 a -= c; a ^= rot(c, 4); c += b; \
9019 b -= a; b ^= rot(a, 6); a += c; \
9020 c -= b; c ^= rot(b, 8); b += a; \
9021 a -= c; a ^= rot(c,16); c += b; \
9022 b -= a; b ^= rot(a,19); a += c; \
9023 c -= b; c ^= rot(b, 4); b += a; \
9025 #define final(a,b,c) { \
9026 c ^= b; c -= rot(b,14); \
9027 a ^= c; a -= rot(c,11); \
9028 b ^= a; b -= rot(a,25); \
9029 c ^= b; c -= rot(b,16); \
9030 a ^= c; a -= rot(c,4); \
9031 b ^= a; b -= rot(a,14); \
9032 c ^= b; c -= rot(b,24); \
9036 mono_aot_type_hash (MonoType *t1)
9038 guint hash = t1->type;
9040 hash |= t1->byref << 6; /* do not collide with t1->type values */
9042 case MONO_TYPE_VALUETYPE:
9043 case MONO_TYPE_CLASS:
9044 case MONO_TYPE_SZARRAY:
9045 /* check if the distribution is good enough */
9046 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
9048 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
9049 case MONO_TYPE_ARRAY:
9050 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
9051 case MONO_TYPE_GENERICINST:
9052 return ((hash << 5) - hash) ^ 0;
9059 * mono_aot_method_hash:
9061 * Return a hash code for methods which only depends on metadata.
9064 mono_aot_method_hash (MonoMethod *method)
9066 MonoMethodSignature *sig;
9070 guint32 *hashes_start, *hashes;
9072 MonoGenericInst *class_ginst = NULL;
9073 MonoGenericInst *ginst = NULL;
9075 /* Similar to the hash in mono_method_get_imt_slot () */
9077 sig = mono_method_signature (method);
9079 if (mono_class_is_ginst (method->klass))
9080 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
9081 if (method->is_inflated)
9082 ginst = ((MonoMethodInflated*)method)->context.method_inst;
9084 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
9085 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
9086 hashes = hashes_start;
9088 /* Some wrappers are assigned to random classes */
9089 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
9090 klass = method->klass;
9092 klass = mono_defaults.object_class;
9094 if (!method->wrapper_type) {
9097 if (mono_class_is_ginst (klass))
9098 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
9100 full_name = mono_type_full_name (&klass->byval_arg);
9102 hashes [0] = mono_metadata_str_hash (full_name);
9106 hashes [0] = mono_metadata_str_hash (klass->name);
9107 hashes [1] = mono_metadata_str_hash (klass->name_space);
9109 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
9110 /* The method name includes a stringified pointer */
9113 hashes [2] = mono_metadata_str_hash (method->name);
9114 hashes [3] = method->wrapper_type;
9115 hashes [4] = mono_aot_type_hash (sig->ret);
9117 for (i = 0; i < sig->param_count; i++) {
9118 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
9121 for (i = 0; i < class_ginst->type_argc; ++i)
9122 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
9125 for (i = 0; i < ginst->type_argc; ++i)
9126 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
9128 g_assert (hindex == hashes_count);
9130 /* Setup internal state */
9131 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
9133 /* Handle most of the hashes */
9134 while (hashes_count > 3) {
9143 /* Handle the last 3 hashes (all the case statements fall through) */
9144 switch (hashes_count) {
9145 case 3 : c += hashes [2];
9146 case 2 : b += hashes [1];
9147 case 1 : a += hashes [0];
9149 case 0: /* nothing left to add */
9153 g_free (hashes_start);
9162 * mono_aot_get_array_helper_from_wrapper;
9164 * Get the helper method in Array called by an array wrapper method.
9167 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
9171 MonoGenericContext ctx;
9172 MonoType *args [16];
9173 char *mname, *iname, *s, *s2, *helper_name = NULL;
9175 prefix = "System.Collections.Generic";
9176 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
9177 s2 = strstr (s, "`1.");
9183 //printf ("X: %s %s\n", iname, mname);
9185 if (!strcmp (iname, "IList"))
9186 helper_name = g_strdup_printf ("InternalArray__%s", mname);
9188 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
9189 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
9191 g_free (helper_name);
9194 if (m->is_generic) {
9196 memset (&ctx, 0, sizeof (ctx));
9197 args [0] = &method->klass->element_class->byval_arg;
9198 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
9199 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
9200 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9206 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
9208 typedef struct HashEntry {
9209 guint32 key, value, index;
9210 struct HashEntry *next;
9214 * emit_extra_methods:
9216 * Emit methods which are not in the METHOD table, like wrappers.
9219 emit_extra_methods (MonoAotCompile *acfg)
9221 int i, table_size, buf_size;
9223 guint32 *info_offsets;
9226 HashEntry *entry, *new_entry;
9227 int nmethods, max_chain_length;
9230 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
9232 /* Emit method info */
9234 for (i = 0; i < acfg->extra_methods->len; ++i) {
9235 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9236 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9242 p = buf = (guint8 *)g_malloc (buf_size);
9246 method = cfg->method_to_register;
9248 encode_method_ref (acfg, method, p, &p);
9250 g_assert ((p - buf) < buf_size);
9252 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9257 * Construct a chained hash table for mapping indexes in extra_method_info to
9260 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
9261 table = g_ptr_array_sized_new (table_size);
9262 for (i = 0; i < table_size; ++i)
9263 g_ptr_array_add (table, NULL);
9264 chain_lengths = g_new0 (int, table_size);
9265 max_chain_length = 0;
9266 for (i = 0; i < acfg->extra_methods->len; ++i) {
9267 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9268 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
9274 key = info_offsets [i];
9275 value = get_method_index (acfg, method);
9277 hash = mono_aot_method_hash (method) % table_size;
9278 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
9280 chain_lengths [hash] ++;
9281 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
9283 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
9284 new_entry->key = key;
9285 new_entry->value = value;
9287 entry = (HashEntry *)g_ptr_array_index (table, hash);
9288 if (entry == NULL) {
9289 new_entry->index = hash;
9290 g_ptr_array_index (table, hash) = new_entry;
9293 entry = entry->next;
9295 entry->next = new_entry;
9296 new_entry->index = table->len;
9297 g_ptr_array_add (table, new_entry);
9300 g_free (chain_lengths);
9302 //printf ("MAX: %d\n", max_chain_length);
9304 buf_size = table->len * 12 + 4;
9305 p = buf = (guint8 *)g_malloc (buf_size);
9306 encode_int (table_size, p, &p);
9308 for (i = 0; i < table->len; ++i) {
9309 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
9311 if (entry == NULL) {
9312 encode_int (0, p, &p);
9313 encode_int (0, p, &p);
9314 encode_int (0, p, &p);
9316 //g_assert (entry->key > 0);
9317 encode_int (entry->key, p, &p);
9318 encode_int (entry->value, p, &p);
9320 encode_int (entry->next->index, p, &p);
9322 encode_int (0, p, &p);
9325 g_assert (p - buf <= buf_size);
9327 /* Emit the table */
9328 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
9333 * Emit a table reverse mapping method indexes to their index in extra_method_info.
9334 * This is used by mono_aot_find_jit_info ().
9336 buf_size = acfg->extra_methods->len * 8 + 4;
9337 p = buf = (guint8 *)g_malloc (buf_size);
9338 encode_int (acfg->extra_methods->len, p, &p);
9339 for (i = 0; i < acfg->extra_methods->len; ++i) {
9340 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
9342 encode_int (get_method_index (acfg, method), p, &p);
9343 encode_int (info_offsets [i], p, &p);
9345 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
9348 g_free (info_offsets);
9349 g_ptr_array_free (table, TRUE);
9353 generate_aotid (guint8* aotid)
9355 gpointer rand_handle;
9359 rand_handle = mono_rand_init (NULL, 0);
9361 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
9362 mono_error_assert_ok (&error);
9364 mono_rand_close (rand_handle);
9368 emit_exception_info (MonoAotCompile *acfg)
9372 SeqPointData sp_data;
9373 gboolean seq_points_to_file = FALSE;
9375 offsets = g_new0 (gint32, acfg->nmethods);
9376 for (i = 0; i < acfg->nmethods; ++i) {
9377 if (acfg->cfgs [i]) {
9378 MonoCompile *cfg = acfg->cfgs [i];
9380 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
9381 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
9382 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
9383 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
9384 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
9386 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
9387 offsets [i] = cfg->ex_info_offset;
9389 if (method_seq_points_to_file) {
9390 if (!seq_points_to_file) {
9391 mono_seq_point_data_init (&sp_data, acfg->nmethods);
9392 seq_points_to_file = TRUE;
9394 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
9401 if (seq_points_to_file) {
9402 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
9403 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
9404 char *image_basename = g_path_get_basename (acfg->image->name);
9405 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
9406 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
9408 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
9409 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
9413 mono_seq_point_data_write (&sp_data, aot_file_path);
9414 mono_seq_point_data_free (&sp_data);
9418 g_free (image_basename);
9420 g_free (aot_file_path);
9423 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
9428 emit_unwind_info (MonoAotCompile *acfg)
9433 if (acfg->aot_opts.llvm_only) {
9434 g_assert (acfg->unwind_ops->len == 0);
9439 * The unwind info contains a lot of duplicates so we emit each unique
9440 * entry once, and only store the offset from the start of the table in the
9444 sprintf (symbol, "unwind_info");
9445 emit_section_change (acfg, RODATA_SECT, 1);
9446 emit_alignment (acfg, 8);
9447 emit_info_symbol (acfg, symbol);
9449 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9450 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9451 guint8 *unwind_info;
9452 guint32 unwind_info_len;
9456 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9459 encode_value (unwind_info_len, p, &p);
9460 emit_bytes (acfg, buf, p - buf);
9461 emit_bytes (acfg, unwind_info, unwind_info_len);
9463 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9468 emit_class_info (MonoAotCompile *acfg)
9473 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9474 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9475 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9477 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);
9481 typedef struct ClassNameTableEntry {
9482 guint32 token, index;
9483 struct ClassNameTableEntry *next;
9484 } ClassNameTableEntry;
9487 emit_class_name_table (MonoAotCompile *acfg)
9489 int i, table_size, buf_size;
9490 guint32 token, hash;
9495 ClassNameTableEntry *entry, *new_entry;
9498 * Construct a chained hash table for mapping class names to typedef tokens.
9500 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9501 table = g_ptr_array_sized_new (table_size);
9502 for (i = 0; i < table_size; ++i)
9503 g_ptr_array_add (table, NULL);
9504 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9506 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9507 klass = mono_class_get_checked (acfg->image, token, &error);
9509 mono_error_cleanup (&error);
9512 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9513 hash = mono_metadata_str_hash (full_name) % table_size;
9516 /* FIXME: Allocate from the mempool */
9517 new_entry = g_new0 (ClassNameTableEntry, 1);
9518 new_entry->token = token;
9520 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9521 if (entry == NULL) {
9522 new_entry->index = hash;
9523 g_ptr_array_index (table, hash) = new_entry;
9526 entry = entry->next;
9528 entry->next = new_entry;
9529 new_entry->index = table->len;
9530 g_ptr_array_add (table, new_entry);
9534 /* Emit the table */
9535 buf_size = table->len * 4 + 4;
9536 p = buf = (guint8 *)g_malloc0 (buf_size);
9538 /* FIXME: Optimize memory usage */
9539 g_assert (table_size < 65000);
9540 encode_int16 (table_size, p, &p);
9541 g_assert (table->len < 65000);
9542 for (i = 0; i < table->len; ++i) {
9543 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9545 if (entry == NULL) {
9546 encode_int16 (0, p, &p);
9547 encode_int16 (0, p, &p);
9549 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9551 encode_int16 (entry->next->index, p, &p);
9553 encode_int16 (0, p, &p);
9557 g_assert (p - buf <= buf_size);
9558 g_ptr_array_free (table, TRUE);
9560 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9566 emit_image_table (MonoAotCompile *acfg)
9572 * The image table is small but referenced in a lot of places.
9573 * So we emit it at once, and reference its elements by an index.
9575 buf_size = acfg->image_table->len * 28 + 4;
9576 for (i = 0; i < acfg->image_table->len; i++) {
9577 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9578 MonoAssemblyName *aname = &image->assembly->aname;
9580 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9583 buf = p = (guint8 *)g_malloc0 (buf_size);
9584 encode_int (acfg->image_table->len, p, &p);
9585 for (i = 0; i < acfg->image_table->len; i++) {
9586 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9587 MonoAssemblyName *aname = &image->assembly->aname;
9589 /* FIXME: Support multi-module assemblies */
9590 g_assert (image->assembly->image == image);
9592 encode_string (image->assembly_name, p, &p);
9593 encode_string (image->guid, p, &p);
9594 encode_string (aname->culture ? aname->culture : "", p, &p);
9595 encode_string ((const char*)aname->public_key_token, p, &p);
9597 while (GPOINTER_TO_UINT (p) % 8 != 0)
9600 encode_int (aname->flags, p, &p);
9601 encode_int (aname->major, p, &p);
9602 encode_int (aname->minor, p, &p);
9603 encode_int (aname->build, p, &p);
9604 encode_int (aname->revision, p, &p);
9606 g_assert (p - buf <= buf_size);
9608 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9614 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9616 int i, first_plt_got_patch = 0, buf_size;
9618 guint32 *got_info_offsets;
9619 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9621 /* Add the patches needed by the PLT to the GOT */
9623 acfg->plt_got_offset_base = acfg->got_offset;
9624 first_plt_got_patch = info->got_patches->len;
9625 for (i = 1; i < acfg->plt_offset; ++i) {
9626 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9628 g_ptr_array_add (info->got_patches, plt_entry->ji);
9630 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9633 acfg->got_offset += acfg->plt_offset;
9638 * - optimize offsets table.
9639 * - reduce number of exported symbols.
9640 * - emit info for a klass only once.
9641 * - determine when a method uses a GOT slot which is guaranteed to be already
9643 * - clean up and document the code.
9644 * - use String.Empty in class libs.
9647 /* Encode info required to decode shared GOT entries */
9648 buf_size = info->got_patches->len * 128;
9649 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9650 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9652 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9654 if (acfg->plt_offset)
9655 acfg->plt_got_info_offsets [0] = 0;
9657 for (i = 0; i < info->got_patches->len; ++i) {
9658 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9663 encode_value (ji->type, p, &p);
9665 encode_patch (acfg, ji, p, &p);
9666 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9667 g_assert (p - buf <= buf_size);
9668 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9670 if (!llvm && i >= first_plt_got_patch)
9671 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9672 acfg->stats.got_info_size += p - buf;
9675 /* Emit got_info_offsets table */
9677 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9678 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);
9682 emit_got (MonoAotCompile *acfg)
9684 char symbol [MAX_SYMBOL_SIZE];
9686 if (acfg->aot_opts.llvm_only)
9689 /* Don't make GOT global so accesses to it don't need relocations */
9690 sprintf (symbol, "%s", acfg->got_symbol);
9693 emit_unset_mode (acfg);
9694 fprintf (acfg->fp, ".section __DATA, __bss\n");
9695 emit_alignment (acfg, 8);
9697 emit_info_symbol (acfg, "jit_got");
9698 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9700 emit_section_change (acfg, ".bss", 0);
9701 emit_alignment (acfg, 8);
9702 if (acfg->aot_opts.write_symbols)
9703 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9704 emit_label (acfg, symbol);
9706 emit_info_symbol (acfg, "jit_got");
9707 if (acfg->got_offset > 0)
9708 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9711 sprintf (symbol, "got_end");
9712 emit_label (acfg, symbol);
9715 typedef struct GlobalsTableEntry {
9716 guint32 value, index;
9717 struct GlobalsTableEntry *next;
9718 } GlobalsTableEntry;
9720 #ifdef TARGET_WIN32_MSVC
9721 #define DLL_ENTRY_POINT "DllMain"
9724 emit_library_info (MonoAotCompile *acfg)
9726 // Only include for shared libraries linked directly from generated object.
9727 if (link_shared_library (acfg)) {
9729 char symbol [MAX_SYMBOL_SIZE];
9731 // Ask linker to export all global symbols.
9732 emit_section_change (acfg, ".drectve", 0);
9733 for (guint i = 0; i < acfg->globals->len; ++i) {
9734 name = (char *)g_ptr_array_index (acfg->globals, i);
9735 g_assert (name != NULL);
9736 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9737 emit_string (acfg, symbol);
9740 // Emit DLLMain function, needed by MSVC linker for DLL's.
9741 // NOTE, DllMain should not go into exports above.
9742 emit_section_change (acfg, ".text", 0);
9743 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9744 emit_label (acfg, DLL_ENTRY_POINT);
9746 // Simple implementation of DLLMain, just returning TRUE.
9747 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9748 fprintf (acfg->fp, "movl $1, %%eax\n");
9749 fprintf (acfg->fp, "ret\n");
9751 // Inform linker about our dll entry function.
9752 emit_section_change (acfg, ".drectve", 0);
9753 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9761 emit_library_info (MonoAotCompile *acfg)
9768 emit_globals (MonoAotCompile *acfg)
9774 GlobalsTableEntry *entry, *new_entry;
9776 if (!acfg->aot_opts.static_link)
9779 if (acfg->aot_opts.llvm_only) {
9780 g_assert (acfg->globals->len == 0);
9785 * When static linking, we emit a table containing our globals.
9789 * Construct a chained hash table for mapping global names to their index in
9790 * the globals table.
9792 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9793 table = g_ptr_array_sized_new (table_size);
9794 for (i = 0; i < table_size; ++i)
9795 g_ptr_array_add (table, NULL);
9796 for (i = 0; i < acfg->globals->len; ++i) {
9797 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9799 hash = mono_metadata_str_hash (name) % table_size;
9801 /* FIXME: Allocate from the mempool */
9802 new_entry = g_new0 (GlobalsTableEntry, 1);
9803 new_entry->value = i;
9805 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9806 if (entry == NULL) {
9807 new_entry->index = hash;
9808 g_ptr_array_index (table, hash) = new_entry;
9811 entry = entry->next;
9813 entry->next = new_entry;
9814 new_entry->index = table->len;
9815 g_ptr_array_add (table, new_entry);
9819 /* Emit the table */
9820 sprintf (symbol, ".Lglobals_hash");
9821 emit_section_change (acfg, RODATA_SECT, 0);
9822 emit_alignment (acfg, 8);
9823 emit_label (acfg, symbol);
9825 /* FIXME: Optimize memory usage */
9826 g_assert (table_size < 65000);
9827 emit_int16 (acfg, table_size);
9828 for (i = 0; i < table->len; ++i) {
9829 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9831 if (entry == NULL) {
9832 emit_int16 (acfg, 0);
9833 emit_int16 (acfg, 0);
9835 emit_int16 (acfg, entry->value + 1);
9837 emit_int16 (acfg, entry->next->index);
9839 emit_int16 (acfg, 0);
9843 /* Emit the names */
9844 for (i = 0; i < acfg->globals->len; ++i) {
9845 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9847 sprintf (symbol, "name_%d", i);
9848 emit_section_change (acfg, RODATA_SECT, 1);
9850 emit_alignment (acfg, 4);
9852 emit_label (acfg, symbol);
9853 emit_string (acfg, name);
9856 /* Emit the globals table */
9857 sprintf (symbol, "globals");
9858 emit_section_change (acfg, ".data", 0);
9859 /* This is not a global, since it is accessed by the init function */
9860 emit_alignment (acfg, 8);
9861 emit_info_symbol (acfg, symbol);
9863 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9864 emit_pointer (acfg, symbol);
9866 for (i = 0; i < acfg->globals->len; ++i) {
9867 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9869 sprintf (symbol, "name_%d", i);
9870 emit_pointer (acfg, symbol);
9872 g_assert (strlen (name) < sizeof (symbol));
9873 sprintf (symbol, "%s", name);
9874 emit_pointer (acfg, symbol);
9876 /* Null terminate the table */
9877 emit_int32 (acfg, 0);
9878 emit_int32 (acfg, 0);
9882 emit_mem_end (MonoAotCompile *acfg)
9886 if (acfg->aot_opts.llvm_only)
9889 sprintf (symbol, "mem_end");
9890 emit_section_change (acfg, ".text", 1);
9891 emit_alignment_code (acfg, 8);
9892 emit_label (acfg, symbol);
9896 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9900 info->version = MONO_AOT_FILE_VERSION;
9901 info->plt_got_offset_base = acfg->plt_got_offset_base;
9902 info->got_size = acfg->got_offset * sizeof (gpointer);
9903 info->plt_size = acfg->plt_offset;
9904 info->nmethods = acfg->nmethods;
9905 info->flags = acfg->flags;
9906 info->opts = acfg->opts;
9907 info->simd_opts = acfg->simd_opts;
9908 info->gc_name_index = acfg->gc_name_offset;
9909 info->datafile_size = acfg->datafile_offset;
9910 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9911 info->table_offsets [i] = acfg->table_offsets [i];
9912 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9913 info->num_trampolines [i] = acfg->num_trampolines [i];
9914 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9915 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9916 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9917 info->trampoline_size [i] = acfg->trampoline_size [i];
9918 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9920 info->double_align = MONO_ABI_ALIGNOF (double);
9921 info->long_align = MONO_ABI_ALIGNOF (gint64);
9922 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9923 info->tramp_page_size = acfg->tramp_page_size;
9924 info->nshared_got_entries = acfg->nshared_got_entries;
9925 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9926 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9928 memcpy(&info->aotid, acfg->image->aotid, 16);
9932 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9934 char symbol [MAX_SYMBOL_SIZE];
9936 const char **symbols;
9938 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9940 symbols [sindex ++] = acfg->got_symbol;
9942 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9943 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9945 symbols [sindex ++] = NULL;
9946 symbols [sindex ++] = NULL;
9948 /* llvm_get_method */
9949 symbols [sindex ++] = NULL;
9950 /* llvm_get_unbox_tramp */
9951 symbols [sindex ++] = NULL;
9952 if (!acfg->aot_opts.llvm_only) {
9953 symbols [sindex ++] = "jit_code_start";
9954 symbols [sindex ++] = "jit_code_end";
9955 symbols [sindex ++] = "method_addresses";
9957 symbols [sindex ++] = NULL;
9958 symbols [sindex ++] = NULL;
9959 symbols [sindex ++] = NULL;
9961 if (acfg->data_outfile) {
9962 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9963 symbols [sindex ++] = NULL;
9965 symbols [sindex ++] = "blob";
9966 symbols [sindex ++] = "class_name_table";
9967 symbols [sindex ++] = "class_info_offsets";
9968 symbols [sindex ++] = "method_info_offsets";
9969 symbols [sindex ++] = "ex_info_offsets";
9970 symbols [sindex ++] = "extra_method_info_offsets";
9971 symbols [sindex ++] = "extra_method_table";
9972 symbols [sindex ++] = "got_info_offsets";
9974 symbols [sindex ++] = "llvm_got_info_offsets";
9976 symbols [sindex ++] = NULL;
9977 symbols [sindex ++] = "image_table";
9979 symbols [sindex ++] = "mem_end";
9980 symbols [sindex ++] = "assembly_guid";
9981 symbols [sindex ++] = "runtime_version";
9982 if (acfg->num_trampoline_got_entries) {
9983 symbols [sindex ++] = "specific_trampolines";
9984 symbols [sindex ++] = "static_rgctx_trampolines";
9985 symbols [sindex ++] = "imt_trampolines";
9986 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9988 symbols [sindex ++] = NULL;
9989 symbols [sindex ++] = NULL;
9990 symbols [sindex ++] = NULL;
9991 symbols [sindex ++] = NULL;
9993 if (acfg->aot_opts.static_link) {
9994 symbols [sindex ++] = "globals";
9996 symbols [sindex ++] = NULL;
9998 symbols [sindex ++] = "assembly_name";
9999 symbols [sindex ++] = "plt";
10000 symbols [sindex ++] = "plt_end";
10001 symbols [sindex ++] = "unwind_info";
10002 if (!acfg->aot_opts.llvm_only) {
10003 symbols [sindex ++] = "unbox_trampolines";
10004 symbols [sindex ++] = "unbox_trampolines_end";
10005 symbols [sindex ++] = "unbox_trampoline_addresses";
10007 symbols [sindex ++] = NULL;
10008 symbols [sindex ++] = NULL;
10009 symbols [sindex ++] = NULL;
10012 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
10014 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
10015 emit_section_change (acfg, ".data", 0);
10016 emit_alignment (acfg, 8);
10017 emit_label (acfg, symbol);
10018 if (!acfg->aot_opts.static_link)
10019 emit_global (acfg, symbol, FALSE);
10021 /* The data emitted here must match MonoAotFileInfo. */
10023 emit_int32 (acfg, info->version);
10024 emit_int32 (acfg, info->dummy);
10027 * We emit pointers to our data structures instead of emitting global symbols which
10028 * point to them, to reduce the number of globals, and because using globals leads to
10029 * various problems (i.e. arm/thumb).
10031 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
10032 emit_pointer (acfg, symbols [i]);
10034 emit_int32 (acfg, info->plt_got_offset_base);
10035 emit_int32 (acfg, info->got_size);
10036 emit_int32 (acfg, info->plt_size);
10037 emit_int32 (acfg, info->nmethods);
10038 emit_int32 (acfg, info->flags);
10039 emit_int32 (acfg, info->opts);
10040 emit_int32 (acfg, info->simd_opts);
10041 emit_int32 (acfg, info->gc_name_index);
10042 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
10043 emit_int32 (acfg, info->double_align);
10044 emit_int32 (acfg, info->long_align);
10045 emit_int32 (acfg, info->generic_tramp_num);
10046 emit_int32 (acfg, info->tramp_page_size);
10047 emit_int32 (acfg, info->nshared_got_entries);
10048 emit_int32 (acfg, info->datafile_size);
10050 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
10051 emit_int32 (acfg, info->table_offsets [i]);
10052 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10053 emit_int32 (acfg, info->num_trampolines [i]);
10054 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10055 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
10056 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10057 emit_int32 (acfg, info->trampoline_size [i]);
10058 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
10059 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
10061 emit_bytes (acfg, info->aotid, 16);
10063 if (acfg->aot_opts.static_link) {
10064 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
10065 emit_alignment (acfg, sizeof (gpointer));
10066 emit_label (acfg, acfg->static_linking_symbol);
10067 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
10072 * Emit a structure containing all the information not stored elsewhere.
10075 emit_file_info (MonoAotCompile *acfg)
10078 MonoAotFileInfo *info;
10080 if (acfg->aot_opts.bind_to_runtime_version) {
10081 build_info = mono_get_runtime_build_info ();
10082 emit_string_symbol (acfg, "runtime_version", build_info);
10083 g_free (build_info);
10085 emit_string_symbol (acfg, "runtime_version", "");
10088 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
10090 /* Emit a string holding the assembly name */
10091 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
10093 info = g_new0 (MonoAotFileInfo, 1);
10094 init_aot_file_info (acfg, info);
10096 if (acfg->aot_opts.static_link) {
10097 char symbol [MAX_SYMBOL_SIZE];
10101 * Emit a global symbol which can be passed by an embedding app to
10102 * mono_aot_register_module (). The symbol points to a pointer to the the file info
10105 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
10107 /* Get rid of characters which cannot occur in symbols */
10109 for (p = symbol; *p; ++p) {
10110 if (!(isalnum (*p) || *p == '_'))
10113 acfg->static_linking_symbol = g_strdup (symbol);
10117 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
10119 emit_aot_file_info (acfg, info);
10123 emit_blob (MonoAotCompile *acfg)
10125 acfg->blob_closed = TRUE;
10127 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
10131 emit_objc_selectors (MonoAotCompile *acfg)
10136 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
10141 * cat > foo.m << EOF
10144 * return @selector(print:);
10149 mono_img_writer_emit_unset_mode (acfg->w);
10150 g_assert (acfg->fp);
10151 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
10152 fprintf (acfg->fp, ".align 3\n");
10153 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10154 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
10155 emit_label (acfg, symbol);
10156 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
10157 emit_pointer (acfg, symbol);
10160 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
10161 for (i = 0; i < acfg->objc_selectors->len; ++i) {
10162 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
10163 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
10166 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
10167 fprintf (acfg->fp, ".align 3\n");
10168 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
10169 fprintf (acfg->fp, ".long 0\n");
10170 fprintf (acfg->fp, ".long 16\n");
10174 emit_dwarf_info (MonoAotCompile *acfg)
10176 #ifdef EMIT_DWARF_INFO
10178 char symbol2 [128];
10180 /* DIEs for methods */
10181 for (i = 0; i < acfg->nmethods; ++i) {
10182 MonoCompile *cfg = acfg->cfgs [i];
10187 // FIXME: LLVM doesn't define .Lme_...
10188 if (cfg->compile_llvm)
10191 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
10193 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 ()));
10199 collect_methods (MonoAotCompile *acfg)
10202 MonoImage *image = acfg->image;
10204 /* Collect methods */
10205 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
10207 MonoMethod *method;
10208 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
10210 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10213 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
10214 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
10215 mono_error_cleanup (&error);
10219 /* Load all methods eagerly to skip the slower lazy loading code */
10220 mono_class_setup_methods (method->klass);
10222 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
10223 /* Compile the wrapper instead */
10224 /* We do this here instead of add_wrappers () because it is easy to do it here */
10225 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
10229 /* FIXME: Some mscorlib methods don't have debug info */
10231 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
10232 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
10233 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
10234 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10235 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
10236 if (!mono_debug_lookup_method (method)) {
10237 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
10244 if (method->is_generic || mono_class_is_gtd (method->klass))
10245 /* Compile the ref shared version instead */
10246 method = mini_get_shared_method (method);
10248 /* Since we add the normal methods first, their index will be equal to their zero based token index */
10249 add_method_with_index (acfg, method, i, FALSE);
10250 acfg->method_index ++;
10253 /* gsharedvt methods */
10254 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
10256 MonoMethod *method;
10257 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
10259 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
10262 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
10263 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
10265 if (method->is_generic || mono_class_is_gtd (method->klass)) {
10266 MonoMethod *gshared;
10268 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
10269 add_extra_method (acfg, gshared);
10273 if (mono_aot_mode_is_full (&acfg->aot_opts))
10274 add_generic_instances (acfg);
10276 if (mono_aot_mode_is_full (&acfg->aot_opts))
10277 add_wrappers (acfg);
10282 compile_methods (MonoAotCompile *acfg)
10284 int i, methods_len;
10286 if (acfg->aot_opts.nthreads > 0) {
10289 GPtrArray *threads;
10290 MonoThreadHandle *thread_handle;
10291 gpointer *user_data;
10292 MonoMethod **methods;
10294 methods_len = acfg->methods->len;
10296 len = acfg->methods->len / acfg->aot_opts.nthreads;
10297 g_assert (len > 0);
10299 * Partition the list of methods into fragments, and hand it to threads to
10302 threads = g_ptr_array_new ();
10303 /* Make a copy since acfg->methods is modified by compile_method () */
10304 methods = g_new0 (MonoMethod*, methods_len);
10305 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
10306 for (i = 0; i < methods_len; ++i)
10307 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
10309 while (i < methods_len) {
10311 MonoInternalThread *thread;
10313 frag = g_ptr_array_new ();
10314 for (j = 0; j < len; ++j) {
10315 if (i < methods_len) {
10316 g_ptr_array_add (frag, methods [i]);
10321 user_data = g_new0 (gpointer, 3);
10322 user_data [0] = acfg;
10323 user_data [1] = frag;
10325 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
10326 mono_error_assert_ok (&error);
10328 thread_handle = mono_threads_open_thread_handle (thread->handle);
10329 g_ptr_array_add (threads, thread_handle);
10333 for (i = 0; i < threads->len; ++i) {
10334 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
10335 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
10341 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
10342 for (i = methods_len; i < acfg->methods->len; ++i) {
10343 /* This can add new methods to acfg->methods */
10344 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
10349 compile_asm (MonoAotCompile *acfg)
10351 char *command, *objfile;
10352 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
10353 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
10354 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
10356 #ifdef TARGET_WIN32_MSVC
10357 #define AS_OPTIONS "-c -x assembler"
10358 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
10359 #define AS_OPTIONS "--64"
10360 #elif defined(TARGET_POWERPC64)
10361 #define AS_OPTIONS "-a64 -mppc64"
10362 #elif defined(sparc) && SIZEOF_VOID_P == 8
10363 #define AS_OPTIONS "-xarch=v9"
10364 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10365 #define AS_OPTIONS "-arch i386"
10367 #define AS_OPTIONS ""
10370 #ifdef __native_client_codegen__
10371 #if defined(TARGET_AMD64)
10372 #define AS_NAME "nacl64-as"
10374 #define AS_NAME "nacl-as"
10376 #elif defined(TARGET_OSX)
10377 #define AS_NAME "clang"
10378 #elif defined(TARGET_WIN32_MSVC)
10379 #define AS_NAME "clang.exe"
10381 #define AS_NAME "as"
10384 #ifdef TARGET_WIN32_MSVC
10385 #define AS_OBJECT_FILE_SUFFIX "obj"
10387 #define AS_OBJECT_FILE_SUFFIX "o"
10391 #define LD_NAME "ld"
10392 #define LD_OPTIONS "-shared -G"
10393 #elif defined(__ppc__) && defined(TARGET_MACH)
10394 #define LD_NAME "gcc"
10395 #define LD_OPTIONS "-dynamiclib"
10396 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
10397 #define LD_NAME "clang"
10398 #define LD_OPTIONS "--shared"
10399 #elif defined(TARGET_WIN32_MSVC)
10400 #define LD_NAME "link.exe"
10401 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
10402 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
10403 #define LD_NAME "gcc"
10404 #define LD_OPTIONS "-shared"
10405 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
10406 #define LD_NAME "clang"
10407 #define LD_OPTIONS "-m32 -dynamiclib"
10408 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
10409 #define LD_NAME "gcc"
10410 #define LD_OPTIONS "--shared"
10411 #elif defined(TARGET_POWERPC64)
10412 #define LD_OPTIONS "-m elf64ppc"
10416 #define LD_OPTIONS ""
10419 if (acfg->aot_opts.asm_only) {
10420 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
10421 if (acfg->aot_opts.static_link)
10422 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10424 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
10428 if (acfg->aot_opts.static_link) {
10429 if (acfg->aot_opts.outfile)
10430 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10432 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
10434 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
10438 g_string_append (acfg->as_args, "-c -x assembler");
10441 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10442 acfg->as_args ? acfg->as_args->str : "",
10443 wrap_path (objfile), wrap_path (acfg->tmpfname));
10444 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10445 if (execute_system (command) != 0) {
10451 if (acfg->llvm && !acfg->llvm_owriter) {
10452 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10453 acfg->as_args ? acfg->as_args->str : "",
10454 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10455 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10456 if (execute_system (command) != 0) {
10465 if (acfg->aot_opts.static_link) {
10466 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10467 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10472 if (acfg->aot_opts.outfile)
10473 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10475 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10477 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10480 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10482 llvm_ofile = g_strdup ("");
10485 /* replace the ; flags separators with spaces */
10486 g_strdelimit (ld_flags, ";", ' ');
10488 if (acfg->aot_opts.llvm_only)
10489 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10491 #ifdef TARGET_WIN32_MSVC
10492 g_assert (tmp_outfile_name != NULL);
10493 g_assert (objfile != NULL);
10494 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10495 ld_flags, tmp_outfile_name, objfile);
10496 #elif defined(LD_NAME)
10497 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10498 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10499 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10502 if (acfg->aot_opts.tool_prefix) {
10503 /* Cross compiling */
10504 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10505 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10506 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10508 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10509 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10510 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10512 if (acfg->aot_opts.llvm_only) {
10513 command = g_strdup_printf ("clang++ %s", args);
10515 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10520 aot_printf (acfg, "Executing the native linker: %s\n", command);
10521 if (execute_system (command) != 0) {
10522 g_free (tmp_outfile_name);
10523 g_free (outfile_name);
10532 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10533 printf ("Stripping the binary: %s\n", com);
10534 execute_system (com);
10537 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10539 * gas generates 'mapping symbols' each time code and data is mixed, which
10540 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10542 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10543 aot_printf (acfg, "Stripping the binary: %s\n", command);
10544 if (execute_system (command) != 0) {
10545 g_free (tmp_outfile_name);
10546 g_free (outfile_name);
10553 if (0 != rename (tmp_outfile_name, outfile_name)) {
10554 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10555 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10556 unlink (outfile_name);
10557 rename (tmp_outfile_name, outfile_name);
10561 #if defined(TARGET_MACH)
10562 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10563 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10564 if (execute_system (command) != 0) {
10569 if (!acfg->aot_opts.save_temps)
10572 g_free (tmp_outfile_name);
10573 g_free (outfile_name);
10576 if (acfg->aot_opts.save_temps)
10577 aot_printf (acfg, "Retained input file.\n");
10579 unlink (acfg->tmpfname);
10585 profread_byte (FILE *infile)
10590 res = fread (&i, 1, 1, infile);
10591 g_assert (res == 1);
10596 profread_int (FILE *infile)
10600 res = fread (&i, 4, 1, infile);
10601 g_assert (res == 1);
10606 profread_string (FILE *infile)
10612 len = profread_int (infile);
10613 if (len + 1 > 1024)
10614 pbuf = g_malloc (len + 1);
10617 res = fread (pbuf, 1, len, infile);
10618 g_assert (res == len);
10621 return g_strdup (buf);
10627 load_profile_file (MonoAotCompile *acfg, char *filename)
10631 int res, len, version;
10634 infile = fopen (filename, "r");
10636 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10640 printf ("Using profile data file '%s'\n", filename);
10642 sprintf (magic, AOT_PROFILER_MAGIC);
10643 len = strlen (magic);
10644 res = fread (buf, 1, len, infile);
10645 magic [len] = '\0';
10647 if ((res != len) || strcmp (buf, magic) != 0) {
10648 printf ("Profile file has wrong header: '%s'.\n", buf);
10652 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10653 version = profread_int (infile);
10654 if (version != expected_version) {
10655 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10660 ProfileData *data = g_new0 (ProfileData, 1);
10661 data->images = g_hash_table_new (NULL, NULL);
10662 data->classes = g_hash_table_new (NULL, NULL);
10663 data->ginsts = g_hash_table_new (NULL, NULL);
10664 data->methods = g_hash_table_new (NULL, NULL);
10667 int type = profread_byte (infile);
10668 int id = profread_int (infile);
10670 if (type == AOTPROF_RECORD_NONE)
10674 case AOTPROF_RECORD_IMAGE: {
10675 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10676 idata->name = profread_string (infile);
10677 char *mvid = profread_string (infile);
10679 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10682 case AOTPROF_RECORD_GINST: {
10684 int len = profread_int (infile);
10686 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10688 gdata->argv = g_new0 (ClassProfileData*, len);
10690 for (i = 0; i < len; ++i) {
10691 int class_id = profread_int (infile);
10693 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10694 g_assert (gdata->argv [i]);
10696 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10699 case AOTPROF_RECORD_TYPE: {
10700 int type = profread_byte (infile);
10703 case MONO_TYPE_CLASS: {
10704 int image_id = profread_int (infile);
10705 int ginst_id = profread_int (infile);
10706 char *class_name = profread_string (infile);
10708 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10711 char *p = strrchr (class_name, '.');
10715 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10716 cdata->image = image;
10717 cdata->ns = g_strdup (class_name);
10718 cdata->name = g_strdup (p + 1);
10720 if (ginst_id != -1) {
10721 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10722 g_assert (cdata->inst);
10724 g_free (class_name);
10726 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10730 case MONO_TYPE_SZARRAY: {
10731 int elem_id = profread_int (infile);
10737 g_assert_not_reached ();
10742 case AOTPROF_RECORD_METHOD: {
10743 int class_id = profread_int (infile);
10744 int ginst_id = profread_int (infile);
10745 int param_count = profread_int (infile);
10746 char *method_name = profread_string (infile);
10747 char *sig = profread_string (infile);
10749 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10752 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10754 mdata->klass = klass;
10755 mdata->name = method_name;
10756 mdata->signature = sig;
10757 mdata->param_count = param_count;
10759 if (ginst_id != -1) {
10760 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10761 g_assert (mdata->inst);
10763 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10767 printf ("%d\n", type);
10768 g_assert_not_reached ();
10774 acfg->profile_data = g_list_append (acfg->profile_data, data);
10778 resolve_class (ClassProfileData *cdata);
10781 resolve_ginst (GInstProfileData *inst_data)
10785 if (inst_data->inst)
10788 for (i = 0; i < inst_data->argc; ++i) {
10789 resolve_class (inst_data->argv [i]);
10790 if (!inst_data->argv [i]->klass)
10793 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10794 for (i = 0; i < inst_data->argc; ++i)
10795 args [i] = &inst_data->argv [i]->klass->byval_arg;
10797 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10801 resolve_class (ClassProfileData *cdata)
10806 if (!cdata->image->image)
10809 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10811 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10815 resolve_ginst (cdata->inst);
10816 if (!cdata->inst->inst)
10818 MonoGenericContext ctx;
10820 memset (&ctx, 0, sizeof (ctx));
10821 ctx.class_inst = cdata->inst->inst;
10822 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10824 cdata->klass = klass;
10829 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10832 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10834 GHashTableIter iter;
10835 gpointer key, value;
10842 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10843 g_hash_table_iter_init (&iter, data->images);
10844 while (g_hash_table_iter_next (&iter, &key, &value)) {
10845 ImageProfileData *idata = (ImageProfileData*)value;
10847 for (i = 0; i < assemblies->len; ++i) {
10848 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10850 if (!strcmp (ass->aname.name, idata->name)) {
10851 idata->image = ass->image;
10856 g_ptr_array_free (assemblies, TRUE);
10859 g_hash_table_iter_init (&iter, data->classes);
10860 while (g_hash_table_iter_next (&iter, &key, &value)) {
10861 ClassProfileData *cdata = (ClassProfileData*)value;
10863 if (!cdata->image->image) {
10864 if (acfg->aot_opts.verbose)
10865 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10869 resolve_class (cdata);
10872 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10877 g_hash_table_iter_init (&iter, data->methods);
10878 while (g_hash_table_iter_next (&iter, &key, &value)) {
10879 MethodProfileData *mdata = (MethodProfileData*)value;
10884 resolve_class (mdata->klass);
10885 klass = mdata->klass->klass;
10887 if (acfg->aot_opts.verbose)
10888 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10892 while ((m = mono_class_get_methods (klass, &miter))) {
10895 if (strcmp (m->name, mdata->name))
10897 MonoMethodSignature *sig = mono_method_signature (m);
10900 if (sig->param_count != mdata->param_count)
10903 resolve_ginst (mdata->inst);
10904 if (!mdata->inst->inst)
10906 MonoGenericContext ctx;
10908 memset (&ctx, 0, sizeof (ctx));
10909 ctx.method_inst = mdata->inst->inst;
10911 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10914 sig = mono_method_signature_checked (m, &error);
10915 if (!is_ok (&error)) {
10916 mono_error_cleanup (&error);
10920 char *sig_str = mono_signature_full_name (sig);
10921 gboolean match = !strcmp (sig_str, mdata->signature);
10926 //printf ("%s\n", mono_method_full_name (m, 1));
10930 if (!mdata->method) {
10931 if (acfg->aot_opts.verbose)
10932 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10938 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10942 for (i = 0; i < inst->type_argc; ++i) {
10943 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10944 if (k->image == image)
10946 if (mono_class_is_ginst (k)) {
10947 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10948 if (inst_references_image (kinst, image))
10956 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10960 for (i = 0; i < inst->type_argc; ++i) {
10961 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10962 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10969 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10971 GHashTableIter iter;
10972 gpointer key, value;
10978 if (acfg->aot_opts.profile_only) {
10979 /* Add methods referenced by the profile */
10980 g_hash_table_iter_init (&iter, data->methods);
10981 while (g_hash_table_iter_next (&iter, &key, &value)) {
10982 MethodProfileData *mdata = (MethodProfileData*)value;
10983 MonoMethod *m = mdata->method;
10987 if (m->is_inflated)
10989 add_extra_method (acfg, m);
10990 g_hash_table_insert (acfg->profile_methods, m, m);
10996 * Add method instances 'related' to this assembly to the AOT image.
10998 g_hash_table_iter_init (&iter, data->methods);
10999 while (g_hash_table_iter_next (&iter, &key, &value)) {
11000 MethodProfileData *mdata = (MethodProfileData*)value;
11001 MonoMethod *m = mdata->method;
11002 MonoGenericContext *ctx;
11006 if (!m->is_inflated)
11009 ctx = mono_method_get_context (m);
11010 /* For simplicity, add instances which reference the assembly we are compiling */
11011 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
11012 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
11013 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11014 //printf ("%s\n", mono_method_full_name (m, TRUE));
11015 add_extra_method (acfg, m);
11017 } else if (m->klass->image == acfg->image &&
11018 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
11019 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
11020 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
11021 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
11022 //printf ("%s\n", mono_method_full_name (m, TRUE));
11023 add_extra_method (acfg, m);
11027 * FIXME: We might skip some instances, for example:
11028 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
11029 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
11033 printf ("Added %d methods from profile.\n", count);
11037 init_got_info (GotInfo *info)
11041 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11042 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11043 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11044 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
11045 info->got_patches = g_ptr_array_new ();
11048 static MonoAotCompile*
11049 acfg_create (MonoAssembly *ass, guint32 opts)
11051 MonoImage *image = ass->image;
11052 MonoAotCompile *acfg;
11054 acfg = g_new0 (MonoAotCompile, 1);
11055 acfg->methods = g_ptr_array_new ();
11056 acfg->method_indexes = g_hash_table_new (NULL, NULL);
11057 acfg->method_depth = g_hash_table_new (NULL, NULL);
11058 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
11059 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
11060 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
11061 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
11062 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
11063 acfg->image_hash = g_hash_table_new (NULL, NULL);
11064 acfg->image_table = g_ptr_array_new ();
11065 acfg->globals = g_ptr_array_new ();
11066 acfg->image = image;
11068 /* TODO: Write out set of SIMD instructions used, rather than just those available */
11069 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
11070 acfg->mempool = mono_mempool_new ();
11071 acfg->extra_methods = g_ptr_array_new ();
11072 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
11073 acfg->unwind_ops = g_ptr_array_new ();
11074 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
11075 acfg->method_order = g_ptr_array_new ();
11076 acfg->export_names = g_hash_table_new (NULL, NULL);
11077 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
11078 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
11079 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
11080 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11081 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
11082 acfg->profile_methods = g_hash_table_new (NULL, NULL);
11083 mono_os_mutex_init_recursive (&acfg->mutex);
11085 init_got_info (&acfg->got_info);
11086 init_got_info (&acfg->llvm_got_info);
11092 got_info_free (GotInfo *info)
11096 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11097 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
11098 g_free (info->patch_to_got_offset_by_type);
11099 g_hash_table_destroy (info->patch_to_got_offset);
11100 g_ptr_array_free (info->got_patches, TRUE);
11104 acfg_free (MonoAotCompile *acfg)
11108 mono_img_writer_destroy (acfg->w);
11109 for (i = 0; i < acfg->nmethods; ++i)
11110 if (acfg->cfgs [i])
11111 mono_destroy_compile (acfg->cfgs [i]);
11113 g_free (acfg->cfgs);
11115 g_free (acfg->static_linking_symbol);
11116 g_free (acfg->got_symbol);
11117 g_free (acfg->plt_symbol);
11118 g_ptr_array_free (acfg->methods, TRUE);
11119 g_ptr_array_free (acfg->image_table, TRUE);
11120 g_ptr_array_free (acfg->globals, TRUE);
11121 g_ptr_array_free (acfg->unwind_ops, TRUE);
11122 g_hash_table_destroy (acfg->method_indexes);
11123 g_hash_table_destroy (acfg->method_depth);
11124 g_hash_table_destroy (acfg->plt_offset_to_entry);
11125 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
11126 if (acfg->patch_to_plt_entry [i])
11127 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
11129 g_free (acfg->patch_to_plt_entry);
11130 g_hash_table_destroy (acfg->method_to_cfg);
11131 g_hash_table_destroy (acfg->token_info_hash);
11132 g_hash_table_destroy (acfg->method_to_pinvoke_import);
11133 g_hash_table_destroy (acfg->image_hash);
11134 g_hash_table_destroy (acfg->unwind_info_offsets);
11135 g_hash_table_destroy (acfg->method_label_hash);
11136 if (acfg->typespec_classes)
11137 g_hash_table_destroy (acfg->typespec_classes);
11138 g_hash_table_destroy (acfg->export_names);
11139 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
11140 g_hash_table_destroy (acfg->klass_blob_hash);
11141 g_hash_table_destroy (acfg->method_blob_hash);
11142 got_info_free (&acfg->got_info);
11143 got_info_free (&acfg->llvm_got_info);
11144 mono_mempool_destroy (acfg->mempool);
11148 #define WRAPPER(e,n) n,
11149 static const char* const
11150 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
11151 #include "mono/metadata/wrapper-types.h"
11155 static G_GNUC_UNUSED const char*
11156 get_wrapper_type_name (int type)
11158 return wrapper_type_names [type];
11164 static void aot_dump (MonoAotCompile *acfg)
11170 mono_json_writer_init (&writer);
11172 mono_json_writer_object_begin(&writer);
11175 mono_json_writer_indent (&writer);
11176 mono_json_writer_object_key(&writer, "methods");
11177 mono_json_writer_array_begin (&writer);
11180 for (i = 0; i < acfg->nmethods; ++i) {
11182 MonoMethod *method;
11185 cfg = acfg->cfgs [i];
11189 method = cfg->orig_method;
11191 mono_json_writer_indent (&writer);
11192 mono_json_writer_object_begin(&writer);
11194 mono_json_writer_indent (&writer);
11195 mono_json_writer_object_key(&writer, "name");
11196 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
11198 mono_json_writer_indent (&writer);
11199 mono_json_writer_object_key(&writer, "signature");
11200 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
11202 mono_json_writer_indent (&writer);
11203 mono_json_writer_object_key(&writer, "code_size");
11204 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
11206 klass = method->klass;
11208 mono_json_writer_indent (&writer);
11209 mono_json_writer_object_key(&writer, "class");
11210 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
11212 mono_json_writer_indent (&writer);
11213 mono_json_writer_object_key(&writer, "namespace");
11214 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
11216 mono_json_writer_indent (&writer);
11217 mono_json_writer_object_key(&writer, "wrapper_type");
11218 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
11220 mono_json_writer_indent_pop (&writer);
11221 mono_json_writer_indent (&writer);
11222 mono_json_writer_object_end (&writer);
11223 mono_json_writer_printf (&writer, ",\n");
11226 mono_json_writer_indent_pop (&writer);
11227 mono_json_writer_indent (&writer);
11228 mono_json_writer_array_end (&writer);
11229 mono_json_writer_printf (&writer, ",\n");
11233 mono_json_writer_indent_push (&writer);
11234 mono_json_writer_indent (&writer);
11235 mono_json_writer_object_key(&writer, "plt");
11236 mono_json_writer_array_begin (&writer);
11238 for (i = 0; i < acfg->plt_offset; ++i) {
11239 MonoPltEntry *plt_entry = NULL;
11244 * The first plt entry is unused.
11248 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
11249 ji = plt_entry->ji;
11251 mono_json_writer_indent (&writer);
11252 mono_json_writer_printf (&writer, "{ ");
11253 mono_json_writer_object_key(&writer, "symbol");
11254 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
11257 mono_json_writer_indent_pop (&writer);
11258 mono_json_writer_indent (&writer);
11259 mono_json_writer_array_end (&writer);
11260 mono_json_writer_printf (&writer, ",\n");
11265 mono_json_writer_indent_push (&writer);
11266 mono_json_writer_indent (&writer);
11267 mono_json_writer_object_key(&writer, "got");
11268 mono_json_writer_array_begin (&writer);
11270 mono_json_writer_indent_push (&writer);
11271 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
11272 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
11274 mono_json_writer_indent (&writer);
11275 mono_json_writer_printf (&writer, "{ ");
11276 mono_json_writer_object_key(&writer, "patch_name");
11277 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
11280 mono_json_writer_indent_pop (&writer);
11281 mono_json_writer_indent (&writer);
11282 mono_json_writer_array_end (&writer);
11283 mono_json_writer_printf (&writer, ",\n");
11286 mono_json_writer_indent_pop (&writer);
11287 mono_json_writer_indent (&writer);
11288 mono_json_writer_object_end (&writer);
11290 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
11291 dumpfile = fopen (dumpname, "w+");
11294 fprintf (dumpfile, "%s", writer.text->str);
11297 mono_json_writer_destroy (&writer);
11300 static const char *preinited_jit_icalls[] = {
11301 "mono_aot_init_llvm_method",
11302 "mono_aot_init_gshared_method_this",
11303 "mono_aot_init_gshared_method_mrgctx",
11304 "mono_aot_init_gshared_method_vtable",
11305 "mono_llvm_throw_corlib_exception",
11306 "mono_init_vtable_slot",
11307 "mono_helper_ldstr_mscorlib"
11311 add_preinit_got_slots (MonoAotCompile *acfg)
11317 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
11318 * during method initialization etc.
11321 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11322 ji->type = MONO_PATCH_INFO_IMAGE;
11323 ji->data.image = acfg->image;
11324 get_got_offset (acfg, FALSE, ji);
11325 get_got_offset (acfg, TRUE, ji);
11327 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11328 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
11329 get_got_offset (acfg, FALSE, ji);
11330 get_got_offset (acfg, TRUE, ji);
11332 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11333 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
11334 get_got_offset (acfg, FALSE, ji);
11335 get_got_offset (acfg, TRUE, ji);
11337 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11338 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
11339 get_got_offset (acfg, FALSE, ji);
11340 get_got_offset (acfg, TRUE, ji);
11342 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11343 ji->type = MONO_PATCH_INFO_AOT_MODULE;
11344 get_got_offset (acfg, FALSE, ji);
11345 get_got_offset (acfg, TRUE, ji);
11347 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11348 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
11349 get_got_offset (acfg, FALSE, ji);
11350 get_got_offset (acfg, TRUE, ji);
11352 for (i = 0; i < TLS_KEY_NUM; i++) {
11353 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11354 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
11355 ji->data.index = i;
11356 get_got_offset (acfg, FALSE, ji);
11357 get_got_offset (acfg, TRUE, ji);
11359 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11360 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
11361 ji->data.index = i;
11362 get_got_offset (acfg, FALSE, ji);
11363 get_got_offset (acfg, TRUE, ji);
11366 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
11367 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
11368 get_got_offset (acfg, FALSE, ji);
11369 get_got_offset (acfg, TRUE, ji);
11371 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
11372 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
11373 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11374 ji->data.name = preinited_jit_icalls [i];
11375 get_got_offset (acfg, FALSE, ji);
11376 get_got_offset (acfg, TRUE, ji);
11379 acfg->nshared_got_entries = acfg->got_offset;
11383 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11385 MonoImage *image = ass->image;
11388 MonoAotCompile *acfg;
11389 char *outfile_name, *tmp_outfile_name, *p;
11390 char llvm_stats_msg [256];
11394 acfg = acfg_create (ass, opts);
11396 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
11397 acfg->aot_opts.write_symbols = TRUE;
11398 acfg->aot_opts.ntrampolines = 4096;
11399 acfg->aot_opts.nrgctx_trampolines = 4096;
11400 acfg->aot_opts.nimt_trampolines = 512;
11401 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
11402 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
11403 acfg->aot_opts.llvm_path = g_strdup ("");
11404 acfg->aot_opts.temp_path = g_strdup ("");
11406 acfg->aot_opts.use_trampolines_page = TRUE;
11409 mono_aot_parse_options (aot_options, &acfg->aot_opts);
11411 if (acfg->aot_opts.logfile) {
11412 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
11415 if (acfg->aot_opts.data_outfile) {
11416 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
11417 if (!acfg->data_outfile) {
11418 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
11421 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
11424 //acfg->aot_opts.print_skipped_methods = TRUE;
11426 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
11427 if (acfg->opts & MONO_OPT_GSHAREDVT) {
11428 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
11431 if (acfg->aot_opts.llvm_only) {
11432 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
11436 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11437 acfg->opts |= MONO_OPT_GSHAREDVT;
11440 #if !defined(ENABLE_LLVM)
11441 if (acfg->aot_opts.llvm_only) {
11442 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11447 if (acfg->opts & MONO_OPT_GSHAREDVT)
11448 mono_set_generic_sharing_vt_supported (TRUE);
11450 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11452 generate_aotid ((guint8*) &acfg->image->aotid);
11454 char *aotid = mono_guid_to_string (acfg->image->aotid);
11455 aot_printf (acfg, "AOTID %s\n", aotid);
11458 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11459 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11460 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11465 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11466 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11470 if (acfg->aot_opts.static_link)
11471 acfg->aot_opts.asm_writer = TRUE;
11473 if (acfg->aot_opts.soft_debug) {
11474 MonoDebugOptions *opt = mini_get_debug_options ();
11476 opt->mdb_optimizations = TRUE;
11477 opt->gen_sdb_seq_points = TRUE;
11479 if (!mono_debug_enabled ()) {
11480 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11483 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11486 if (mono_use_llvm || acfg->aot_opts.llvm) {
11488 acfg->aot_opts.asm_writer = TRUE;
11489 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11491 if (acfg->aot_opts.soft_debug) {
11492 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11498 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11499 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11504 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11505 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11506 acfg->is_full_aot = TRUE;
11509 if (mono_threads_is_coop_enabled ())
11510 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11512 if (acfg->aot_opts.instances_logfile_path) {
11513 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11514 if (!acfg->instances_logfile) {
11515 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11520 if (acfg->aot_opts.profile_files) {
11523 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11524 load_profile_file (acfg, (char*)l->data);
11531 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11532 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11536 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11537 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11538 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11540 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11541 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11542 if (acfg->opts & MONO_OPT_GSHAREDVT)
11543 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11546 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11550 if (mono_use_llvm || acfg->aot_opts.llvm) {
11553 * Emit all LLVM code into a separate assembly/object file and link with it
11556 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11557 acfg->llvm_owriter = TRUE;
11558 } else if (acfg->aot_opts.llvm_outfile) {
11559 int len = strlen (acfg->aot_opts.llvm_outfile);
11561 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11562 acfg->llvm_owriter = TRUE;
11566 if (acfg->llvm && acfg->thumb_mixed)
11567 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11568 if (acfg->aot_opts.llvm_only)
11569 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11571 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11572 /* Get rid of characters which cannot occur in symbols */
11573 for (p = acfg->assembly_name_sym; *p; ++p) {
11574 if (!(isalnum (*p) || *p == '_'))
11578 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11579 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11580 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11582 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11583 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11586 acfg->method_index = 1;
11588 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11589 mono_set_partial_sharing_supported (TRUE);
11591 res = collect_methods (acfg);
11598 for (l = acfg->profile_data; l; l = l->next)
11599 resolve_profile_data (acfg, (ProfileData*)l->data);
11600 for (l = acfg->profile_data; l; l = l->next)
11601 add_profile_instances (acfg, (ProfileData*)l->data);
11604 acfg->cfgs_size = acfg->methods->len + 32;
11605 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11607 /* PLT offset 0 is reserved for the PLT trampoline */
11608 acfg->plt_offset = 1;
11609 add_preinit_got_slots (acfg);
11614 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11620 compile_methods (acfg);
11624 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11630 if (acfg->aot_opts.asm_only) {
11631 if (acfg->aot_opts.outfile) {
11632 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11633 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11635 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11636 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11638 g_assert (acfg->aot_opts.llvm_outfile);
11639 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11640 if (acfg->llvm_owriter)
11641 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11643 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11645 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11646 g_strdup_printf ("%s", "temp") :
11647 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11649 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11650 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11651 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11656 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11657 if (acfg->aot_opts.outfile)
11658 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11660 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11661 acfg->fp = fopen (acfg->tmpfname, "w+");
11663 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11664 acfg->fp = fdopen (i, "w+");
11666 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11667 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11671 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11673 tmp_outfile_name = NULL;
11674 outfile_name = NULL;
11676 /* Compute symbols for methods */
11677 for (i = 0; i < acfg->nmethods; ++i) {
11678 if (acfg->cfgs [i]) {
11679 MonoCompile *cfg = acfg->cfgs [i];
11680 int method_index = get_method_index (acfg, cfg->orig_method);
11682 if (COMPILE_LLVM (cfg))
11683 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11684 else if (acfg->global_symbols || acfg->llvm)
11685 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11687 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11688 cfg->asm_debug_symbol = cfg->asm_symbol;
11692 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11694 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11696 acfg->gas_line_numbers = TRUE;
11699 #ifdef EMIT_DWARF_INFO
11700 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11701 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11702 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11705 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11707 #endif /* EMIT_DWARF_INFO */
11710 mono_img_writer_emit_start (acfg->w);
11713 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11719 emit_extra_methods (acfg);
11721 emit_trampolines (acfg);
11723 emit_class_name_table (acfg);
11725 emit_got_info (acfg, FALSE);
11727 emit_got_info (acfg, TRUE);
11729 emit_exception_info (acfg);
11731 emit_unwind_info (acfg);
11733 emit_class_info (acfg);
11737 emit_image_table (acfg);
11743 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11746 const char *gc_name = mono_gc_get_gc_name ();
11747 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11752 emit_objc_selectors (acfg);
11754 emit_globals (acfg);
11756 emit_file_info (acfg);
11758 emit_library_info (acfg);
11761 emit_dwarf_info (acfg);
11762 mono_dwarf_writer_close (acfg->dwarf);
11765 emit_mem_end (acfg);
11767 if (acfg->need_pt_gnu_stack) {
11768 /* This is required so the .so doesn't have an executable stack */
11769 /* The bin writer already emits this */
11770 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11773 if (acfg->aot_opts.data_outfile)
11774 fclose (acfg->data_outfile);
11780 res = emit_llvm_file (acfg);
11788 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11791 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11793 strcpy (llvm_stats_msg, "");
11795 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;
11797 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",
11798 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11799 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11800 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11801 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11802 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11803 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,
11804 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11805 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11806 (int)(acfg->got_offset * sizeof (gpointer)));
11807 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11808 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11810 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11811 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11812 if (acfg->stats.genericcount)
11813 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11814 if (acfg->stats.abscount)
11815 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11816 if (acfg->stats.lmfcount)
11817 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11818 if (acfg->stats.ocount)
11819 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11823 res = mono_img_writer_emit_writeout (acfg->w);
11828 res = compile_asm (acfg);
11835 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11837 if (acfg->aot_opts.stats) {
11840 aot_printf (acfg, "GOT slot distribution:\n");
11841 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11842 if (acfg->stats.got_slot_types [i])
11843 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]);
11844 aot_printf (acfg, "\nMethod stats:\n");
11845 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11846 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11847 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11848 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11851 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);
11853 if (acfg->aot_opts.dump_json)
11866 mono_aot_readonly_field_override (MonoClassField *field)
11872 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11878 mono_aot_is_shared_got_offset (int offset)