2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
7 * Johan Lorensson (lateralusx.github@gmail.com)
9 * (C) 2002 Ximian, Inc.
10 * Copyright 2003-2011 Novell, Inc
11 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #include <sys/types.h>
36 #include <mono/metadata/abi-details.h>
37 #include <mono/metadata/tabledefs.h>
38 #include <mono/metadata/class.h>
39 #include <mono/metadata/object.h>
40 #include <mono/metadata/tokentype.h>
41 #include <mono/metadata/appdomain.h>
42 #include <mono/metadata/debug-helpers.h>
43 #include <mono/metadata/assembly.h>
44 #include <mono/metadata/metadata-internals.h>
45 #include <mono/metadata/reflection-internals.h>
46 #include <mono/metadata/marshal.h>
47 #include <mono/metadata/gc-internals.h>
48 #include <mono/metadata/mempool-internals.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/threads-types.h>
51 #include <mono/utils/mono-logger-internals.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-time.h>
54 #include <mono/utils/mono-mmap.h>
55 #include <mono/utils/mono-rand.h>
56 #include <mono/utils/json.h>
57 #include <mono/utils/mono-threads-coop.h>
58 #include <mono/profiler/mono-profiler-aot.h>
59 #include <mono/utils/w32api.h>
61 #include "aot-compiler.h"
62 #include "seq-points.h"
63 #include "image-writer.h"
64 #include "dwarfwriter.h"
66 #include "mini-llvm.h"
68 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
70 // Use MSVC toolchain, Clang for MSVC using MSVC codegen and linker, when compiling for AMD64
71 // targeting WIN32 platforms running AOT compiler on WIN32 platform with VS installation.
72 #if defined(TARGET_AMD64) && defined(TARGET_WIN32) && defined(HOST_WIN32) && defined(_MSC_VER)
73 #define TARGET_X86_64_WIN32_MSVC
76 #if defined(TARGET_X86_64_WIN32_MSVC)
77 #define TARGET_WIN32_MSVC
80 #if defined(__linux__) || defined(__native_client_codegen__)
81 #define RODATA_SECT ".rodata"
82 #elif defined(TARGET_MACH)
83 #define RODATA_SECT ".section __TEXT, __const"
84 #elif defined(TARGET_WIN32_MSVC)
85 #define RODATA_SECT ".rdata"
87 #define RODATA_SECT ".text"
90 #define TV_DECLARE(name) gint64 name
91 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
92 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
94 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
95 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
96 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
103 typedef struct ClassProfileData ClassProfileData;
107 ClassProfileData **argv;
108 MonoGenericInst *inst;
111 struct ClassProfileData {
112 ImageProfileData *image;
114 GInstProfileData *inst;
119 ClassProfileData *klass;
124 GInstProfileData *inst;
129 GHashTable *images, *classes, *ginsts, *methods;
132 /* predefined values for static readonly fields without needed to run the .cctor */
133 typedef struct _ReadOnlyValue ReadOnlyValue;
134 struct _ReadOnlyValue {
137 int type; /* to be used later for typechecking to prevent user errors */
146 static ReadOnlyValue *readonly_values;
148 typedef struct MonoAotOptions {
152 GList *profile_files;
154 gboolean write_symbols;
155 gboolean metadata_only;
156 gboolean bind_to_runtime_version;
159 gboolean static_link;
163 gboolean dwarf_debug;
165 gboolean log_generics;
166 gboolean log_instances;
167 gboolean gen_msym_dir;
168 char *gen_msym_dir_path;
169 gboolean direct_pinvoke;
170 gboolean direct_icalls;
171 gboolean no_direct_calls;
172 gboolean use_trampolines_page;
173 gboolean no_instances;
179 int nrgctx_trampolines;
180 int nimt_trampolines;
181 int ngsharedvt_arg_trampolines;
182 int nrgctx_fetch_trampolines;
183 gboolean print_skipped_methods;
191 char *instances_logfile_path;
194 gboolean profile_only;
199 METHOD_CAT_GSHAREDVT,
205 typedef struct MonoAotStats {
206 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
207 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
208 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
209 int got_slots, offsets_size;
210 int method_categories [METHOD_CAT_NUM];
211 int got_slot_types [MONO_PATCH_INFO_NUM];
212 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
213 int jit_time, gen_time, link_time;
216 typedef struct GotInfo {
217 GHashTable *patch_to_got_offset;
218 GHashTable **patch_to_got_offset_by_type;
219 GPtrArray *got_patches;
222 typedef struct MonoAotCompile {
225 GHashTable *method_indexes;
226 GHashTable *method_depth;
229 GHashTable **patch_to_plt_entry;
230 GHashTable *plt_offset_to_entry;
231 //GHashTable *patch_to_got_offset;
232 //GHashTable **patch_to_got_offset_by_type;
233 //GPtrArray *got_patches;
234 GotInfo got_info, llvm_got_info;
235 GHashTable *image_hash;
236 GHashTable *method_to_cfg;
237 GHashTable *token_info_hash;
238 GHashTable *method_to_pinvoke_import;
239 GPtrArray *extra_methods;
240 GPtrArray *image_table;
242 GPtrArray *method_order;
243 GHashTable *export_names;
244 /* Maps MonoClass* -> blob offset */
245 GHashTable *klass_blob_hash;
246 /* Maps MonoMethod* -> blob offset */
247 GHashTable *method_blob_hash;
248 GHashTable *gsharedvt_in_signatures;
249 GHashTable *gsharedvt_out_signatures;
250 guint32 *plt_got_info_offsets;
251 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
252 /* Number of GOT entries reserved for trampolines */
253 guint32 num_trampoline_got_entries;
254 guint32 tramp_page_size;
256 guint32 table_offsets [MONO_AOT_TABLE_NUM];
257 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
258 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
259 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
260 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
262 MonoAotOptions aot_opts;
266 MonoMemPool *mempool;
269 char *static_linking_symbol;
271 gboolean gas_line_numbers;
272 /* Whenever to emit an object file directly from llc */
273 gboolean llvm_owriter;
274 gboolean llvm_owriter_supported;
276 MonoDwarfWriter *dwarf;
283 GHashTable *unwind_info_offsets;
284 GPtrArray *unwind_ops;
285 guint32 unwind_info_offset;
288 char *llvm_got_symbol;
290 char *llvm_eh_frame_symbol;
291 GHashTable *method_label_hash;
292 const char *temp_prefix;
293 const char *user_symbol_prefix;
294 const char *llvm_label_prefix;
295 const char *inst_directive;
297 guint32 label_generator;
299 gboolean has_jitted_code;
300 MonoAotFileFlags flags;
301 MonoDynamicStream blob;
302 gboolean blob_closed;
303 GHashTable *typespec_classes;
306 char *assembly_name_sym;
307 GHashTable *plt_entry_debug_sym_cache;
308 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
309 GHashTable *ginst_hash;
310 GHashTable *dwarf_ln_filenames;
311 gboolean global_symbols;
312 int objc_selector_index, objc_selector_index_2;
313 GPtrArray *objc_selectors;
314 GHashTable *objc_selector_to_index;
316 GHashTable *profile_methods;
318 FILE *instances_logfile;
326 char *symbol, *llvm_symbol, *debug_sym;
328 gboolean jit_used, llvm_used;
331 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
332 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
334 /* This points to the current acfg in LLVM mode */
335 static MonoAotCompile *llvm_acfg;
337 #ifdef HAVE_ARRAY_ELEM_INIT
338 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
339 #define MSGSTRFIELD1(line) str##line
340 static const struct msgstr_t {
341 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
342 #include "patch-info.h"
345 #define PATCH_INFO(a,b) b,
346 #include "patch-info.h"
349 static const gint16 opidx [] = {
350 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
351 #include "patch-info.h"
355 static G_GNUC_UNUSED const char*
356 get_patch_name (int info)
358 return (const char*)&opstr + opidx [info];
362 #define PATCH_INFO(a,b) b,
363 static const char* const
364 patch_types [MONO_PATCH_INFO_NUM + 1] = {
365 #include "patch-info.h"
369 static G_GNUC_UNUSED const char*
370 get_patch_name (int info)
372 return patch_types [info];
378 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
381 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
384 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out);
387 add_profile_instances (MonoAotCompile *acfg, ProfileData *data);
390 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
396 output = acfg->logfile;
400 va_start (args, format);
401 vfprintf (output, format, args);
406 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
412 output = acfg->logfile;
416 va_start (args, format);
417 vfprintf (output, format, args);
422 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
427 if (mono_error_ok (error))
431 output = acfg->logfile;
435 va_start (args, format);
436 vfprintf (output, format, args);
438 mono_error_cleanup (error);
440 g_error ("FullAOT cannot continue if there are loader errors");
443 /* Wrappers around the image writer functions */
445 #define MAX_SYMBOL_SIZE 256
447 static inline const char *
448 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
450 gsize needed_size = length;
452 g_assert (NULL != symbol);
453 g_assert (NULL != mangled_symbol);
454 g_assert (0 != length);
456 #if defined(TARGET_WIN32) && defined(TARGET_X86)
457 if (symbol && '_' != symbol [0]) {
458 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
460 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
463 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
466 g_assert (0 <= needed_size && needed_size < length);
467 return mangled_symbol;
471 mangle_symbol_alloc (const char * symbol)
473 g_assert (NULL != symbol);
475 #if defined(TARGET_WIN32) && defined(TARGET_X86)
476 if (symbol && '_' != symbol [0]) {
477 return g_strdup_printf ("_%s", symbol);
480 return g_strdup_printf ("%s", symbol);
483 return g_strdup_printf ("%s", symbol);
488 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
490 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
493 #if defined(TARGET_WIN32) && defined(TARGET_X86)
496 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
498 const char * mangled_symbol_name = name;
499 char * mangled_symbol_name_alloc = NULL;
502 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
503 mangled_symbol_name = mangled_symbol_name_alloc;
506 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
507 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
509 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
511 if (NULL != mangled_symbol_name_alloc) {
512 g_free (mangled_symbol_name_alloc);
519 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
521 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
527 emit_label (MonoAotCompile *acfg, const char *name)
529 mono_img_writer_emit_label (acfg->w, name);
533 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
535 mono_img_writer_emit_bytes (acfg->w, buf, size);
539 emit_string (MonoAotCompile *acfg, const char *value)
541 mono_img_writer_emit_string (acfg->w, value);
545 emit_line (MonoAotCompile *acfg)
547 mono_img_writer_emit_line (acfg->w);
551 emit_alignment (MonoAotCompile *acfg, int size)
553 mono_img_writer_emit_alignment (acfg->w, size);
557 emit_alignment_code (MonoAotCompile *acfg, int size)
559 if (acfg->align_pad_value)
560 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
562 mono_img_writer_emit_alignment (acfg->w, size);
566 emit_padding (MonoAotCompile *acfg, int size)
571 if (acfg->align_pad_value) {
572 for (i = 0; i < 16; ++i)
573 buf [i] = acfg->align_pad_value;
575 memset (buf, 0, sizeof (buf));
578 for (i = 0; i < size; i += 16) {
580 emit_bytes (acfg, buf, size - i);
582 emit_bytes (acfg, buf, 16);
587 emit_pointer (MonoAotCompile *acfg, const char *target)
589 mono_img_writer_emit_pointer (acfg->w, target);
593 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
595 if (prefix [0] != '\0') {
596 char *s = g_strdup_printf ("%s%s", prefix, target);
597 mono_img_writer_emit_pointer (acfg->w, s);
600 mono_img_writer_emit_pointer (acfg->w, target);
605 emit_int16 (MonoAotCompile *acfg, int value)
607 mono_img_writer_emit_int16 (acfg->w, value);
611 emit_int32 (MonoAotCompile *acfg, int value)
613 mono_img_writer_emit_int32 (acfg->w, value);
617 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
619 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
623 emit_zero_bytes (MonoAotCompile *acfg, int num)
625 mono_img_writer_emit_zero_bytes (acfg->w, num);
629 emit_byte (MonoAotCompile *acfg, guint8 val)
631 mono_img_writer_emit_byte (acfg->w, val);
634 #if defined(TARGET_WIN32) && defined(TARGET_X86)
636 static G_GNUC_UNUSED void
637 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
639 const char * mangled_symbol_name = name;
640 char * mangled_symbol_name_alloc = NULL;
642 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
643 mangled_symbol_name = mangled_symbol_name_alloc;
645 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
646 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
648 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
650 if (NULL != mangled_symbol_name_alloc) {
651 g_free (mangled_symbol_name_alloc);
657 static G_GNUC_UNUSED void
658 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
660 mono_img_writer_emit_global (acfg->w, name, func);
665 static inline gboolean
666 link_shared_library (MonoAotCompile *acfg)
668 return !acfg->aot_opts.static_link && !acfg->aot_opts.asm_only;
671 static inline gboolean
672 add_to_global_symbol_table (MonoAotCompile *acfg)
674 #ifdef TARGET_WIN32_MSVC
675 return acfg->aot_opts.no_dlsym || link_shared_library (acfg);
677 return acfg->aot_opts.no_dlsym;
682 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
684 if (add_to_global_symbol_table (acfg))
685 g_ptr_array_add (acfg->globals, g_strdup (name));
687 if (acfg->aot_opts.no_dlsym) {
688 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
690 emit_global_inner (acfg, name, func);
695 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
697 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
700 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
702 emit_info_symbol (MonoAotCompile *acfg, const char *name)
704 char symbol [MAX_SYMBOL_SIZE];
707 emit_label (acfg, name);
708 /* LLVM generated code references this */
709 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
710 emit_label (acfg, symbol);
711 emit_global_inner (acfg, symbol, FALSE);
713 emit_label (acfg, name);
718 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
721 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
725 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
727 /* On apple, all symbols need to be aligned to avoid warnings from ld */
728 emit_alignment (acfg, 4);
730 mono_img_writer_emit_label (acfg->w, name);
731 mono_img_writer_emit_string (acfg->w, value);
734 static G_GNUC_UNUSED void
735 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
738 guint8 b = value & 0x7f;
740 if (value != 0) /* more bytes to come */
746 static G_GNUC_UNUSED void
747 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
750 gboolean negative = (value < 0);
757 /* the following is unnecessary if the
758 * implementation of >>= uses an arithmetic rather
759 * than logical shift for a signed left operand
763 value |= - ((gint64)1 <<(size - 7));
764 /* sign bit of byte is second high order bit (0x40) */
765 if ((value == 0 && !(byte & 0x40)) ||
766 (value == -1 && (byte & 0x40)))
770 emit_byte (acfg, byte);
774 static G_GNUC_UNUSED void
775 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
780 guint8 b = value & 0x7f;
782 if (value != 0) /* more bytes to come */
790 static G_GNUC_UNUSED void
791 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
794 gboolean negative = (value < 0);
802 /* the following is unnecessary if the
803 * implementation of >>= uses an arithmetic rather
804 * than logical shift for a signed left operand
808 value |= - (1 <<(size - 7));
809 /* sign bit of byte is second high order bit (0x40) */
810 if ((value == 0 && !(byte & 0x40)) ||
811 (value == -1 && (byte & 0x40)))
822 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
825 buf [0] = (val >> 0) & 0xff;
826 buf [1] = (val >> 8) & 0xff;
827 buf [2] = (val >> 16) & 0xff;
828 buf [3] = (val >> 24) & 0xff;
834 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
836 buf [0] = (val >> 0) & 0xff;
837 buf [1] = (val >> 8) & 0xff;
843 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
845 int len = strlen (s);
847 memcpy (buf, s, len + 1);
848 *endbuf = buf + len + 1;
852 emit_unset_mode (MonoAotCompile *acfg)
854 mono_img_writer_emit_unset_mode (acfg->w);
857 static G_GNUC_UNUSED void
858 emit_set_thumb_mode (MonoAotCompile *acfg)
860 emit_unset_mode (acfg);
861 fprintf (acfg->fp, ".code 16\n");
864 static G_GNUC_UNUSED void
865 emit_set_arm_mode (MonoAotCompile *acfg)
867 emit_unset_mode (acfg);
868 fprintf (acfg->fp, ".code 32\n");
872 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
877 g_assert (size % 4 == 0);
878 emit_unset_mode (acfg);
879 for (i = 0; i < size; i += 4)
880 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
882 emit_bytes (acfg, buf, size);
886 /* ARCHITECTURE SPECIFIC CODE */
888 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
889 #define EMIT_DWARF_INFO 1
892 #ifdef TARGET_WIN32_MSVC
893 #undef EMIT_DWARF_INFO
896 #if defined(TARGET_ARM)
897 #define AOT_FUNC_ALIGNMENT 4
899 #define AOT_FUNC_ALIGNMENT 16
902 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
903 #define PPC_LD_OP "ld"
904 #define PPC_LDX_OP "ldx"
906 #define PPC_LD_OP "lwz"
907 #define PPC_LDX_OP "lwzx"
910 #ifdef TARGET_X86_64_WIN32_MSVC
911 #define AOT_TARGET_STR "AMD64 (WIN32) (MSVC codegen)"
913 #define AOT_TARGET_STR "AMD64"
918 #define AOT_TARGET_STR "ARM (MACH)"
920 #define AOT_TARGET_STR "ARM (!MACH)"
926 #define AOT_TARGET_STR "ARM64 (MACH)"
928 #define AOT_TARGET_STR "ARM64 (!MACH)"
932 #ifdef TARGET_POWERPC64
933 #ifdef __mono_ilp32__
934 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
936 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
939 #ifdef TARGET_POWERPC
940 #ifdef __mono_ilp32__
941 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
943 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
950 #define AOT_TARGET_STR "X86 (WIN32)"
951 #elif defined(__native_client_codegen__)
952 #define AOT_TARGET_STR "X86 (native client codegen)"
954 #define AOT_TARGET_STR "X86 (!native client codegen)"
958 #ifndef AOT_TARGET_STR
959 #define AOT_TARGET_STR ""
963 arch_init (MonoAotCompile *acfg)
965 acfg->llc_args = g_string_new ("");
966 acfg->as_args = g_string_new ("");
967 acfg->llvm_owriter_supported = TRUE;
970 * The prefix LLVM likes to put in front of symbol names on darwin.
971 * The mach-os specs require this for globals, but LLVM puts them in front of all
972 * symbols. We need to handle this, since we need to refer to LLVM generated
975 acfg->llvm_label_prefix = "";
976 acfg->user_symbol_prefix = "";
978 #if defined(TARGET_X86)
979 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
982 #if defined(TARGET_AMD64)
983 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
985 acfg->align_pad_value = 0x90;
989 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
990 g_string_append (acfg->llc_args, "-mattr=+v6");
992 #if defined(ARM_FPU_VFP_HARD)
993 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
994 g_string_append (acfg->as_args, " -mfpu=vfp3");
995 #elif defined(ARM_FPU_VFP)
996 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
997 g_string_append (acfg->as_args, " -mfpu=vfp3");
999 g_string_append (acfg->llc_args, " -soft-float");
1002 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
1003 acfg->thumb_mixed = TRUE;
1005 if (acfg->aot_opts.mtriple)
1006 mono_arch_set_target (acfg->aot_opts.mtriple);
1010 acfg->inst_directive = ".inst";
1011 if (acfg->aot_opts.mtriple)
1012 mono_arch_set_target (acfg->aot_opts.mtriple);
1016 acfg->user_symbol_prefix = "_";
1017 acfg->llvm_label_prefix = "_";
1018 acfg->inst_directive = ".word";
1019 acfg->need_no_dead_strip = TRUE;
1020 acfg->aot_opts.gnu_asm = TRUE;
1023 #if defined(__linux__) && !defined(TARGET_ARM)
1024 acfg->need_pt_gnu_stack = TRUE;
1028 acfg->global_symbols = TRUE;
1031 #ifdef TARGET_ANDROID
1032 acfg->llvm_owriter_supported = FALSE;
1039 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
1041 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
1045 g_assert (acfg->fp);
1046 emit_unset_mode (acfg);
1048 offset = (int)(got_slot * sizeof (gpointer));
1050 /* clang's integrated assembler */
1051 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
1052 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
1053 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
1056 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
1057 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
1058 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
1063 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1067 g_assert (acfg->fp);
1068 emit_unset_mode (acfg);
1070 /* ldr rt, target */
1071 reg = arm_get_ldr_lit_reg (code);
1073 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
1074 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
1075 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
1081 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1083 g_assert (acfg->fp);
1084 emit_unset_mode (acfg);
1085 if (ji && ji->relocation == MONO_R_ARM64_B) {
1086 fprintf (acfg->fp, "b %s\n", target);
1089 g_assert (ji->relocation == MONO_R_ARM64_BL);
1090 fprintf (acfg->fp, "bl %s\n", target);
1096 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1100 /* ldr rt, target */
1101 reg = arm_get_ldr_lit_reg (code);
1102 arm64_emit_load_got_slot (acfg, reg, got_slot);
1107 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1109 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1110 fprintf (acfg->fp, "br x16\n");
1111 /* Used by mono_aot_get_plt_info_offset () */
1112 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1116 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1122 /* The common code */
1125 /* The trampoline address is in IP0 */
1126 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1127 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1128 /* Compute the data slot address */
1129 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1130 /* Trampoline argument */
1131 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1133 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1134 arm_brx (code, ARMREG_IP0);
1137 emit_code_bytes (acfg, buf, code - buf);
1143 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1149 count = (pagesize - common_tramp_size) / specific_tramp_size;
1150 for (i = 0; i < count; ++i) {
1152 arm_adrx (code, ARMREG_IP0, code);
1153 /* Branch to the generic code */
1154 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1155 /* This has to be 2 pointers long */
1158 g_assert (code - buf == specific_tramp_size);
1159 emit_code_bytes (acfg, buf, code - buf);
1164 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1168 guint8 *labels [16];
1169 int common_tramp_size;
1170 int specific_tramp_size = 2 * 8;
1174 if (!acfg->aot_opts.use_trampolines_page)
1178 /* Have to match the target pagesize */
1181 pagesize = mono_pagesize ();
1183 acfg->tramp_page_size = pagesize;
1185 /* The specific trampolines */
1186 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1187 emit_alignment (acfg, pagesize);
1188 emit_global (acfg, symbol, TRUE);
1189 emit_label (acfg, symbol);
1191 /* The common code */
1192 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1193 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1195 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1197 /* The rgctx trampolines */
1198 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1199 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1200 emit_alignment (acfg, pagesize);
1201 emit_global (acfg, symbol, TRUE);
1202 emit_label (acfg, symbol);
1204 /* The common code */
1205 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1206 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1208 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1210 /* The gsharedvt arg trampolines */
1211 /* These are the same as the specific trampolines */
1212 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1213 emit_alignment (acfg, pagesize);
1214 emit_global (acfg, symbol, TRUE);
1215 emit_label (acfg, symbol);
1217 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1218 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1220 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1222 /* The IMT trampolines */
1223 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1224 emit_alignment (acfg, pagesize);
1225 emit_global (acfg, symbol, TRUE);
1226 emit_label (acfg, symbol);
1230 /* The trampoline address is in IP0 */
1231 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1232 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1233 /* Compute the data slot address */
1234 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1235 /* Trampoline argument */
1236 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1238 /* Same as arch_emit_imt_trampoline () */
1240 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1241 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1243 arm_bcc (code, ARMCOND_EQ, 0);
1245 /* End-of-loop check */
1247 arm_cbzx (code, ARMREG_IP0, 0);
1250 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1251 arm_b (code, labels [0]);
1254 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1255 /* Load vtable slot addr */
1256 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1257 /* Load vtable slot */
1258 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1259 arm_brx (code, ARMREG_IP0);
1262 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1263 /* Load fail addr */
1264 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1265 arm_brx (code, ARMREG_IP0);
1267 emit_code_bytes (acfg, buf, code - buf);
1269 common_tramp_size = code - buf;
1270 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1272 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1276 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1278 /* Load argument from second GOT slot */
1279 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1280 /* Load generic trampoline address from first GOT slot */
1281 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1282 fprintf (acfg->fp, "br x16\n");
1283 *tramp_size = 7 * 4;
1287 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1289 emit_unset_mode (acfg);
1290 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1291 fprintf (acfg->fp, "b %s\n", call_target);
1295 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1297 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1299 /* Load argument from first GOT slot */
1300 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1301 /* Load generic trampoline address from second GOT slot */
1302 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1303 fprintf (acfg->fp, "br x16\n");
1304 *tramp_size = 7 * 4;
1308 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1311 guint8 *code, *labels [16];
1313 /* Load parameter from GOT slot into ip1 */
1314 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1318 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1319 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1321 arm_bcc (code, ARMCOND_EQ, 0);
1323 /* End-of-loop check */
1325 arm_cbzx (code, ARMREG_IP0, 0);
1328 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1329 arm_b (code, labels [0]);
1332 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1333 /* Load vtable slot addr */
1334 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1335 /* Load vtable slot */
1336 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1337 arm_brx (code, ARMREG_IP0);
1340 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1341 /* Load fail addr */
1342 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1343 arm_brx (code, ARMREG_IP0);
1345 emit_code_bytes (acfg, buf, code - buf);
1347 *tramp_size = code - buf + (3 * 4);
1351 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1353 /* Similar to the specific trampolines, but the address is in the second slot */
1354 /* Load argument from first GOT slot */
1355 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1356 /* Load generic trampoline address from second GOT slot */
1357 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1358 fprintf (acfg->fp, "br x16\n");
1359 *tramp_size = 7 * 4;
1365 #ifdef MONO_ARCH_AOT_SUPPORTED
1367 * arch_emit_direct_call:
1369 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1373 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1375 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1376 /* Need to make sure this is exactly 5 bytes long */
1377 emit_unset_mode (acfg);
1378 fprintf (acfg->fp, "call %s\n", target);
1380 #elif defined(TARGET_ARM)
1381 emit_unset_mode (acfg);
1383 fprintf (acfg->fp, "blx %s\n", target);
1385 fprintf (acfg->fp, "bl %s\n", target);
1387 #elif defined(TARGET_ARM64)
1388 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1389 #elif defined(TARGET_POWERPC)
1390 emit_unset_mode (acfg);
1391 fprintf (acfg->fp, "bl %s\n", target);
1394 g_assert_not_reached ();
1401 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1403 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1404 * in in the 2. slot of every GOT, and require every method to place the GOT
1405 * address in r30, even when it doesn't access the GOT otherwise. This way,
1406 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1411 * PPC64 uses function descriptors which greatly complicate all code, since
1412 * these are used very inconsistently in the runtime. Some functions like
1413 * mono_compile_method () return ftn descriptors, while others like the
1414 * trampoline creation functions do not.
1415 * We assume that all GOT slots contain function descriptors, and create
1416 * descriptors in aot-runtime.c when needed.
1417 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1418 * from function descriptors, we could do the same, but it would require
1419 * rewriting all the ppc/aot code to handle function descriptors properly.
1420 * So instead, we use the same approach as on PPC32.
1421 * This is a horrible mess, but fixing it would probably lead to an even bigger
1427 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1430 #ifdef MONO_ARCH_AOT_SUPPORTED
1432 * arch_emit_got_offset:
1434 * The memory pointed to by CODE should hold native code for computing the GOT
1435 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1436 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1439 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1441 #if defined(TARGET_POWERPC64)
1442 emit_unset_mode (acfg);
1444 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1445 * unsupported relocations. So we store the got address into the .Lgot_addr
1446 * symbol which is in the text segment, compute its address, and load it.
1448 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1449 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1450 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1451 fprintf (acfg->fp, "add 30, 30, 0\n");
1452 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1453 acfg->label_generator ++;
1455 #elif defined(TARGET_POWERPC)
1456 emit_unset_mode (acfg);
1457 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1458 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1459 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1460 acfg->label_generator ++;
1463 guint32 offset = mono_arch_get_patch_offset (code);
1464 emit_bytes (acfg, code, offset);
1465 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1467 *code_size = offset + 4;
1472 * arch_emit_got_access:
1474 * The memory pointed to by CODE should hold native code for loading a GOT
1475 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1476 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1479 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1482 /* mov reg, got+offset(%rip) */
1484 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1488 /* Decode reg, see amd64_mov_reg_membase () */
1489 rex_r = code [0] & AMD64_REX_R;
1490 g_assert (code [0] == 0x49 + rex_r);
1491 g_assert (code [1] == 0x8b);
1492 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1494 emit_unset_mode (acfg);
1495 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1498 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1499 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1500 *code_size = mono_arch_get_patch_offset (code) + 4;
1502 #elif defined(TARGET_X86)
1503 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1504 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1505 *code_size = mono_arch_get_patch_offset (code) + 4;
1506 #elif defined(TARGET_ARM)
1507 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1508 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1509 *code_size = mono_arch_get_patch_offset (code) + 4;
1510 #elif defined(TARGET_ARM64)
1511 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1512 arm64_emit_got_access (acfg, code, got_slot, code_size);
1513 #elif defined(TARGET_POWERPC)
1517 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1519 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1520 g_assert (code - buf == 8);
1521 emit_bytes (acfg, buf, code - buf);
1522 *code_size = code - buf;
1525 g_assert_not_reached ();
1531 #ifdef MONO_ARCH_AOT_SUPPORTED
1533 * arch_emit_objc_selector_ref:
1535 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1538 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1540 #if defined(TARGET_ARM)
1541 char symbol1 [MAX_SYMBOL_SIZE];
1542 char symbol2 [MAX_SYMBOL_SIZE];
1543 int lindex = acfg->objc_selector_index_2 ++;
1545 /* Emit ldr.imm/b */
1546 emit_bytes (acfg, code, 8);
1548 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1549 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1551 emit_label (acfg, symbol1);
1552 mono_img_writer_emit_unset_mode (acfg->w);
1553 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1556 #elif defined(TARGET_ARM64)
1557 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1559 g_assert_not_reached ();
1565 * arch_emit_plt_entry:
1567 * Emit code for the PLT entry.
1568 * The plt entry should look like this:
1569 * <indirect jump to GOT_SYMBOL + OFFSET>
1570 * <INFO_OFFSET embedded into the instruction stream>
1573 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1575 #if defined(TARGET_X86)
1576 /* jmp *<offset>(%ebx) */
1577 emit_byte (acfg, 0xff);
1578 emit_byte (acfg, 0xa3);
1579 emit_int32 (acfg, offset);
1580 /* Used by mono_aot_get_plt_info_offset */
1581 emit_int32 (acfg, info_offset);
1582 #elif defined(TARGET_AMD64)
1583 emit_unset_mode (acfg);
1584 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1585 /* Used by mono_aot_get_plt_info_offset */
1586 emit_int32 (acfg, info_offset);
1587 acfg->stats.plt_size += 10;
1588 #elif defined(TARGET_ARM)
1593 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1594 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1595 emit_bytes (acfg, buf, code - buf);
1596 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1597 /* Used by mono_aot_get_plt_info_offset */
1598 emit_int32 (acfg, info_offset);
1599 #elif defined(TARGET_ARM64)
1600 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1601 #elif defined(TARGET_POWERPC)
1602 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1603 emit_unset_mode (acfg);
1604 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1605 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1606 fprintf (acfg->fp, "add 11, 11, 30\n");
1607 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1608 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1609 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1610 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1612 fprintf (acfg->fp, "mtctr 11\n");
1613 fprintf (acfg->fp, "bctr\n");
1614 emit_int32 (acfg, info_offset);
1616 g_assert_not_reached ();
1621 * arch_emit_llvm_plt_entry:
1623 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1624 * This is only needed on arm to handle thumb interop.
1627 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1629 #if defined(TARGET_ARM)
1630 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1631 /* The caller already transitioned to thumb */
1632 /* The code below should be 12 bytes long */
1633 /* clang has trouble encoding these instructions, so emit the binary */
1635 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1636 /* thumb can't encode ld pc, [pc, ip] */
1637 fprintf (acfg->fp, "add ip, pc, ip\n");
1638 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1639 fprintf (acfg->fp, "bx ip\n");
1641 emit_set_thumb_mode (acfg);
1642 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1643 fprintf (acfg->fp, ".2byte 0x44fc\n");
1644 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1645 fprintf (acfg->fp, ".2byte 0x4760\n");
1646 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1647 emit_int32 (acfg, info_offset);
1648 emit_unset_mode (acfg);
1649 emit_set_arm_mode (acfg);
1651 g_assert_not_reached ();
1655 /* Save unwind_info in the module and emit the offset to the information at symbol */
1656 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1658 guint32 uw_offset, encoded_len;
1661 emit_section_change (acfg, RODATA_SECT, 0);
1662 emit_global (acfg, symbol, FALSE);
1663 emit_label (acfg, symbol);
1665 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1666 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1668 emit_int32 (acfg, uw_offset);
1672 * arch_emit_specific_trampoline_pages:
1674 * Emits a page full of trampolines: each trampoline uses its own address to
1675 * lookup both the generic trampoline code and the data argument.
1676 * This page can be remapped in process multiple times so we can get an
1677 * unlimited number of trampolines.
1678 * Specifically this implementation uses the following trick: two memory pages
1679 * are allocated, with the first containing the data and the second containing the trampolines.
1680 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1681 * implementation does all the lifting.
1682 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1683 * on the arm 32 bit system.
1686 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1688 #if defined(TARGET_ARM)
1691 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1693 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1694 GSList *unwind_ops = NULL;
1695 #define COMMON_TRAMP_SIZE 16
1696 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1697 int imm8, rot_amount;
1700 if (!acfg->aot_opts.use_trampolines_page)
1703 acfg->tramp_page_size = pagesize;
1705 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1706 emit_alignment (acfg, pagesize);
1707 emit_global (acfg, symbol, TRUE);
1708 emit_label (acfg, symbol);
1710 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1712 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1713 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1714 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1715 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1717 g_assert (code - buf == COMMON_TRAMP_SIZE);
1720 emit_bytes (acfg, buf, code - buf);
1722 for (i = 0; i < count; ++i) {
1724 ARM_PUSH (code, 0x5fff);
1726 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1727 g_assert (code - buf == 8);
1728 emit_bytes (acfg, buf, code - buf);
1731 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1732 * the instruction pointer address, so the generic trampoline at the start of the page
1733 * subtracts 4096 to get to the data page and loads the values
1734 * We again fit the generic trampiline in 16 bytes.
1736 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1737 emit_global (acfg, symbol, TRUE);
1738 emit_label (acfg, symbol);
1740 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1741 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1742 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1743 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1745 g_assert (code - buf == COMMON_TRAMP_SIZE);
1748 emit_bytes (acfg, buf, code - buf);
1750 for (i = 0; i < count; ++i) {
1752 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1754 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1755 g_assert (code - buf == 8);
1756 emit_bytes (acfg, buf, code - buf);
1760 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1762 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1763 emit_global (acfg, symbol, TRUE);
1764 emit_label (acfg, symbol);
1766 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1767 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1768 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1769 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1770 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1771 g_assert (code - buf == COMMON_TRAMP_SIZE);
1773 emit_bytes (acfg, buf, code - buf);
1775 for (i = 0; i < count; ++i) {
1777 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1779 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1780 g_assert (code - buf == 8);
1781 emit_bytes (acfg, buf, code - buf);
1784 /* now the imt trampolines: each specific trampolines puts in the ip register
1785 * the instruction pointer address, so the generic trampoline at the start of the page
1786 * subtracts 4096 to get to the data page and loads the values
1788 #define IMT_TRAMP_SIZE 72
1789 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1790 emit_global (acfg, symbol, TRUE);
1791 emit_label (acfg, symbol);
1793 /* Need at least two free registers, plus a slot for storing the pc */
1794 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1796 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1797 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1798 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1800 /* The IMT method is in v5, r0 has the imt array address */
1803 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1804 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1805 imt_found_check = code;
1806 ARM_B_COND (code, ARMCOND_EQ, 0);
1808 /* End-of-loop check */
1809 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1810 loop_end_check = code;
1811 ARM_B_COND (code, ARMCOND_EQ, 0);
1814 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1815 loop_branch_back = code;
1817 arm_patch (loop_branch_back, loop_start);
1820 arm_patch (imt_found_check, code);
1821 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1822 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1823 /* Save it to the third stack slot */
1824 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1825 /* Restore the registers and branch */
1826 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1829 arm_patch (loop_end_check, code);
1830 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1831 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1832 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1836 g_assert (code - buf == IMT_TRAMP_SIZE);
1837 emit_bytes (acfg, buf, code - buf);
1839 for (i = 0; i < count; ++i) {
1841 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1843 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1844 g_assert (code - buf == 8);
1845 emit_bytes (acfg, buf, code - buf);
1848 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1849 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1850 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1851 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1853 /* Unwind info for specifc trampolines */
1854 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1855 /* We unwind to the original caller, from the stack, since lr is clobbered */
1856 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1857 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1858 save_unwind_info (acfg, symbol, unwind_ops);
1859 mono_free_unwind_info (unwind_ops);
1861 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1862 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1863 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1864 save_unwind_info (acfg, symbol, unwind_ops);
1865 mono_free_unwind_info (unwind_ops);
1867 /* Unwind info for rgctx trampolines */
1868 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1869 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1870 save_unwind_info (acfg, symbol, unwind_ops);
1872 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1873 save_unwind_info (acfg, symbol, unwind_ops);
1874 mono_free_unwind_info (unwind_ops);
1876 /* Unwind info for gsharedvt trampolines */
1877 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1878 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1879 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1880 save_unwind_info (acfg, symbol, unwind_ops);
1881 mono_free_unwind_info (unwind_ops);
1883 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1884 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1885 save_unwind_info (acfg, symbol, unwind_ops);
1886 mono_free_unwind_info (unwind_ops);
1888 /* Unwind info for imt trampolines */
1889 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1890 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1891 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1892 save_unwind_info (acfg, symbol, unwind_ops);
1893 mono_free_unwind_info (unwind_ops);
1895 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1896 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1897 save_unwind_info (acfg, symbol, unwind_ops);
1898 mono_free_unwind_info (unwind_ops);
1899 #elif defined(TARGET_ARM64)
1900 arm64_emit_specific_trampoline_pages (acfg);
1905 * arch_emit_specific_trampoline:
1907 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1908 * two GOT slots which contain the generic trampoline address and the trampoline
1909 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1912 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1915 * The trampolines created here are variations of the specific
1916 * trampolines created in mono_arch_create_specific_trampoline (). The
1918 * - the generic trampoline address is taken from a got slot.
1919 * - the offset of the got slot where the trampoline argument is stored
1920 * is embedded in the instruction stream, and the generic trampoline
1921 * can load the argument by loading the offset, adding it to the
1922 * address of the trampoline to get the address of the got slot, and
1923 * loading the argument from there.
1924 * - all the trampolines should be of the same length.
1926 #if defined(TARGET_AMD64)
1927 /* This should be exactly 8 bytes long */
1929 /* call *<offset>(%rip) */
1931 emit_unset_mode (acfg);
1932 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1933 emit_zero_bytes (acfg, 2);
1935 emit_byte (acfg, '\x41');
1936 emit_byte (acfg, '\xff');
1937 emit_byte (acfg, '\x15');
1938 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1939 emit_zero_bytes (acfg, 1);
1941 #elif defined(TARGET_ARM)
1945 /* This should be exactly 20 bytes long */
1948 ARM_PUSH (code, 0x5fff);
1949 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1950 /* Load the value from the GOT */
1951 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1953 ARM_BLX_REG (code, ARMREG_R1);
1955 g_assert (code - buf == 16);
1958 emit_bytes (acfg, buf, code - buf);
1960 * Only one offset is needed, since the second one would be equal to the
1963 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1964 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1965 #elif defined(TARGET_ARM64)
1966 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1967 #elif defined(TARGET_POWERPC)
1975 * PPC has no ip relative addressing, so we need to compute the address
1976 * of the mscorlib got. That is slow and complex, so instead, we store it
1977 * in the second got slot of every aot image. The caller already computed
1978 * the address of its got and placed it into r30.
1980 emit_unset_mode (acfg);
1981 /* Load mscorlib got address */
1982 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1983 /* Load generic trampoline address */
1984 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1985 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1986 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1987 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1988 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1990 fprintf (acfg->fp, "mtctr 11\n");
1991 /* Load trampoline argument */
1992 /* On ppc, we pass it normally to the generic trampoline */
1993 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1994 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1995 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1996 /* Branch to generic trampoline */
1997 fprintf (acfg->fp, "bctr\n");
1999 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2000 *tramp_size = 10 * 4;
2002 *tramp_size = 9 * 4;
2004 #elif defined(TARGET_X86)
2008 /* Similar to the PPC code above */
2010 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
2013 /* Load mscorlib got address */
2014 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2015 /* Push trampoline argument */
2016 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2017 /* Load generic trampoline address */
2018 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
2019 /* Branch to generic trampoline */
2020 x86_jump_reg (code, X86_ECX);
2022 emit_bytes (acfg, buf, code - buf);
2025 g_assert (code - buf == *tramp_size);
2027 g_assert_not_reached ();
2032 * arch_emit_unbox_trampoline:
2034 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
2035 * CALL_TARGET is the symbol pointing to the native code of METHOD.
2038 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
2040 #if defined(TARGET_AMD64)
2045 this_reg = mono_arch_get_this_arg_reg (NULL);
2047 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
2049 emit_bytes (acfg, buf, code - buf);
2052 emit_unset_mode (acfg);
2053 fprintf (acfg->fp, "jmp %s\n", call_target);
2055 emit_byte (acfg, '\xe9');
2056 emit_symbol_diff (acfg, call_target, ".", -4);
2058 #elif defined(TARGET_X86)
2065 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
2067 emit_bytes (acfg, buf, code - buf);
2070 emit_byte (acfg, '\xe9');
2071 emit_symbol_diff (acfg, call_target, ".", -4);
2072 #elif defined(TARGET_ARM)
2076 if (acfg->thumb_mixed && cfg->compile_llvm) {
2077 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
2078 fprintf (acfg->fp, "b %s\n", call_target);
2079 fprintf (acfg->fp, ".arm\n");
2080 fprintf (acfg->fp, ".align 2\n");
2086 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2088 emit_bytes (acfg, buf, code - buf);
2089 /* jump to method */
2090 if (acfg->thumb_mixed && cfg->compile_llvm)
2091 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2093 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2094 #elif defined(TARGET_ARM64)
2095 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2096 #elif defined(TARGET_POWERPC)
2099 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2100 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2102 g_assert_not_reached ();
2107 * arch_emit_static_rgctx_trampoline:
2109 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2110 * two GOT slots which contain the rgctx argument, and the method to jump to.
2111 * TRAMP_SIZE is set to the size of the emitted trampoline.
2112 * These kinds of trampolines cannot be enumerated statically, since there could
2113 * be one trampoline per method instantiation, so we emit the same code for all
2114 * trampolines, and parameterize them using two GOT slots.
2117 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2119 #if defined(TARGET_AMD64)
2120 /* This should be exactly 13 bytes long */
2124 emit_unset_mode (acfg);
2125 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2126 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2128 /* mov <OFFSET>(%rip), %r10 */
2129 emit_byte (acfg, '\x4d');
2130 emit_byte (acfg, '\x8b');
2131 emit_byte (acfg, '\x15');
2132 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2134 /* jmp *<offset>(%rip) */
2135 emit_byte (acfg, '\xff');
2136 emit_byte (acfg, '\x25');
2137 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2139 #elif defined(TARGET_ARM)
2143 /* This should be exactly 24 bytes long */
2146 /* Load rgctx value */
2147 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2148 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2149 /* Load branch addr + branch */
2150 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2151 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2153 g_assert (code - buf == 16);
2156 emit_bytes (acfg, buf, code - buf);
2157 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2158 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2159 #elif defined(TARGET_ARM64)
2160 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2161 #elif defined(TARGET_POWERPC)
2169 * PPC has no ip relative addressing, so we need to compute the address
2170 * of the mscorlib got. That is slow and complex, so instead, we store it
2171 * in the second got slot of every aot image. The caller already computed
2172 * the address of its got and placed it into r30.
2174 emit_unset_mode (acfg);
2175 /* Load mscorlib got address */
2176 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2178 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2179 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2180 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2181 /* Load target address */
2182 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2183 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2184 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2185 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2186 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2187 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2189 fprintf (acfg->fp, "mtctr 11\n");
2190 /* Branch to the target address */
2191 fprintf (acfg->fp, "bctr\n");
2193 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2194 *tramp_size = 11 * 4;
2196 *tramp_size = 9 * 4;
2199 #elif defined(TARGET_X86)
2203 /* Similar to the PPC code above */
2205 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2208 /* Load mscorlib got address */
2209 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2211 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2212 /* Branch to the target address */
2213 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2215 emit_bytes (acfg, buf, code - buf);
2218 g_assert (code - buf == *tramp_size);
2220 g_assert_not_reached ();
2225 * arch_emit_imt_trampoline:
2227 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2228 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2229 * key is the IMT key, and ptr holds the address of a memory location holding
2230 * the address to branch to if the IMT arg matches the key. The array is
2231 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2233 * TRAMP_SIZE is set to the size of the emitted trampoline.
2236 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2238 #if defined(TARGET_AMD64)
2240 guint8 *labels [16];
2242 guint8 *mov_buf_ptr = mov_buf;
2244 const int kSizeOfMove = 7;
2246 code = buf = (guint8 *)g_malloc (256);
2248 /* FIXME: Optimize this, i.e. use binary search etc. */
2249 /* Maybe move the body into a separate function (slower, but much smaller) */
2251 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2254 emit_unset_mode (acfg);
2255 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2259 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2261 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2264 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2266 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2269 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2270 amd64_jump_code (code, labels [0]);
2273 mono_amd64_patch (labels [2], code);
2274 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2275 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2278 mono_amd64_patch (labels [1], code);
2279 /* Load fail tramp */
2280 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2281 /* Check if there is a fail tramp */
2282 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2284 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2285 /* Jump to fail tramp */
2286 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2289 mono_amd64_patch (labels [3], code);
2290 x86_breakpoint (code);
2293 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2294 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2295 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2296 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2297 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2298 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2300 emit_bytes (acfg, buf, code - buf);
2302 *tramp_size = code - buf + kSizeOfMove;
2306 #elif defined(TARGET_X86)
2308 guint8 *labels [16];
2310 code = buf = g_malloc (256);
2312 /* Allocate a temporary stack slot */
2313 x86_push_reg (code, X86_EAX);
2315 x86_push_reg (code, X86_EAX);
2317 /* Load mscorlib got address */
2318 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2320 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2323 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2325 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2328 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2330 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2333 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2334 x86_jump_code (code, labels [0]);
2337 mono_x86_patch (labels [2], code);
2338 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2339 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2340 /* Save the target address to the temporary stack location */
2341 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2343 x86_pop_reg (code, X86_EAX);
2344 /* Jump to the target address */
2348 mono_x86_patch (labels [1], code);
2349 /* Load fail tramp */
2350 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2351 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2353 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2354 /* Jump to fail tramp */
2355 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2356 x86_pop_reg (code, X86_EAX);
2360 mono_x86_patch (labels [3], code);
2361 x86_breakpoint (code);
2363 emit_bytes (acfg, buf, code - buf);
2365 *tramp_size = code - buf;
2369 #elif defined(TARGET_ARM)
2371 guint8 *code, *code2, *labels [16];
2375 /* The IMT method is in v5 */
2377 /* Need at least two free registers, plus a slot for storing the pc */
2378 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2380 /* Load the parameter from the GOT */
2381 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2382 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2385 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2386 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2388 ARM_B_COND (code, ARMCOND_EQ, 0);
2390 /* End-of-loop check */
2391 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2393 ARM_B_COND (code, ARMCOND_EQ, 0);
2396 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2399 arm_patch (labels [4], labels [1]);
2402 arm_patch (labels [2], code);
2403 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2404 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2405 /* Save it to the third stack slot */
2406 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2407 /* Restore the registers and branch */
2408 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2411 arm_patch (labels [3], code);
2412 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2413 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2414 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2418 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2420 emit_bytes (acfg, buf, code - buf);
2421 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2423 *tramp_size = code - buf + 4;
2424 #elif defined(TARGET_ARM64)
2425 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2426 #elif defined(TARGET_POWERPC)
2428 guint8 *code, *labels [16];
2432 /* Load the mscorlib got address */
2433 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2434 /* Load the parameter from the GOT */
2435 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2436 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2438 /* Load and check key */
2440 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2441 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2443 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2445 /* End-of-loop check */
2446 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2448 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2451 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2454 mono_ppc_patch (labels [4], labels [1]);
2457 mono_ppc_patch (labels [2], code);
2458 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2459 /* r12 now contains the value of the vtable slot */
2460 /* this is not a function descriptor on ppc64 */
2461 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2462 ppc_mtctr (code, ppc_r12);
2463 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2466 mono_ppc_patch (labels [3], code);
2470 *tramp_size = code - buf;
2472 emit_bytes (acfg, buf, code - buf);
2474 g_assert_not_reached ();
2479 #if defined (TARGET_AMD64)
2482 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2485 g_assert (acfg->fp);
2486 emit_unset_mode (acfg);
2488 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2495 * arch_emit_gsharedvt_arg_trampoline:
2497 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2498 * two GOT slots which contain the argument, and the code to jump to.
2499 * TRAMP_SIZE is set to the size of the emitted trampoline.
2500 * These kinds of trampolines cannot be enumerated statically, since there could
2501 * be one trampoline per method instantiation, so we emit the same code for all
2502 * trampolines, and parameterize them using two GOT slots.
2505 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2507 #if defined(TARGET_X86)
2511 /* Similar to the PPC code above */
2513 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2516 /* Load mscorlib got address */
2517 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2519 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2520 /* Branch to the target address */
2521 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2523 emit_bytes (acfg, buf, code - buf);
2526 g_assert (code - buf == *tramp_size);
2527 #elif defined(TARGET_ARM)
2531 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2532 /* Similar to arch_emit_specific_trampoline () */
2535 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2536 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2537 /* Load the arg value from the GOT */
2538 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2539 /* Load the addr from the GOT */
2540 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2542 ARM_BX (code, ARMREG_R1);
2544 g_assert (code - buf == 20);
2547 emit_bytes (acfg, buf, code - buf);
2548 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2549 #elif defined(TARGET_ARM64)
2550 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2551 #elif defined (TARGET_AMD64)
2553 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2554 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2555 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2556 fprintf (acfg->fp, "jmp *%%r11\n");
2560 g_assert_not_reached ();
2564 /* END OF ARCH SPECIFIC CODE */
2567 mono_get_field_token (MonoClassField *field)
2569 MonoClass *klass = field->parent;
2572 int fcount = mono_class_get_field_count (klass);
2573 for (i = 0; i < fcount; ++i) {
2574 if (field == &klass->fields [i])
2575 return MONO_TOKEN_FIELD_DEF | (mono_class_get_first_field_idx (klass) + 1 + i);
2578 g_assert_not_reached ();
2583 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2587 //printf ("ENCODE: %d 0x%x.\n", value, value);
2590 * Same encoding as the one used in the metadata, extended to handle values
2591 * greater than 0x1fffffff.
2593 if ((value >= 0) && (value <= 127))
2595 else if ((value >= 0) && (value <= 16383)) {
2596 p [0] = 0x80 | (value >> 8);
2597 p [1] = value & 0xff;
2599 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2600 p [0] = (value >> 24) | 0xc0;
2601 p [1] = (value >> 16) & 0xff;
2602 p [2] = (value >> 8) & 0xff;
2603 p [3] = value & 0xff;
2608 p [1] = (value >> 24) & 0xff;
2609 p [2] = (value >> 16) & 0xff;
2610 p [3] = (value >> 8) & 0xff;
2611 p [4] = value & 0xff;
2619 stream_init (MonoDynamicStream *sh)
2622 sh->alloc_size = 4096;
2623 sh->data = (char *)g_malloc (4096);
2625 /* So offsets are > 0 */
2631 make_room_in_stream (MonoDynamicStream *stream, int size)
2633 if (size <= stream->alloc_size)
2636 while (stream->alloc_size <= size) {
2637 if (stream->alloc_size < 4096)
2638 stream->alloc_size = 4096;
2640 stream->alloc_size *= 2;
2643 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2647 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2651 make_room_in_stream (stream, stream->index + len);
2652 memcpy (stream->data + stream->index, data, len);
2653 idx = stream->index;
2654 stream->index += len;
2661 * Add data to the binary blob inside the aot image. Returns the offset inside the
2662 * blob where the data was stored.
2665 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2667 g_assert (!acfg->blob_closed);
2669 if (acfg->blob.alloc_size == 0)
2670 stream_init (&acfg->blob);
2672 return add_stream_data (&acfg->blob, (char*)data, data_len);
2676 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2681 if (acfg->blob.alloc_size == 0)
2682 stream_init (&acfg->blob);
2684 count = acfg->blob.index % align;
2686 /* we assume the stream data will be aligned */
2688 add_stream_data (&acfg->blob, buf, 4 - count);
2690 return add_stream_data (&acfg->blob, (char*)data, data_len);
2693 /* Emit a table of data into the aot image */
2695 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2697 if (acfg->data_outfile) {
2698 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2699 fwrite (data,1, size, acfg->data_outfile);
2700 acfg->datafile_offset += size;
2701 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2702 int align = 8 - size % 8;
2703 acfg->datafile_offset += align;
2704 guint8 align_buf [16];
2705 memset (&align_buf, 0, sizeof (align_buf));
2706 fwrite (align_buf, align, 1, acfg->data_outfile);
2707 } else if (acfg->llvm) {
2708 mono_llvm_emit_aot_data (symbol, data, size);
2710 emit_section_change (acfg, RODATA_SECT, 0);
2711 emit_alignment (acfg, 8);
2712 emit_label (acfg, symbol);
2713 emit_bytes (acfg, data, size);
2718 * emit_offset_table:
2720 * Emit a table of increasing offsets in a compact form using differential encoding.
2721 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2722 * group size, the more compact the table becomes, but the slower it becomes to compute
2723 * a given entry. Returns the size of the table.
2726 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2728 gint32 current_offset;
2729 int i, buf_size, ngroups, index_entry_size;
2731 guint8 *data_p, *data_buf;
2732 guint32 *index_offsets;
2734 ngroups = (noffsets + (group_size - 1)) / group_size;
2736 index_offsets = g_new0 (guint32, ngroups);
2738 buf_size = noffsets * 4;
2739 p = buf = (guint8 *)g_malloc0 (buf_size);
2742 for (i = 0; i < noffsets; ++i) {
2743 //printf ("D: %d -> %d\n", i, offsets [i]);
2744 if ((i % group_size) == 0) {
2745 index_offsets [i / group_size] = p - buf;
2746 /* Emit the full value for these entries */
2747 encode_value (offsets [i], p, &p);
2749 /* The offsets are allowed to be non-increasing */
2750 //g_assert (offsets [i] >= current_offset);
2751 encode_value (offsets [i] - current_offset, p, &p);
2753 current_offset = offsets [i];
2758 if (ngroups && index_offsets [ngroups - 1] < 65000)
2759 index_entry_size = 2;
2761 index_entry_size = 4;
2763 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2764 p = buf = (guint8 *)g_malloc0 (buf_size);
2766 /* Emit the header */
2767 encode_int (noffsets, p, &p);
2768 encode_int (group_size, p, &p);
2769 encode_int (ngroups, p, &p);
2770 encode_int (index_entry_size, p, &p);
2772 /* Emit the index */
2773 for (i = 0; i < ngroups; ++i) {
2774 if (index_entry_size == 2)
2775 encode_int16 (index_offsets [i], p, &p);
2777 encode_int (index_offsets [i], p, &p);
2780 memcpy (p, data_buf, data_p - data_buf);
2781 p += data_p - data_buf;
2783 g_assert (p - buf <= buf_size);
2785 emit_aot_data (acfg, table, symbol, buf, p - buf);
2790 return (int)(p - buf);
2794 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2798 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2802 index = g_hash_table_size (cfg->image_hash);
2803 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2804 g_ptr_array_add (cfg->image_table, image);
2810 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2813 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2815 /* FIXME: Search referenced images as well */
2816 if (!acfg->typespec_classes) {
2817 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2818 for (i = 0; i < len; i++) {
2820 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2821 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2822 if (!is_ok (&error)) {
2823 mono_error_cleanup (&error);
2826 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2829 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2833 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2836 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2839 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2842 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2845 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2850 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2854 if (mono_class_is_ginst (klass)) {
2856 g_assert (klass->type_token);
2858 /* Find a typespec for a class if possible */
2859 token = find_typespec_for_class (acfg, klass);
2861 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2862 encode_value (token, p, &p);
2864 MonoClass *gclass = mono_class_get_generic_class (klass)->container_class;
2865 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
2866 static int count = 0;
2869 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2870 encode_klass_ref (acfg, gclass, p, &p);
2871 encode_ginst (acfg, inst, p, &p);
2875 } else if (klass->type_token) {
2876 int iindex = get_image_index (acfg, klass->image);
2878 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2880 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2881 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2883 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2884 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2885 encode_value (get_image_index (acfg, klass->image), p, &p);
2887 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2888 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2889 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2891 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2893 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2894 if (par->gshared_constraint) {
2895 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2896 encode_type (acfg, par->gshared_constraint, p, &p);
2897 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2899 encode_value (klass->byval_arg.type, p, &p);
2900 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2902 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2904 if (!container->is_anonymous) {
2905 encode_value (container->is_method, p, &p);
2906 if (container->is_method)
2907 encode_method_ref (acfg, container->owner.method, p, &p);
2909 encode_klass_ref (acfg, container->owner.klass, p, &p);
2912 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2913 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2914 encode_type (acfg, &klass->byval_arg, p, &p);
2917 g_assert (klass->rank > 0);
2918 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2919 encode_value (klass->rank, p, &p);
2920 encode_klass_ref (acfg, klass->element_class, p, &p);
2928 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2929 * standard metadata encoding.
2932 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2934 gboolean shared = FALSE;
2937 * The encoding of generic instances is large so emit them only once.
2939 if (mono_class_is_ginst (klass)) {
2941 g_assert (klass->type_token);
2943 /* Find a typespec for a class if possible */
2944 token = find_typespec_for_class (acfg, klass);
2947 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2952 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2956 buf2 = (guint8 *)g_malloc (1024);
2959 encode_klass_ref_inner (acfg, klass, p, &p);
2960 g_assert (p - buf2 < 1024);
2962 offset = add_to_blob (acfg, buf2, p - buf2);
2965 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2971 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2972 encode_value (offset, p, &p);
2977 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2981 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2983 guint32 token = mono_get_field_token (field);
2986 encode_klass_ref (cfg, field->parent, p, &p);
2987 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2988 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2993 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2998 encode_value (inst->type_argc, p, &p);
2999 for (i = 0; i < inst->type_argc; ++i)
3000 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
3005 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
3008 MonoGenericInst *inst;
3010 inst = context->class_inst;
3012 g_assert (inst->type_argc);
3013 encode_ginst (acfg, inst, p, &p);
3015 encode_value (0, p, &p);
3017 inst = context->method_inst;
3019 g_assert (inst->type_argc);
3020 encode_ginst (acfg, inst, p, &p);
3022 encode_value (0, p, &p);
3028 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
3032 g_assert (t->num_mods == 0);
3033 /* t->attrs can be ignored */
3034 //g_assert (t->attrs == 0);
3037 *p = MONO_TYPE_PINNED;
3041 *p = MONO_TYPE_BYREF;
3049 case MONO_TYPE_VOID:
3050 case MONO_TYPE_BOOLEAN:
3051 case MONO_TYPE_CHAR:
3064 case MONO_TYPE_STRING:
3065 case MONO_TYPE_OBJECT:
3066 case MONO_TYPE_TYPEDBYREF:
3068 case MONO_TYPE_VALUETYPE:
3069 case MONO_TYPE_CLASS:
3070 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3072 case MONO_TYPE_SZARRAY:
3073 encode_klass_ref (acfg, t->data.klass, p, &p);
3076 encode_type (acfg, t->data.type, p, &p);
3078 case MONO_TYPE_GENERICINST: {
3079 MonoClass *gclass = t->data.generic_class->container_class;
3080 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
3082 encode_klass_ref (acfg, gclass, p, &p);
3083 encode_ginst (acfg, inst, p, &p);
3086 case MONO_TYPE_ARRAY: {
3087 MonoArrayType *array = t->data.array;
3090 encode_klass_ref (acfg, array->eklass, p, &p);
3091 encode_value (array->rank, p, &p);
3092 encode_value (array->numsizes, p, &p);
3093 for (i = 0; i < array->numsizes; ++i)
3094 encode_value (array->sizes [i], p, &p);
3095 encode_value (array->numlobounds, p, &p);
3096 for (i = 0; i < array->numlobounds; ++i)
3097 encode_value (array->lobounds [i], p, &p);
3101 case MONO_TYPE_MVAR:
3102 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3105 g_assert_not_reached ();
3112 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3118 /* Similar to the metadata encoding */
3119 if (sig->generic_param_count)
3123 if (sig->explicit_this)
3125 flags |= (sig->call_convention & 0x0F);
3129 if (sig->generic_param_count)
3130 encode_value (sig->generic_param_count, p, &p);
3131 encode_value (sig->param_count, p, &p);
3133 encode_type (acfg, sig->ret, p, &p);
3134 for (i = 0; i < sig->param_count; ++i) {
3135 if (sig->sentinelpos == i) {
3136 *p = MONO_TYPE_SENTINEL;
3139 encode_type (acfg, sig->params [i], p, &p);
3145 #define MAX_IMAGE_INDEX 250
3148 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3150 guint32 image_index = get_image_index (acfg, method->klass->image);
3151 guint32 token = method->token;
3152 MonoJumpInfoToken *ji;
3156 * The encoding for most methods is as follows:
3157 * - image index encoded as a leb128
3158 * - token index encoded as a leb128
3159 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3160 * types of method encodings.
3163 /* Mark methods which can't use aot trampolines because they need the further
3164 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3166 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3167 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3168 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3170 if (method->wrapper_type) {
3171 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3173 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3175 encode_value (method->wrapper_type, p, &p);
3177 switch (method->wrapper_type) {
3178 case MONO_WRAPPER_REMOTING_INVOKE:
3179 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3180 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3183 m = mono_marshal_method_from_wrapper (method);
3185 encode_method_ref (acfg, m, p, &p);
3188 case MONO_WRAPPER_PROXY_ISINST:
3189 case MONO_WRAPPER_LDFLD:
3190 case MONO_WRAPPER_LDFLDA:
3191 case MONO_WRAPPER_STFLD: {
3193 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3196 case MONO_WRAPPER_ALLOC: {
3197 /* The GC name is saved once in MonoAotFileInfo */
3198 g_assert (info->d.alloc.alloc_type != -1);
3199 encode_value (info->d.alloc.alloc_type, p, &p);
3202 case MONO_WRAPPER_WRITE_BARRIER: {
3206 case MONO_WRAPPER_STELEMREF: {
3208 encode_value (info->subtype, p, &p);
3209 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3210 encode_value (info->d.virtual_stelemref.kind, p, &p);
3213 case MONO_WRAPPER_UNKNOWN: {
3215 encode_value (info->subtype, p, &p);
3216 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3217 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3218 encode_klass_ref (acfg, method->klass, p, &p);
3219 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3220 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3221 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3222 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3223 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3224 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3225 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3226 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3229 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3231 encode_value (info->subtype, p, &p);
3232 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3233 strcpy ((char*)p, method->name);
3234 p += strlen (method->name) + 1;
3235 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3236 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3238 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3239 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3243 case MONO_WRAPPER_SYNCHRONIZED: {
3246 m = mono_marshal_method_from_wrapper (method);
3248 g_assert (m != method);
3249 encode_method_ref (acfg, m, p, &p);
3252 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3254 encode_value (info->subtype, p, &p);
3256 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3257 encode_value (info->d.element_addr.rank, p, &p);
3258 encode_value (info->d.element_addr.elem_size, p, &p);
3259 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3260 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3262 g_assert_not_reached ();
3266 case MONO_WRAPPER_CASTCLASS: {
3268 encode_value (info->subtype, p, &p);
3271 case MONO_WRAPPER_RUNTIME_INVOKE: {
3273 encode_value (info->subtype, p, &p);
3274 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3275 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3276 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3277 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3280 case MONO_WRAPPER_DELEGATE_INVOKE:
3281 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3282 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3283 if (method->is_inflated) {
3284 /* These wrappers are identified by their class */
3285 encode_value (1, p, &p);
3286 encode_klass_ref (acfg, method->klass, p, &p);
3288 MonoMethodSignature *sig = mono_method_signature (method);
3289 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3291 encode_value (0, p, &p);
3292 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3293 encode_value (info ? info->subtype : 0, p, &p);
3294 encode_signature (acfg, sig, p, &p);
3298 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3300 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3301 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3305 g_assert_not_reached ();
3307 } else if (mono_method_signature (method)->is_inflated) {
3309 * This is a generic method, find the original token which referenced it and
3311 * Obtain the token from information recorded by the JIT.
3313 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3315 image_index = get_image_index (acfg, ji->image);
3316 g_assert (image_index < MAX_IMAGE_INDEX);
3319 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3320 encode_value (image_index, p, &p);
3321 encode_value (token, p, &p);
3323 MonoMethod *declaring;
3324 MonoGenericContext *context = mono_method_get_context (method);
3326 g_assert (method->is_inflated);
3327 declaring = ((MonoMethodInflated*)method)->declaring;
3330 * This might be a non-generic method of a generic instance, which
3331 * doesn't have a token since the reference is generated by the JIT
3332 * like Nullable:Box/Unbox, or by generic sharing.
3334 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3335 /* Encode the klass */
3336 encode_klass_ref (acfg, method->klass, p, &p);
3337 /* Encode the method */
3338 image_index = get_image_index (acfg, method->klass->image);
3339 g_assert (image_index < MAX_IMAGE_INDEX);
3340 g_assert (declaring->token);
3341 token = declaring->token;
3342 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3343 encode_value (image_index, p, &p);
3344 encode_value (token, p, &p);
3345 encode_generic_context (acfg, context, p, &p);
3347 } else if (token == 0) {
3348 /* This might be a method of a constructed type like int[,].Set */
3349 /* Obtain the token from information recorded by the JIT */
3350 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3352 image_index = get_image_index (acfg, ji->image);
3353 g_assert (image_index < MAX_IMAGE_INDEX);
3356 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3357 encode_value (image_index, p, &p);
3358 encode_value (token, p, &p);
3361 g_assert (method->klass->rank);
3363 /* Encode directly */
3364 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3365 encode_klass_ref (acfg, method->klass, p, &p);
3366 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3367 encode_value (0, p, &p);
3368 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3369 encode_value (1, p, &p);
3370 else if (!strcmp (method->name, "Get"))
3371 encode_value (2, p, &p);
3372 else if (!strcmp (method->name, "Address"))
3373 encode_value (3, p, &p);
3374 else if (!strcmp (method->name, "Set"))
3375 encode_value (4, p, &p);
3377 g_assert_not_reached ();
3380 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3382 if (image_index >= MONO_AOT_METHODREF_MIN) {
3383 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3384 encode_value (image_index, p, &p);
3385 encode_value (mono_metadata_token_index (token), p, &p);
3387 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3394 compare_patches (gconstpointer a, gconstpointer b)
3398 i = (*(MonoJumpInfo**)a)->ip.i;
3399 j = (*(MonoJumpInfo**)b)->ip.i;
3410 static G_GNUC_UNUSED char*
3411 patch_to_string (MonoJumpInfo *patch_info)
3415 str = g_string_new ("");
3417 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3419 switch (patch_info->type) {
3420 case MONO_PATCH_INFO_VTABLE:
3421 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3426 g_string_append_printf (str, ")");
3427 return g_string_free (str, FALSE);
3433 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3436 static inline gboolean
3437 is_plt_patch (MonoJumpInfo *patch_info)
3439 switch (patch_info->type) {
3440 case MONO_PATCH_INFO_METHOD:
3441 case MONO_PATCH_INFO_INTERNAL_METHOD:
3442 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3443 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3444 case MONO_PATCH_INFO_RGCTX_FETCH:
3454 * Return the symbol identifying the plt entry PLT_OFFSET.
3457 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3461 * The Apple linker reorganizes object files, so it doesn't like branches to local
3462 * labels, since those have no relocations.
3464 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3466 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3473 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3475 static MonoPltEntry*
3476 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3479 gboolean synchronized = FALSE;
3480 static int synchronized_symbol_idx;
3482 if (!is_plt_patch (patch_info))
3485 if (!acfg->patch_to_plt_entry [patch_info->type])
3486 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3487 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3489 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3491 * Allocate a separate PLT slot for each such patch, since some plt
3492 * entries will refer to the method itself, and some will refer to the
3496 synchronized = TRUE;
3500 MonoJumpInfo *new_ji;
3502 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3504 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3505 res->plt_offset = acfg->plt_offset;
3507 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3508 if (acfg->aot_opts.write_symbols)
3509 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3511 /* Avoid duplicate symbols because we don't cache */
3512 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3514 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3515 synchronized_symbol_idx ++;
3518 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3520 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3522 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3524 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3526 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3527 //mono_print_ji (patch_info); printf ("\n");
3528 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3530 acfg->plt_offset ++;
3539 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3540 * JI could be found if it exists, otherwise allocates a new one.
3543 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3546 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3548 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3550 return got_offset - 1;
3553 got_offset = acfg->llvm_got_offset;
3554 acfg->llvm_got_offset ++;
3556 got_offset = acfg->got_offset;
3557 acfg->got_offset ++;
3560 acfg->stats.got_slots ++;
3561 acfg->stats.got_slot_types [ji->type] ++;
3563 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3564 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3565 g_ptr_array_add (info->got_patches, ji);
3570 /* Add a method to the list of methods which need to be emitted */
3572 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3575 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3576 g_ptr_array_add (acfg->methods, method);
3577 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3578 acfg->nmethods = acfg->methods->len + 1;
3581 if (method->wrapper_type || extra)
3582 g_ptr_array_add (acfg->extra_methods, method);
3586 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3588 /* One instantiation with valuetypes is generated for each async method */
3589 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3596 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3598 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3606 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3610 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3614 index = acfg->method_index;
3615 add_method_with_index (acfg, method, index, extra);
3617 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3619 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3621 acfg->method_index ++;
3627 add_method (MonoAotCompile *acfg, MonoMethod *method)
3629 return add_method_full (acfg, method, FALSE, 0);
3633 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3635 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3636 method = mini_get_shared_method (method);
3637 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3638 /* Use the gsharedvt version */
3639 method = mini_get_shared_method_full (method, TRUE, TRUE);
3641 if (acfg->aot_opts.log_generics)
3642 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3644 add_method_full (acfg, method, TRUE, depth);
3648 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3650 add_extra_method_with_depth (acfg, method, 0);
3654 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3656 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3657 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3658 MonoMethod *wrapper;
3664 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3665 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3668 add_method (acfg, wrapper);
3672 get_runtime_invoke_sig (MonoMethodSignature *sig)
3674 MonoMethodBuilder *mb;
3677 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3678 m = mono_mb_create_method (mb, sig, 16);
3679 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3685 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3687 return mono_marshal_get_runtime_invoke (method, virtual_);
3691 can_marshal_struct (MonoClass *klass)
3693 MonoClassField *field;
3694 gboolean can_marshal = TRUE;
3695 gpointer iter = NULL;
3696 MonoMarshalType *info;
3699 if (mono_class_is_auto_layout (klass))
3702 info = mono_marshal_load_type_info (klass);
3704 /* Only allow a few field types to avoid asserts in the marshalling code */
3705 while ((field = mono_class_get_fields (klass, &iter))) {
3706 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3709 switch (field->type->type) {
3714 case MONO_TYPE_BOOLEAN:
3717 case MONO_TYPE_CHAR:
3725 case MONO_TYPE_STRING:
3727 case MONO_TYPE_VALUETYPE:
3728 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3729 can_marshal = FALSE;
3731 case MONO_TYPE_SZARRAY: {
3732 gboolean has_mspec = FALSE;
3735 for (i = 0; i < info->num_fields; ++i) {
3736 if (info->fields [i].field == field && info->fields [i].mspec)
3741 can_marshal = FALSE;
3745 can_marshal = FALSE;
3751 /* Its hard to compute whenever these can be marshalled or not */
3752 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3759 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3761 /* Create a vtype instantiation */
3762 MonoGenericContext shared_context;
3764 MonoGenericInst *inst;
3765 MonoGenericContainer *container;
3766 MonoClass **constraints;
3769 memset (ctx, 0, sizeof (MonoGenericContext));
3771 if (mono_class_is_gtd (method->klass)) {
3772 shared_context = mono_class_get_generic_container (method->klass)->context;
3773 inst = shared_context.class_inst;
3775 args = g_new0 (MonoType*, inst->type_argc);
3776 for (i = 0; i < inst->type_argc; ++i) {
3777 args [i] = &mono_defaults.int_class->byval_arg;
3779 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3781 if (method->is_generic) {
3782 container = mono_method_get_generic_container (method);
3783 shared_context = container->context;
3784 inst = shared_context.method_inst;
3786 args = g_new0 (MonoType*, inst->type_argc);
3787 for (i = 0; i < container->type_argc; ++i) {
3788 MonoGenericParamInfo *info = &container->type_params [i].info;
3789 gboolean ref_only = FALSE;
3791 if (info && info->constraints) {
3792 constraints = info->constraints;
3794 while (*constraints) {
3795 MonoClass *cklass = *constraints;
3796 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3797 /* Inflaring the method with our vtype would not be valid */
3804 args [i] = &mono_defaults.object_class->byval_arg;
3806 args [i] = &mono_defaults.int_class->byval_arg;
3808 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3813 add_wrappers (MonoAotCompile *acfg)
3815 MonoMethod *method, *m;
3817 MonoMethodSignature *sig, *csig;
3821 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3822 * so there is only one wrapper of a given type, or inlining their contents into their
3825 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3828 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3829 gboolean skip = FALSE;
3831 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3832 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3834 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3835 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3836 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3839 /* Skip methods which can not be handled by get_runtime_invoke () */
3840 sig = mono_method_signature (method);
3843 if ((sig->ret->type == MONO_TYPE_PTR) ||
3844 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3846 if (mono_class_is_open_constructed_type (sig->ret))
3849 for (j = 0; j < sig->param_count; j++) {
3850 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3852 if (mono_class_is_open_constructed_type (sig->params [j]))
3856 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3857 if (!mono_class_is_contextbound (method->klass)) {
3858 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3859 gboolean has_nullable = FALSE;
3861 for (j = 0; j < sig->param_count; j++) {
3862 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3863 has_nullable = TRUE;
3866 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3867 /* Supported by the dynamic runtime-invoke wrapper */
3871 mono_arch_dyn_call_free (info);
3875 if (acfg->aot_opts.llvm_only)
3876 /* Supported by the gsharedvt based runtime-invoke wrapper */
3880 //printf ("%s\n", mono_method_full_name (method, TRUE));
3881 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3885 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3888 /* Runtime invoke wrappers */
3890 /* void runtime-invoke () [.cctor] */
3891 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3892 csig->ret = &mono_defaults.void_class->byval_arg;
3893 add_method (acfg, get_runtime_invoke_sig (csig));
3895 /* void runtime-invoke () [Finalize] */
3896 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3898 csig->ret = &mono_defaults.void_class->byval_arg;
3899 add_method (acfg, get_runtime_invoke_sig (csig));
3901 /* void runtime-invoke (string) [exception ctor] */
3902 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3904 csig->ret = &mono_defaults.void_class->byval_arg;
3905 csig->params [0] = &mono_defaults.string_class->byval_arg;
3906 add_method (acfg, get_runtime_invoke_sig (csig));
3908 /* void runtime-invoke (string, string) [exception ctor] */
3909 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3911 csig->ret = &mono_defaults.void_class->byval_arg;
3912 csig->params [0] = &mono_defaults.string_class->byval_arg;
3913 csig->params [1] = &mono_defaults.string_class->byval_arg;
3914 add_method (acfg, get_runtime_invoke_sig (csig));
3916 /* string runtime-invoke () [Exception.ToString ()] */
3917 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3919 csig->ret = &mono_defaults.string_class->byval_arg;
3920 add_method (acfg, get_runtime_invoke_sig (csig));
3922 /* void runtime-invoke (string, Exception) [exception ctor] */
3923 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3925 csig->ret = &mono_defaults.void_class->byval_arg;
3926 csig->params [0] = &mono_defaults.string_class->byval_arg;
3927 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3928 add_method (acfg, get_runtime_invoke_sig (csig));
3930 /* Assembly runtime-invoke (string, Assembly, bool) [DoAssemblyResolve] */
3931 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
3933 csig->ret = &(mono_class_load_from_name (
3934 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3935 csig->params [0] = &mono_defaults.string_class->byval_arg;
3936 csig->params [1] = &(mono_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3937 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3938 add_method (acfg, get_runtime_invoke_sig (csig));
3940 /* runtime-invoke used by finalizers */
3941 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3943 /* This is used by mono_runtime_capture_context () */
3944 method = mono_get_context_capture_method ();
3946 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3948 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3949 if (!acfg->aot_opts.llvm_only)
3950 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3953 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3954 if (acfg->aot_opts.llvm_only) {
3957 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3958 for (variants = 0; variants < 4; ++variants) {
3959 for (i = 0; i < 16; ++i) {
3960 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3961 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3969 add_method (acfg, mono_marshal_get_stelemref ());
3971 /* Managed Allocators */
3972 nallocators = mono_gc_get_managed_allocator_types ();
3973 for (i = 0; i < nallocators; ++i) {
3974 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3975 add_method (acfg, m);
3976 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3977 add_method (acfg, m);
3980 /* write barriers */
3981 if (mono_gc_is_moving ()) {
3982 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3983 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3986 /* Stelemref wrappers */
3988 MonoMethod **wrappers;
3991 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3992 for (i = 0; i < nwrappers; ++i)
3993 add_method (acfg, wrappers [i]);
3997 /* castclass_with_check wrapper */
3998 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3999 /* isinst_with_check wrapper */
4000 add_method (acfg, mono_marshal_get_isinst_with_cache ());
4002 /* JIT icall wrappers */
4003 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
4004 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
4008 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
4009 * we use the original method instead at runtime.
4010 * Since full-aot doesn't support remoting, this is not a problem.
4013 /* remoting-invoke wrappers */
4014 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4016 MonoMethodSignature *sig;
4018 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4019 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4020 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4022 sig = mono_method_signature (method);
4024 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
4025 m = mono_marshal_get_remoting_invoke_with_check (method);
4027 add_method (acfg, m);
4032 /* delegate-invoke wrappers */
4033 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4036 MonoCustomAttrInfo *cattr;
4038 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4039 klass = mono_class_get_checked (acfg->image, token, &error);
4042 mono_error_cleanup (&error);
4046 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
4049 if (!mono_class_is_gtd (klass)) {
4050 method = mono_get_delegate_invoke (klass);
4052 m = mono_marshal_get_delegate_invoke (method, NULL);
4054 add_method (acfg, m);
4056 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
4058 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
4060 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
4062 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
4064 cattr = mono_custom_attrs_from_class_checked (klass, &error);
4065 if (!is_ok (&error)) {
4066 mono_error_cleanup (&error);
4073 for (j = 0; j < cattr->num_attrs; ++j)
4074 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
4076 if (j < cattr->num_attrs) {
4078 MonoMethod *wrapper;
4079 MonoMethod *del_invoke;
4081 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4082 invoke = mono_get_delegate_invoke (klass);
4083 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4084 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4085 add_method (acfg, wrapper);
4086 add_method (acfg, del_invoke);
4089 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (klass)) {
4091 MonoGenericContext ctx;
4092 MonoMethod *inst, *gshared;
4095 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4098 method = mono_get_delegate_invoke (klass);
4099 create_gsharedvt_inst (acfg, method, &ctx);
4101 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4102 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4104 m = mono_marshal_get_delegate_invoke (inst, NULL);
4105 g_assert (m->is_inflated);
4107 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4108 add_extra_method (acfg, gshared);
4111 method = mono_get_delegate_begin_invoke (klass);
4113 create_gsharedvt_inst (acfg, method, &ctx);
4115 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4116 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4118 m = mono_marshal_get_delegate_begin_invoke (inst);
4119 g_assert (m->is_inflated);
4121 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4122 add_extra_method (acfg, gshared);
4126 method = mono_get_delegate_end_invoke (klass);
4128 create_gsharedvt_inst (acfg, method, &ctx);
4130 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4131 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4133 m = mono_marshal_get_delegate_end_invoke (inst);
4134 g_assert (m->is_inflated);
4136 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4137 add_extra_method (acfg, gshared);
4142 /* array access wrappers */
4143 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4147 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4148 klass = mono_class_get_checked (acfg->image, token, &error);
4151 mono_error_cleanup (&error);
4155 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4156 MonoMethod *m, *wrapper;
4158 /* Add runtime-invoke wrappers too */
4160 m = mono_class_get_method_from_name (klass, "Get", -1);
4162 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4163 add_extra_method (acfg, wrapper);
4164 if (!acfg->aot_opts.llvm_only)
4165 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4167 m = mono_class_get_method_from_name (klass, "Set", -1);
4169 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4170 add_extra_method (acfg, wrapper);
4171 if (!acfg->aot_opts.llvm_only)
4172 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4176 /* Synchronized wrappers */
4177 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4179 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4180 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4181 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4183 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4184 if (method->is_generic) {
4186 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && mono_class_is_gtd (method->klass)) {
4188 MonoGenericContext ctx;
4189 MonoMethod *inst, *gshared, *m;
4192 * Create a generic wrapper for a generic instance, and AOT that.
4194 create_gsharedvt_inst (acfg, method, &ctx);
4195 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4196 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4197 m = mono_marshal_get_synchronized_wrapper (inst);
4198 g_assert (m->is_inflated);
4199 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4200 add_method (acfg, gshared);
4202 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4207 /* pinvoke wrappers */
4208 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4211 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4213 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4214 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4216 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4217 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4218 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4221 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4222 if (acfg->aot_opts.llvm_only) {
4223 /* The wrappers have a different signature (hasthis is not set) so need to add this too */
4224 add_gsharedvt_wrappers (acfg, mono_method_signature (method), FALSE, TRUE);
4229 /* native-to-managed wrappers */
4230 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4233 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4234 MonoCustomAttrInfo *cattr;
4237 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4238 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4241 * Only generate native-to-managed wrappers for methods which have an
4242 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4243 * name to avoid defining a new assembly to contain it.
4245 cattr = mono_custom_attrs_from_method_checked (method, &error);
4246 if (!is_ok (&error)) {
4247 char *name = mono_method_get_full_name (method);
4248 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4253 for (j = 0; j < cattr->num_attrs; ++j)
4254 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4256 if (j < cattr->num_attrs) {
4257 MonoCustomAttrEntry *e = &cattr->attrs [j];
4258 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4259 const char *p = (const char*)e->data;
4261 int slen, num_named, named_type;
4265 char *export_name = NULL;
4266 MonoMethod *wrapper;
4268 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4269 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4270 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4271 mono_method_full_name (method, TRUE));
4275 g_assert (sig->param_count == 1);
4276 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4279 * Decode the cattr manually since we can't create objects
4280 * during aot compilation.
4286 /* From load_cattr_value () in reflection.c */
4287 slen = mono_metadata_decode_value (p, &p);
4288 n = (char *)g_memdup (p, slen + 1);
4290 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4292 mono_error_assert_ok (&error);
4295 klass = mono_class_from_mono_type (t);
4296 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4300 num_named = read16 (p);
4303 g_assert (num_named < 2);
4304 if (num_named == 1) {
4308 /* parse ExportSymbol attribute */
4310 named_type = *named;
4312 /* data_type = *named; */
4315 name_len = mono_metadata_decode_blob_size (named, &named);
4316 name = (char *)g_malloc (name_len + 1);
4317 memcpy (name, named, name_len);
4318 name [name_len] = 0;
4321 g_assert (named_type == 0x54);
4322 g_assert (!strcmp (name, "ExportSymbol"));
4324 /* load_cattr_value (), string case */
4325 g_assert (*named != (char)0xff);
4326 slen = mono_metadata_decode_value (named, &named);
4327 export_name = (char *)g_malloc (slen + 1);
4328 memcpy (export_name, named, slen);
4329 export_name [slen] = 0;
4333 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0, &error);
4334 mono_error_assert_ok (&error);
4336 add_method (acfg, wrapper);
4338 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4343 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4344 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4345 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4349 /* StructureToPtr/PtrToStructure wrappers */
4350 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4354 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4355 klass = mono_class_get_checked (acfg->image, token, &error);
4358 mono_error_cleanup (&error);
4362 if (klass->valuetype && !mono_class_is_gtd (klass) && can_marshal_struct (klass) &&
4363 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4364 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4365 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4371 has_type_vars (MonoClass *klass)
4373 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4376 return has_type_vars (klass->element_class);
4377 if (mono_class_is_ginst (klass)) {
4378 MonoGenericContext *context = &mono_class_get_generic_class (klass)->context;
4379 if (context->class_inst) {
4382 for (i = 0; i < context->class_inst->type_argc; ++i)
4383 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4387 if (mono_class_is_gtd (klass))
4393 is_vt_inst (MonoGenericInst *inst)
4397 for (i = 0; i < inst->type_argc; ++i) {
4398 MonoType *t = inst->type_argv [i];
4399 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4406 method_has_type_vars (MonoMethod *method)
4408 if (has_type_vars (method->klass))
4411 if (method->is_inflated) {
4412 MonoGenericContext *context = mono_method_get_context (method);
4413 if (context->method_inst) {
4416 for (i = 0; i < context->method_inst->type_argc; ++i)
4417 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4425 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4427 return opts->mode == MONO_AOT_MODE_FULL;
4431 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4433 return opts->mode == MONO_AOT_MODE_HYBRID;
4436 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4439 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4441 /* This might lead to a huge code blowup so only do it if neccesary */
4442 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4445 add_generic_class_with_depth (acfg, klass, 0, ref);
4449 check_type_depth (MonoType *t, int depth)
4457 case MONO_TYPE_GENERICINST: {
4458 MonoGenericClass *gklass = t->data.generic_class;
4459 MonoGenericInst *ginst = gklass->context.class_inst;
4462 for (i = 0; i < ginst->type_argc; ++i) {
4463 if (check_type_depth (ginst->type_argv [i], depth + 1))
4477 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4480 * add_generic_class:
4482 * Add all methods of a generic class.
4485 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4488 MonoClassField *field;
4490 gboolean use_gsharedvt = FALSE;
4492 if (!acfg->ginst_hash)
4493 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4495 mono_class_init (klass);
4497 if (mono_class_is_ginst (klass) && mono_class_get_generic_class (klass)->context.class_inst->is_open)
4500 if (has_type_vars (klass))
4503 if (!mono_class_is_ginst (klass) && !klass->rank)
4506 if (mono_class_has_failure (klass))
4509 if (!acfg->ginst_hash)
4510 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4512 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4515 if (check_type_depth (&klass->byval_arg, 0))
4518 if (acfg->aot_opts.log_generics)
4519 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4521 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4524 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4525 * Enable this only for some classes since gsharedvt might not support all methods.
4527 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) &&
4528 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4529 use_gsharedvt = TRUE;
4532 while ((method = mono_class_get_methods (klass, &iter))) {
4533 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4535 * This is partial sharing, and we can't handle it yet
4540 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4542 add_types_from_method_header (acfg, method);
4546 if (method->is_generic)
4551 * FIXME: Instances which are referenced by these methods are not added,
4552 * for example Array.Resize<int> for List<int>.Add ().
4554 add_extra_method_with_depth (acfg, method, depth + 1);
4558 while ((field = mono_class_get_fields (klass, &iter))) {
4559 if (field->type->type == MONO_TYPE_GENERICINST)
4560 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4563 if (klass->delegate) {
4564 method = mono_get_delegate_invoke (klass);
4566 method = mono_marshal_get_delegate_invoke (method, NULL);
4568 if (acfg->aot_opts.log_generics)
4569 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4571 add_method (acfg, method);
4574 /* Add superclasses */
4576 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4579 * For ICollection<T>, add instances of the helper methods
4580 * in Array, since a T[] could be cast to ICollection<T>.
4582 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4583 (!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"))) {
4584 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4585 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4589 if (!strcmp (klass->name, "IEnumerator`1"))
4590 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4592 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4594 /* Add the T[]/InternalEnumerator class */
4595 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4600 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4601 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4605 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (mono_class_get_generic_class (klass)), &error);
4606 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4607 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4611 while ((method = mono_class_get_methods (array_class, &iter))) {
4612 if (strstr (method->name, name_prefix)) {
4613 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4615 add_extra_method_with_depth (acfg, m, depth);
4619 g_free (name_prefix);
4622 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4623 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4625 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4626 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4627 MonoGenericContext ctx;
4628 MonoType *args [16];
4630 memset (&ctx, 0, sizeof (ctx));
4632 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4634 args [0] = &tclass->byval_arg;
4635 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4637 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4638 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4640 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4641 MonoClass *gcomparer_inst;
4642 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4643 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4644 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4646 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4650 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4651 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4653 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4654 MonoClass *iface, *gcomparer, *iface_inst;
4655 MonoGenericContext ctx;
4656 MonoType *args [16];
4658 memset (&ctx, 0, sizeof (ctx));
4660 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4662 args [0] = &tclass->byval_arg;
4663 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4665 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4666 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4668 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4669 MonoClass *gcomparer_inst;
4672 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4673 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4674 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4675 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4679 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4680 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4681 MonoClass *enum_comparer;
4682 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4683 MonoGenericContext ctx;
4684 MonoType *args [16];
4686 if (mono_class_is_enum (tclass)) {
4687 MonoClass *enum_comparer_inst;
4690 memset (&ctx, 0, sizeof (ctx));
4691 args [0] = &tclass->byval_arg;
4692 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4694 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4695 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4696 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4697 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4701 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4702 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4703 MonoClass *comparer;
4704 MonoClass *tclass = mono_class_from_mono_type (mono_class_get_generic_class (klass)->context.class_inst->type_argv [0]);
4705 MonoGenericContext ctx;
4706 MonoType *args [16];
4708 if (mono_class_is_enum (tclass)) {
4709 MonoClass *comparer_inst;
4712 memset (&ctx, 0, sizeof (ctx));
4713 args [0] = &tclass->byval_arg;
4714 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4716 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4717 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4718 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4719 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4725 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4728 MonoGenericContext ctx;
4729 MonoType *args [16];
4731 if (acfg->aot_opts.no_instances)
4734 memset (&ctx, 0, sizeof (ctx));
4736 for (i = 0; i < ninsts; ++i) {
4738 MonoClass *generic_inst;
4739 args [0] = insts [i];
4740 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4741 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4742 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4743 add_generic_class (acfg, generic_inst, force, "");
4748 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4751 MonoMethodHeader *header;
4752 MonoMethodSignature *sig;
4755 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4757 sig = mono_method_signature (method);
4760 for (j = 0; j < sig->param_count; ++j)
4761 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4762 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4765 header = mono_method_get_header_checked (method, &error);
4768 for (j = 0; j < header->num_locals; ++j)
4769 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4770 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4771 mono_metadata_free_mh (header);
4773 mono_error_cleanup (&error); /* FIXME report the error */
4779 * add_generic_instances:
4781 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4784 add_generic_instances (MonoAotCompile *acfg)
4789 MonoGenericContext *context;
4791 if (acfg->aot_opts.no_instances)
4794 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4796 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4797 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4800 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4801 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4802 mono_error_cleanup (&error);
4806 if (method->klass->image != acfg->image)
4809 context = mono_method_get_context (method);
4811 if (context && ((context->class_inst && context->class_inst->is_open)))
4815 * For open methods, create an instantiation which can be passed to the JIT.
4816 * FIXME: Handle class_inst as well.
4818 if (context && context->method_inst && context->method_inst->is_open) {
4820 MonoGenericContext shared_context;
4821 MonoGenericInst *inst;
4822 MonoType **type_argv;
4824 MonoMethod *declaring_method;
4825 gboolean supported = TRUE;
4827 /* Check that the context doesn't contain open constructed types */
4828 if (context->class_inst) {
4829 inst = context->class_inst;
4830 for (i = 0; i < inst->type_argc; ++i) {
4831 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)
4833 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4837 if (context->method_inst) {
4838 inst = context->method_inst;
4839 for (i = 0; i < inst->type_argc; ++i) {
4840 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)
4842 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4850 memset (&shared_context, 0, sizeof (MonoGenericContext));
4852 inst = context->class_inst;
4854 type_argv = g_new0 (MonoType*, inst->type_argc);
4855 for (i = 0; i < inst->type_argc; ++i) {
4856 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)
4857 type_argv [i] = &mono_defaults.object_class->byval_arg;
4859 type_argv [i] = inst->type_argv [i];
4862 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4866 inst = context->method_inst;
4868 type_argv = g_new0 (MonoType*, inst->type_argc);
4869 for (i = 0; i < inst->type_argc; ++i) {
4870 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)
4871 type_argv [i] = &mono_defaults.object_class->byval_arg;
4873 type_argv [i] = inst->type_argv [i];
4876 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4880 if (method->is_generic || mono_class_is_gtd (method->klass))
4881 declaring_method = method;
4883 declaring_method = mono_method_get_declaring_generic_method (method);
4885 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4886 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4890 * If the method is fully sharable, it was already added in place of its
4891 * generic definition.
4893 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4897 * FIXME: Partially shared methods are not shared here, so we end up with
4898 * many identical methods.
4900 add_extra_method (acfg, method);
4903 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4907 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4909 klass = mono_class_get_checked (acfg->image, token, &error);
4910 if (!klass || klass->rank) {
4911 mono_error_cleanup (&error);
4915 add_generic_class (acfg, klass, FALSE, "typespec");
4918 /* Add types of args/locals */
4919 for (i = 0; i < acfg->methods->len; ++i) {
4920 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4921 add_types_from_method_header (acfg, method);
4924 if (acfg->image == mono_defaults.corlib) {
4926 MonoType *insts [256];
4929 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4930 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4931 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4932 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4933 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4934 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4935 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4936 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4937 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4938 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4939 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4940 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4942 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4943 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4945 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4946 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4948 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4950 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4952 MonoClass *enum_comparer;
4953 MonoType *insts [16];
4957 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4958 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4959 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4960 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4961 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4962 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4965 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4966 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4967 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4970 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4971 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4972 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4974 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4976 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4977 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4978 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4981 /* Add instances of the array generic interfaces for primitive types */
4982 /* This will add instances of the InternalArray_ helper methods in Array too */
4983 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4985 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4987 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4989 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4991 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4993 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4996 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4997 * used for all instances of GetGenericValueImpl by the AOT runtime.
5000 MonoGenericContext ctx;
5001 MonoType *args [16];
5002 MonoMethod *get_method;
5003 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
5005 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
5009 memset (&ctx, 0, sizeof (ctx));
5010 args [0] = &mono_defaults.object_class->byval_arg;
5011 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5012 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
5013 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5017 /* Same for CompareExchange<T>/Exchange<T> */
5019 MonoGenericContext ctx;
5020 MonoType *args [16];
5022 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
5023 gpointer iter = NULL;
5025 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
5026 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
5028 memset (&ctx, 0, sizeof (ctx));
5029 args [0] = &mono_defaults.object_class->byval_arg;
5030 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5031 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5032 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5037 /* Same for Volatile.Read/Write<T> */
5039 MonoGenericContext ctx;
5040 MonoType *args [16];
5042 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
5043 gpointer iter = NULL;
5045 if (volatile_klass) {
5046 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
5047 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
5049 memset (&ctx, 0, sizeof (ctx));
5050 args [0] = &mono_defaults.object_class->byval_arg;
5051 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5052 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
5053 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
5059 /* object[] accessor wrappers. */
5060 for (i = 1; i < 4; ++i) {
5061 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
5064 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
5067 m = mono_marshal_get_array_accessor_wrapper (m);
5068 add_extra_method (acfg, m);
5070 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
5073 m = mono_marshal_get_array_accessor_wrapper (m);
5074 add_extra_method (acfg, m);
5076 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
5079 m = mono_marshal_get_array_accessor_wrapper (m);
5080 add_extra_method (acfg, m);
5086 * is_direct_callable:
5088 * Return whenever the method identified by JI is directly callable without
5089 * going through the PLT.
5092 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5094 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5095 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5097 gboolean direct_callable = TRUE;
5099 if (direct_callable && !(!callee_cfg->has_got_slots && mono_class_is_before_field_init (callee_cfg->method->klass)))
5100 direct_callable = FALSE;
5101 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5102 // FIXME: Maybe call the wrapper directly ?
5103 direct_callable = FALSE;
5105 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5106 /* Disable this so all calls go through load_method (), see the
5107 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5108 * mono_debugger_agent_init ().
5110 direct_callable = FALSE;
5113 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5114 /* sgen does some initialization when the allocator method is created */
5115 direct_callable = FALSE;
5116 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5117 /* we don't know at compile time whether sgen is concurrent or not */
5118 direct_callable = FALSE;
5120 if (direct_callable)
5123 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5124 if (acfg->aot_opts.direct_pinvoke)
5126 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5127 if (acfg->aot_opts.direct_icalls)
5135 #ifdef MONO_ARCH_AOT_SUPPORTED
5137 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5139 MonoImage *image = method->klass->image;
5140 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5141 MonoTableInfo *tables = image->tables;
5142 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5143 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5144 guint32 im_cols [MONO_IMPLMAP_SIZE];
5147 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5151 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5154 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5156 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5159 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5161 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5167 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5174 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5176 if (a->native_offset == b->native_offset)
5177 return a->il_offset - b->il_offset;
5179 return a->native_offset - b->native_offset;
5183 * compute_line_numbers:
5185 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5188 static MonoDebugSourceLocation**
5189 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5191 MonoDebugMethodInfo *minfo;
5192 MonoDebugLineNumberEntry *ln_array;
5193 MonoDebugSourceLocation *loc;
5194 int i, prev_line, prev_il_offset;
5195 int *native_to_il_offset = NULL;
5196 MonoDebugSourceLocation **res;
5199 minfo = mono_debug_lookup_method (method);
5202 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5203 if (debug_info->code_size != code_size)
5206 g_assert (code_size);
5208 /* Compute the native->IL offset mapping */
5210 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5211 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5213 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5215 native_to_il_offset = g_new0 (int, code_size + 1);
5217 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5219 MonoDebugLineNumberEntry *lne = &ln_array [i];
5222 for (j = 0; j < lne->native_offset; ++j)
5223 native_to_il_offset [j] = -1;
5226 if (i < debug_info->num_line_numbers - 1) {
5227 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5229 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5230 native_to_il_offset [j] = lne->il_offset;
5232 for (j = lne->native_offset; j < code_size; ++j)
5233 native_to_il_offset [j] = lne->il_offset;
5238 /* Compute the native->line number mapping */
5239 res = g_new0 (MonoDebugSourceLocation*, code_size);
5240 prev_il_offset = -1;
5243 for (i = 0; i < code_size; ++i) {
5244 int il_offset = native_to_il_offset [i];
5246 if (il_offset == -1 || il_offset == prev_il_offset)
5248 prev_il_offset = il_offset;
5249 loc = mono_debug_method_lookup_location (minfo, il_offset);
5250 if (!(loc && loc->source_file))
5252 if (loc->row == prev_line) {
5253 mono_debug_free_source_location (loc);
5256 prev_line = loc->row;
5257 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5259 /* This will cover the prolog too */
5269 get_file_index (MonoAotCompile *acfg, const char *source_file)
5273 // FIXME: Free these
5274 if (!acfg->dwarf_ln_filenames)
5275 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5276 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5278 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5279 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5280 emit_unset_mode (acfg);
5281 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5293 * emit_and_reloc_code:
5295 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5296 * is true, calls are made through the GOT too. This is used for emitting trampolines
5297 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5298 * since trampolines are needed to make PTL work.
5301 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5303 int i, pindex, start_index;
5305 MonoJumpInfo *patch_info;
5306 MonoDebugSourceLocation **locs = NULL;
5307 gboolean skip, prologue_end = FALSE;
5308 #ifdef MONO_ARCH_AOT_SUPPORTED
5309 gboolean direct_call, external_call;
5311 const char *direct_call_target = 0;
5312 const char *direct_pinvoke;
5315 if (acfg->gas_line_numbers && method && debug_info) {
5316 locs = compute_line_numbers (method, code_len, debug_info);
5318 int findex = get_file_index (acfg, "<unknown>");
5319 emit_unset_mode (acfg);
5320 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5324 /* Collect and sort relocations */
5325 patches = g_ptr_array_new ();
5326 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5327 g_ptr_array_add (patches, patch_info);
5328 g_ptr_array_sort (patches, compare_patches);
5331 for (i = 0; i < code_len; i += INST_LEN) {
5333 for (pindex = start_index; pindex < patches->len; ++pindex) {
5334 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5335 if (patch_info->ip.i >= i)
5339 if (locs && locs [i]) {
5340 MonoDebugSourceLocation *loc = locs [i];
5342 const char *options;
5344 findex = get_file_index (acfg, loc->source_file);
5345 emit_unset_mode (acfg);
5347 options = " prologue_end";
5350 prologue_end = TRUE;
5351 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5352 mono_debug_free_source_location (loc);
5356 #ifdef MONO_ARCH_AOT_SUPPORTED
5357 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5358 start_index = pindex;
5360 switch (patch_info->type) {
5361 case MONO_PATCH_INFO_NONE:
5363 case MONO_PATCH_INFO_GOT_OFFSET: {
5366 arch_emit_got_offset (acfg, code + i, &code_size);
5367 i += code_size - INST_LEN;
5369 patch_info->type = MONO_PATCH_INFO_NONE;
5372 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5373 int code_size, index;
5374 char *selector = (char *)patch_info->data.target;
5376 if (!acfg->objc_selector_to_index)
5377 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5378 if (!acfg->objc_selectors)
5379 acfg->objc_selectors = g_ptr_array_new ();
5380 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5384 index = acfg->objc_selector_index;
5385 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5386 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5387 acfg->objc_selector_index ++;
5390 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5391 i += code_size - INST_LEN;
5393 patch_info->type = MONO_PATCH_INFO_NONE;
5398 * If this patch is a call, try emitting a direct call instead of
5399 * through a PLT entry. This is possible if the called method is in
5400 * the same assembly and requires no initialization.
5402 direct_call = FALSE;
5403 external_call = FALSE;
5404 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5405 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5406 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5407 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5409 direct_call_target = callee_cfg->asm_symbol;
5410 patch_info->type = MONO_PATCH_INFO_NONE;
5411 acfg->stats.direct_calls ++;
5414 acfg->stats.all_calls ++;
5415 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5416 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5417 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5418 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5420 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5421 if (direct_pinvoke) {
5423 g_assert (strlen (direct_pinvoke) < 1000);
5424 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5427 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5428 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5429 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5430 /* Call to a C function implementing a jit icall */
5432 external_call = TRUE;
5433 g_assert (strlen (sym) < 1000);
5434 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5436 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5437 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5438 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5439 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5440 /* Call to a jit icall without a wrapper */
5442 external_call = TRUE;
5443 g_assert (strlen (sym) < 1000);
5444 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5449 patch_info->type = MONO_PATCH_INFO_NONE;
5450 acfg->stats.direct_calls ++;
5453 if (!got_only && !direct_call) {
5454 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5456 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5458 direct_call_target = plt_entry->symbol;
5460 /* Nullify the patch */
5461 patch_info->type = MONO_PATCH_INFO_NONE;
5462 plt_entry->jit_used = TRUE;
5469 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5470 i += call_size - INST_LEN;
5474 got_slot = get_got_offset (acfg, FALSE, patch_info);
5476 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5477 i += code_size - INST_LEN;
5483 #endif /* MONO_ARCH_AOT_SUPPORTED */
5486 /* Find next patch */
5488 for (pindex = start_index; pindex < patches->len; ++pindex) {
5489 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5490 if (patch_info->ip.i >= i)
5494 /* Try to emit multiple bytes at once */
5495 if (pindex < patches->len && patch_info->ip.i > i) {
5498 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5499 if (locs && locs [limit])
5503 emit_code_bytes (acfg, code + i, limit - i);
5504 i = limit - INST_LEN;
5506 emit_code_bytes (acfg, code + i, INST_LEN);
5511 g_ptr_array_free (patches, TRUE);
5518 * Return a modified version of S which only includes characters permissible in symbols.
5521 sanitize_symbol (MonoAotCompile *acfg, char *s)
5523 gboolean process = FALSE;
5532 for (i = 0; i < len; ++i)
5533 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5538 gs = g_string_sized_new (len);
5539 for (i = 0; i < len; ++i) {
5541 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5542 g_string_append_c (gs, c);
5543 } else if (c > 0x7f) {
5544 /* multi-byte utf8 */
5545 g_string_append_printf (gs, "_0x%x", c);
5548 while (c >> 6 == 0x2) {
5549 g_string_append_printf (gs, "%x", c);
5553 g_string_append_printf (gs, "_");
5556 g_string_append_c (gs, '_');
5560 res = mono_mempool_strdup (acfg->mempool, gs->str);
5561 g_string_free (gs, TRUE);
5566 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5568 char *name1, *name2, *cached;
5569 int i, j, len, count;
5570 MonoMethod *cached_method;
5572 name1 = mono_method_full_name (method, TRUE);
5575 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5576 if ((!prefix || !*prefix) && name1 [0] == 'L')
5580 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5581 char adjustedPrefix [MAX_SYMBOL_SIZE];
5582 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5585 len = strlen (name1);
5586 name2 = (char *)malloc (strlen (prefix) + len + 16);
5587 memcpy (name2, prefix, strlen (prefix));
5588 j = strlen (prefix);
5589 for (i = 0; i < len; ++i) {
5590 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5592 } else if (isalnum (name1 [i])) {
5593 name2 [j ++] = name1 [i];
5594 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5596 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5599 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5609 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5610 if (!(cached_method && cached_method != method))
5612 sprintf (name2 + j, "_%d", count);
5616 cached = g_strdup (name2);
5617 g_hash_table_insert (cache, cached, method);
5623 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5628 char *debug_sym = NULL;
5629 char *symbol = NULL;
5630 int func_alignment = AOT_FUNC_ALIGNMENT;
5633 method = cfg->orig_method;
5634 code = cfg->native_code;
5636 method_index = get_method_index (acfg, method);
5637 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5639 /* Make the labels local */
5640 emit_section_change (acfg, ".text", 0);
5641 emit_alignment_code (acfg, func_alignment);
5643 if (acfg->global_symbols && acfg->need_no_dead_strip)
5644 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5646 emit_label (acfg, cfg->asm_symbol);
5648 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5650 * Write a C style symbol for every method, this has two uses:
5651 * - it works on platforms where the dwarf debugging info is not
5653 * - it allows the setting of breakpoints of aot-ed methods.
5655 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5656 cfg->asm_debug_symbol = g_strdup (debug_sym);
5658 if (acfg->need_no_dead_strip)
5659 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5660 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5661 emit_label (acfg, debug_sym);
5664 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5666 /* Emit a global symbol for the method */
5667 emit_global_inner (acfg, export_name, TRUE);
5668 emit_label (acfg, export_name);
5671 if (cfg->verbose_level > 0)
5672 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5674 acfg->stats.code_size += cfg->code_len;
5676 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5678 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 ()));
5682 if (acfg->aot_opts.write_symbols) {
5684 emit_symbol_size (acfg, debug_sym, ".");
5686 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5690 emit_label (acfg, symbol);
5697 * Encode PATCH_INFO into its disk representation.
5700 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5704 switch (patch_info->type) {
5705 case MONO_PATCH_INFO_NONE:
5707 case MONO_PATCH_INFO_IMAGE:
5708 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5710 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5711 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5712 case MONO_PATCH_INFO_GC_NURSERY_START:
5713 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5715 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5716 encode_value (patch_info->data.index, p, &p);
5718 case MONO_PATCH_INFO_METHOD_REL:
5719 encode_value ((gint)patch_info->data.offset, p, &p);
5721 case MONO_PATCH_INFO_SWITCH: {
5722 gpointer *table = (gpointer *)patch_info->data.table->table;
5725 encode_value (patch_info->data.table->table_size, p, &p);
5726 for (k = 0; k < patch_info->data.table->table_size; k++)
5727 encode_value ((int)(gssize)table [k], p, &p);
5730 case MONO_PATCH_INFO_METHODCONST:
5731 case MONO_PATCH_INFO_METHOD:
5732 case MONO_PATCH_INFO_METHOD_JUMP:
5733 case MONO_PATCH_INFO_ICALL_ADDR:
5734 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5735 case MONO_PATCH_INFO_METHOD_RGCTX:
5736 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5737 encode_method_ref (acfg, patch_info->data.method, p, &p);
5739 case MONO_PATCH_INFO_AOT_JIT_INFO:
5740 case MONO_PATCH_INFO_GET_TLS_TRAMP:
5741 case MONO_PATCH_INFO_SET_TLS_TRAMP:
5742 encode_value (patch_info->data.index, p, &p);
5744 case MONO_PATCH_INFO_INTERNAL_METHOD:
5745 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5746 guint32 len = strlen (patch_info->data.name);
5748 encode_value (len, p, &p);
5750 memcpy (p, patch_info->data.name, len);
5755 case MONO_PATCH_INFO_LDSTR: {
5756 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5757 guint32 token = patch_info->data.token->token;
5758 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5759 encode_value (image_index, p, &p);
5760 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5763 case MONO_PATCH_INFO_RVA:
5764 case MONO_PATCH_INFO_DECLSEC:
5765 case MONO_PATCH_INFO_LDTOKEN:
5766 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5767 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5768 encode_value (patch_info->data.token->token, p, &p);
5769 encode_value (patch_info->data.token->has_context, p, &p);
5770 if (patch_info->data.token->has_context)
5771 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5773 case MONO_PATCH_INFO_EXC_NAME: {
5774 MonoClass *ex_class;
5777 mono_class_load_from_name (mono_defaults.exception_class->image,
5778 "System", (const char *)patch_info->data.target);
5779 encode_klass_ref (acfg, ex_class, p, &p);
5782 case MONO_PATCH_INFO_R4:
5783 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5785 case MONO_PATCH_INFO_R8:
5786 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5787 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5789 case MONO_PATCH_INFO_VTABLE:
5790 case MONO_PATCH_INFO_CLASS:
5791 case MONO_PATCH_INFO_IID:
5792 case MONO_PATCH_INFO_ADJUSTED_IID:
5793 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5795 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5796 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5797 if (patch_info->data.del_tramp->method) {
5798 encode_value (1, p, &p);
5799 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5801 encode_value (0, p, &p);
5803 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5805 case MONO_PATCH_INFO_FIELD:
5806 case MONO_PATCH_INFO_SFLDA:
5807 encode_field_info (acfg, patch_info->data.field, p, &p);
5809 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5811 case MONO_PATCH_INFO_RGCTX_FETCH:
5812 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5813 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5818 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5819 * reference the same method, so encode the method only once.
5821 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5823 buf2 = (guint8 *)g_malloc (1024);
5826 encode_method_ref (acfg, entry->method, p2, &p2);
5827 g_assert (p2 - buf2 < 1024);
5829 offset = add_to_blob (acfg, buf2, p2 - buf2);
5832 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5837 encode_value (offset, p, &p);
5838 g_assert ((int)entry->info_type < 256);
5839 g_assert (entry->data->type < 256);
5840 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5841 encode_patch (acfg, entry->data, p, &p);
5844 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5845 case MONO_PATCH_INFO_AOT_MODULE:
5847 case MONO_PATCH_INFO_SIGNATURE:
5848 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5849 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5851 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5852 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5853 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5855 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5856 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5859 encode_method_ref (acfg, info->method, p, &p);
5860 encode_value (info->num_entries, p, &p);
5861 for (i = 0; i < info->num_entries; ++i) {
5862 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5864 encode_value (template_->info_type, p, &p);
5865 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5866 case MONO_PATCH_INFO_CLASS:
5867 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5869 case MONO_PATCH_INFO_FIELD:
5870 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5873 g_assert_not_reached ();
5879 case MONO_PATCH_INFO_LDSTR_LIT: {
5880 const char *s = (const char *)patch_info->data.target;
5881 int len = strlen (s);
5883 encode_value (len, p, &p);
5884 memcpy (p, s, len + 1);
5888 case MONO_PATCH_INFO_VIRT_METHOD:
5889 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5890 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5892 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5893 case MONO_PATCH_INFO_JIT_THREAD_ATTACH:
5896 g_warning ("unable to handle jump info %d", patch_info->type);
5897 g_assert_not_reached ();
5904 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5907 guint32 pindex, offset;
5908 MonoJumpInfo *patch_info;
5910 encode_value (n_patches, p, &p);
5912 for (pindex = 0; pindex < patches->len; ++pindex) {
5913 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5915 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5919 offset = get_got_offset (acfg, llvm, patch_info);
5920 encode_value (offset, p, &p);
5927 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5930 int pindex, buf_size, n_patches;
5932 MonoJumpInfo *patch_info;
5933 guint32 method_index;
5935 guint32 first_got_offset;
5937 method = cfg->orig_method;
5939 method_index = get_method_index (acfg, method);
5941 /* Sort relocations */
5942 patches = g_ptr_array_new ();
5943 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5944 g_ptr_array_add (patches, patch_info);
5945 g_ptr_array_sort (patches, compare_patches);
5947 first_got_offset = acfg->cfgs [method_index]->got_offset;
5949 /**********************/
5950 /* Encode method info */
5951 /**********************/
5953 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5954 p = buf = (guint8 *)g_malloc (buf_size);
5956 if (mono_class_get_cctor (method->klass)) {
5957 encode_value (1, p, &p);
5958 encode_klass_ref (acfg, method->klass, p, &p);
5960 /* Not needed when loading the method */
5961 encode_value (0, p, &p);
5964 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5967 for (pindex = 0; pindex < patches->len; ++pindex) {
5968 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5970 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5971 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5972 patch_info->type = MONO_PATCH_INFO_NONE;
5977 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5978 /* Stored in a GOT slot initialized at module load time */
5979 patch_info->type = MONO_PATCH_INFO_NONE;
5983 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5984 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5985 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5986 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5987 /* Stored in a GOT slot initialized at module load time */
5988 patch_info->type = MONO_PATCH_INFO_NONE;
5992 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5993 /* Calls are made through the PLT */
5994 patch_info->type = MONO_PATCH_INFO_NONE;
6002 g_assert (cfg->has_got_slots);
6004 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
6006 g_ptr_array_free (patches, TRUE);
6008 acfg->stats.info_size += p - buf;
6010 g_assert (p - buf < buf_size);
6012 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
6017 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
6019 guint32 cache_index;
6022 /* Reuse the unwind module to canonize and store unwind info entries */
6023 cache_index = mono_cache_unwind_info (encoded, encoded_len);
6025 /* Use +/- 1 to distinguish 0s from missing entries */
6026 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
6034 * It would be easier to use assembler symbols, but the caller needs an
6037 offset = acfg->unwind_info_offset;
6038 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
6039 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
6042 encode_value (encoded_len, p, &p);
6044 acfg->unwind_info_offset += encoded_len + (p - buf);
6050 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
6053 guint32 debug_info_size, seq_points_size;
6055 MonoMethodHeader *header;
6056 guint8 *p, *buf, *debug_info;
6057 MonoJitInfo *jinfo = cfg->jit_info;
6059 gboolean use_unwind_ops = FALSE;
6060 MonoSeqPointInfo *seq_points;
6062 code = cfg->native_code;
6063 header = cfg->header;
6065 if (!acfg->aot_opts.nodebug) {
6066 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
6069 debug_info_size = 0;
6072 seq_points = cfg->seq_point_info;
6073 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
6075 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
6077 p = buf = (guint8 *)g_malloc (buf_size);
6079 use_unwind_ops = cfg->unwind_ops != NULL;
6081 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);
6083 encode_value (flags, p, &p);
6085 if (use_unwind_ops) {
6086 guint32 encoded_len;
6088 guint32 unwind_desc;
6090 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6092 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6093 encode_value (unwind_desc, p, &p);
6097 encode_value (jinfo->unwind_info, p, &p);
6100 /*Encode the number of holes before the number of clauses to make decoding easier*/
6101 if (jinfo->has_try_block_holes) {
6102 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6103 encode_value (table->num_holes, p, &p);
6106 if (jinfo->has_arch_eh_info) {
6108 * In AOT mode, the code length is calculated from the address of the previous method,
6109 * which could include alignment padding, so calculating the start of the epilog as
6110 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6112 encode_value (jinfo->code_size, p, &p);
6115 /* Exception table */
6116 if (cfg->compile_llvm) {
6118 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6119 * since the information is only available to llc. Instead, we let llc save the data
6120 * into the LSDA, and read it from there at runtime.
6122 /* The assembly might be CIL stripped so emit the data ourselves */
6123 if (header->num_clauses)
6124 encode_value (header->num_clauses, p, &p);
6126 for (k = 0; k < header->num_clauses; ++k) {
6127 MonoExceptionClause *clause;
6129 clause = &header->clauses [k];
6131 encode_value (clause->flags, p, &p);
6132 if (clause->data.catch_class) {
6133 encode_value (1, p, &p);
6134 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6136 encode_value (0, p, &p);
6139 /* Emit the IL ranges too, since they might not be available at runtime */
6140 encode_value (clause->try_offset, p, &p);
6141 encode_value (clause->try_len, p, &p);
6142 encode_value (clause->handler_offset, p, &p);
6143 encode_value (clause->handler_len, p, &p);
6145 /* Emit a list of nesting clauses */
6146 for (i = 0; i < header->num_clauses; ++i) {
6148 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6150 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6152 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6153 encode_value (i, p, &p);
6155 encode_value (-1, p, &p);
6158 if (jinfo->num_clauses)
6159 encode_value (jinfo->num_clauses, p, &p);
6161 for (k = 0; k < jinfo->num_clauses; ++k) {
6162 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6164 encode_value (ei->flags, p, &p);
6165 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6166 /* Not used for catch clauses */
6167 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6168 encode_value (ei->exvar_offset, p, &p);
6170 encode_value (ei->exvar_offset, p, &p);
6173 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6174 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6176 if (ei->data.catch_class) {
6180 buf2 = (guint8 *)g_malloc (4096);
6182 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6184 g_assert (len < 4096);
6185 encode_value (len, p, &p);
6186 memcpy (p, buf2, len);
6190 encode_value (0, p, &p);
6194 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6195 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6196 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6200 if (jinfo->has_try_block_holes) {
6201 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6202 for (i = 0; i < table->num_holes; ++i) {
6203 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6204 encode_value (hole->clause, p, &p);
6205 encode_value (hole->length, p, &p);
6206 encode_value (hole->offset, p, &p);
6210 if (jinfo->has_arch_eh_info) {
6211 MonoArchEHJitInfo *eh_info;
6213 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6214 encode_value (eh_info->stack_size, p, &p);
6215 encode_value (eh_info->epilog_size, p, &p);
6218 if (jinfo->has_generic_jit_info) {
6219 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6220 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6224 encode_value (gi->nlocs, p, &p);
6226 for (i = 0; i < gi->nlocs; ++i) {
6227 MonoDwarfLocListEntry *entry = &gi->locations [i];
6229 encode_value (entry->is_reg ? 1 : 0, p, &p);
6230 encode_value (entry->reg, p, &p);
6232 encode_value (entry->offset, p, &p);
6234 g_assert (entry->from == 0);
6236 encode_value (entry->from, p, &p);
6237 encode_value (entry->to, p, &p);
6240 if (!cfg->compile_llvm) {
6241 encode_value (gi->has_this ? 1 : 0, p, &p);
6242 encode_value (gi->this_reg, p, &p);
6243 encode_value (gi->this_offset, p, &p);
6248 * Need to encode jinfo->method too, since it is not equal to 'method'
6249 * when using generic sharing.
6251 buf2 = (guint8 *)g_malloc (4096);
6253 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6255 g_assert (len < 4096);
6256 encode_value (len, p, &p);
6257 memcpy (p, buf2, len);
6261 if (gsctx && gsctx->is_gsharedvt) {
6262 encode_value (1, p, &p);
6264 encode_value (0, p, &p);
6268 if (seq_points_size)
6269 p += mono_seq_point_info_write (seq_points, p);
6271 g_assert (debug_info_size < buf_size);
6273 encode_value (debug_info_size, p, &p);
6274 if (debug_info_size) {
6275 memcpy (p, debug_info, debug_info_size);
6276 p += debug_info_size;
6277 g_free (debug_info);
6282 encode_value (cfg->gc_map_size, p, &p);
6283 /* The GC map requires 4 bytes of alignment */
6284 while ((gsize)p % 4)
6286 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6287 p += cfg->gc_map_size;
6290 acfg->stats.ex_info_size += p - buf;
6292 g_assert (p - buf < buf_size);
6295 /* The GC Map requires 4 byte alignment */
6296 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6301 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6304 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6306 int i, buf_size, res;
6307 gboolean no_special_static, cant_encode;
6308 gpointer iter = NULL;
6311 mono_error_cleanup (&error);
6315 p = buf = (guint8 *)g_malloc (buf_size);
6317 /* Mark as unusable */
6318 encode_value (-1, p, &p);
6320 res = add_to_blob (acfg, buf, p - buf);
6326 buf_size = 10240 + (klass->vtable_size * 16);
6327 p = buf = (guint8 *)g_malloc (buf_size);
6331 mono_class_init (klass);
6333 mono_class_get_nested_types (klass, &iter);
6334 g_assert (klass->nested_classes_inited);
6336 mono_class_setup_vtable (klass);
6339 * Emit all the information which is required for creating vtables so
6340 * the runtime does not need to create the MonoMethod structures which
6341 * take up a lot of space.
6344 no_special_static = !mono_class_has_special_static_fields (klass);
6346 /* Check whenever we have enough info to encode the vtable */
6347 cant_encode = FALSE;
6348 for (i = 0; i < klass->vtable_size; ++i) {
6349 MonoMethod *cm = klass->vtable [i];
6351 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6355 mono_class_has_finalizer (klass);
6356 if (mono_class_has_failure (klass))
6359 if (mono_class_is_gtd (klass) || cant_encode) {
6360 encode_value (-1, p, &p);
6362 gboolean has_nested = mono_class_get_nested_classes_property (klass) != NULL;
6363 encode_value (klass->vtable_size, p, &p);
6364 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);
6365 if (klass->has_cctor)
6366 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6367 if (klass->has_finalize)
6368 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6370 encode_value (klass->instance_size, p, &p);
6371 encode_value (mono_class_data_size (klass), p, &p);
6372 encode_value (klass->packing_size, p, &p);
6373 encode_value (klass->min_align, p, &p);
6375 for (i = 0; i < klass->vtable_size; ++i) {
6376 MonoMethod *cm = klass->vtable [i];
6379 encode_method_ref (acfg, cm, p, &p);
6381 encode_value (0, p, &p);
6385 acfg->stats.class_info_size += p - buf;
6387 g_assert (p - buf < buf_size);
6388 res = add_to_blob (acfg, buf, p - buf);
6395 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6397 char *debug_sym = NULL;
6400 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6401 /* Need to add a prefix to create unique symbols */
6402 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6404 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6405 prefix = mangle_symbol_alloc ("plt_");
6407 prefix = g_strdup ("plt_");
6412 case MONO_PATCH_INFO_METHOD:
6413 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6415 case MONO_PATCH_INFO_INTERNAL_METHOD:
6416 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6418 case MONO_PATCH_INFO_RGCTX_FETCH:
6419 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6421 case MONO_PATCH_INFO_ICALL_ADDR:
6422 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6423 char *s = get_debug_sym (ji->data.method, "", cache);
6425 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6429 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6430 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6438 return sanitize_symbol (acfg, debug_sym);
6442 * Calls made from AOTed code are routed through a table of jumps similar to the
6443 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6444 * control to the AOT runtime through a trampoline.
6447 emit_plt (MonoAotCompile *acfg)
6451 if (acfg->aot_opts.llvm_only) {
6452 g_assert (acfg->plt_offset == 1);
6458 emit_section_change (acfg, ".text", 0);
6459 emit_alignment_code (acfg, 16);
6460 emit_info_symbol (acfg, "plt");
6461 emit_label (acfg, acfg->plt_symbol);
6463 for (i = 0; i < acfg->plt_offset; ++i) {
6464 char *debug_sym = NULL;
6465 MonoPltEntry *plt_entry = NULL;
6469 * The first plt entry is unused.
6473 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6475 debug_sym = plt_entry->debug_sym;
6477 if (acfg->thumb_mixed && !plt_entry->jit_used)
6478 /* Emit only a thumb version */
6481 /* Skip plt entries not actually called */
6482 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6485 if (acfg->llvm && !acfg->thumb_mixed) {
6486 emit_label (acfg, plt_entry->llvm_symbol);
6488 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6489 #if defined(TARGET_MACH)
6490 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6496 if (acfg->need_no_dead_strip) {
6497 emit_unset_mode (acfg);
6498 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6500 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6501 emit_label (acfg, debug_sym);
6504 emit_label (acfg, plt_entry->symbol);
6506 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6509 emit_symbol_size (acfg, debug_sym, ".");
6512 if (acfg->thumb_mixed) {
6513 /* Make sure the ARM symbols don't alias the thumb ones */
6514 emit_zero_bytes (acfg, 16);
6517 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6520 for (i = 0; i < acfg->plt_offset; ++i) {
6521 char *debug_sym = NULL;
6522 MonoPltEntry *plt_entry = NULL;
6527 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6529 /* Skip plt entries not actually called by LLVM code */
6530 if (!plt_entry->llvm_used)
6533 if (acfg->aot_opts.write_symbols) {
6534 if (plt_entry->debug_sym)
6535 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6539 #if defined(TARGET_MACH)
6540 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6541 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6543 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6544 emit_label (acfg, debug_sym);
6546 fprintf (acfg->fp, "\n.thumb_func\n");
6548 emit_label (acfg, plt_entry->llvm_symbol);
6551 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6553 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6556 emit_symbol_size (acfg, debug_sym, ".");
6562 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6564 emit_info_symbol (acfg, "plt_end");
6568 * emit_trampoline_full:
6570 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6571 * create_jit_info_for_trampoline ().
6573 static G_GNUC_UNUSED void
6574 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6576 char start_symbol [MAX_SYMBOL_SIZE];
6577 char end_symbol [MAX_SYMBOL_SIZE];
6578 char symbol [MAX_SYMBOL_SIZE];
6579 guint32 buf_size, info_offset;
6580 MonoJumpInfo *patch_info;
6593 code_size = info->code_size;
6595 unwind_ops = info->unwind_ops;
6599 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6601 emit_section_change (acfg, ".text", 0);
6602 emit_global (acfg, start_symbol, TRUE);
6603 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6604 emit_label (acfg, start_symbol);
6606 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6607 emit_label (acfg, symbol);
6610 * The code should access everything through the GOT, so we pass
6613 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6615 emit_symbol_size (acfg, start_symbol, ".");
6618 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6619 emit_label (acfg, end_symbol);
6624 /* Sort relocations */
6625 patches = g_ptr_array_new ();
6626 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6627 if (patch_info->type != MONO_PATCH_INFO_NONE)
6628 g_ptr_array_add (patches, patch_info);
6629 g_ptr_array_sort (patches, compare_patches);
6631 buf_size = patches->len * 128 + 128;
6632 buf = (guint8 *)g_malloc (buf_size);
6635 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6636 g_assert (p - buf < buf_size);
6637 g_ptr_array_free (patches, TRUE);
6639 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6641 info_offset = add_to_blob (acfg, buf, p - buf);
6643 emit_section_change (acfg, RODATA_SECT, 0);
6644 emit_global (acfg, symbol, FALSE);
6645 emit_label (acfg, symbol);
6647 emit_int32 (acfg, info_offset);
6651 guint32 encoded_len;
6655 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6657 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6658 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6661 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6662 emit_int32 (acfg, uw_offset);
6665 /* Emit debug info */
6667 char symbol2 [MAX_SYMBOL_SIZE];
6669 sprintf (symbol, "%s", name);
6670 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6673 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6679 static G_GNUC_UNUSED void
6680 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6682 emit_trampoline_full (acfg, got_offset, info, TRUE);
6686 emit_trampolines (MonoAotCompile *acfg)
6688 char symbol [MAX_SYMBOL_SIZE];
6689 char end_symbol [MAX_SYMBOL_SIZE];
6690 int i, tramp_got_offset;
6692 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6696 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6699 g_assert (acfg->image->assembly);
6701 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6702 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6703 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6704 MonoTrampInfo *info;
6707 * Emit the generic trampolines.
6709 * We could save some code by treating the generic trampolines as a wrapper
6710 * method, but that approach has its own complexities, so we choose the simpler
6713 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6714 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6715 #ifdef DISABLE_REMOTING
6716 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6719 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6720 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6723 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6724 emit_trampoline (acfg, acfg->got_offset, info);
6727 /* Emit the exception related code pieces */
6728 mono_arch_get_restore_context (&info, TRUE);
6729 emit_trampoline (acfg, acfg->got_offset, info);
6730 mono_arch_get_call_filter (&info, TRUE);
6731 emit_trampoline (acfg, acfg->got_offset, info);
6732 mono_arch_get_throw_exception (&info, TRUE);
6733 emit_trampoline (acfg, acfg->got_offset, info);
6734 mono_arch_get_rethrow_exception (&info, TRUE);
6735 emit_trampoline (acfg, acfg->got_offset, info);
6736 mono_arch_get_throw_corlib_exception (&info, TRUE);
6737 emit_trampoline (acfg, acfg->got_offset, info);
6739 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6740 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6741 emit_trampoline (acfg, acfg->got_offset, info);
6742 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6743 emit_trampoline (acfg, acfg->got_offset, info);
6746 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6747 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6749 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6751 /* Create a separate out trampoline for more information in stack traces */
6752 info->name = g_strdup ("gsharedvt_out_trampoline");
6753 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6757 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6759 GSList *l = mono_arch_get_trampolines (TRUE);
6762 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6764 emit_trampoline (acfg, acfg->got_offset, info);
6770 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6773 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6774 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6775 emit_trampoline (acfg, acfg->got_offset, info);
6778 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6779 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6780 emit_trampoline (acfg, acfg->got_offset, info);
6784 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6785 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6786 emit_trampoline (acfg, acfg->got_offset, info);
6792 /* delegate_invoke_impl trampolines */
6793 l = mono_arch_get_delegate_invoke_impls ();
6795 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6797 emit_trampoline (acfg, acfg->got_offset, info);
6802 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6803 mono_arch_create_handler_block_trampoline (&info, TRUE);
6804 emit_trampoline (acfg, acfg->got_offset, info);
6807 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6809 /* Emit trampolines which are numerous */
6812 * These include the following:
6813 * - specific trampolines
6814 * - static rgctx invoke trampolines
6816 * These trampolines have the same code, they are parameterized by GOT
6818 * They are defined in this file, in the arch_... routines instead of
6819 * in tramp-<ARCH>.c, since it is easier to do it this way.
6823 * When running in aot-only mode, we can't create specific trampolines at
6824 * runtime, so we create a few, and save them in the AOT file.
6825 * Normal trampolines embed their argument as a literal inside the
6826 * trampoline code, we can't do that here, so instead we embed an offset
6827 * which needs to be added to the trampoline address to get the address of
6828 * the GOT slot which contains the argument value.
6829 * The generated trampolines jump to the generic trampolines using another
6830 * GOT slot, which will be setup by the AOT loader to point to the
6831 * generic trampoline code of the given type.
6835 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6839 emit_section_change (acfg, ".text", 0);
6841 tramp_got_offset = acfg->got_offset;
6843 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6845 case MONO_AOT_TRAMP_SPECIFIC:
6846 sprintf (symbol, "specific_trampolines");
6848 case MONO_AOT_TRAMP_STATIC_RGCTX:
6849 sprintf (symbol, "static_rgctx_trampolines");
6851 case MONO_AOT_TRAMP_IMT:
6852 sprintf (symbol, "imt_trampolines");
6854 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6855 sprintf (symbol, "gsharedvt_arg_trampolines");
6858 g_assert_not_reached ();
6861 sprintf (end_symbol, "%s_e", symbol);
6863 if (acfg->aot_opts.write_symbols)
6864 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6866 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6867 emit_info_symbol (acfg, symbol);
6869 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6871 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6875 case MONO_AOT_TRAMP_SPECIFIC:
6876 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6877 tramp_got_offset += 2;
6879 case MONO_AOT_TRAMP_STATIC_RGCTX:
6880 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6881 tramp_got_offset += 2;
6883 case MONO_AOT_TRAMP_IMT:
6884 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6885 tramp_got_offset += 1;
6887 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6888 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6889 tramp_got_offset += 2;
6892 g_assert_not_reached ();
6894 if (!acfg->trampoline_size [ntype]) {
6895 g_assert (tramp_size);
6896 acfg->trampoline_size [ntype] = tramp_size;
6900 emit_label (acfg, end_symbol);
6901 emit_int32 (acfg, 0);
6904 arch_emit_specific_trampoline_pages (acfg);
6906 /* Reserve some entries at the end of the GOT for our use */
6907 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6910 acfg->got_offset += acfg->num_trampoline_got_entries;
6914 str_begins_with (const char *str1, const char *str2)
6916 int len = strlen (str2);
6917 return strncmp (str1, str2, len) == 0;
6921 mono_aot_readonly_field_override (MonoClassField *field)
6924 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6925 char *p = rdv->name;
6927 len = strlen (field->parent->name_space);
6928 if (strncmp (p, field->parent->name_space, len))
6933 len = strlen (field->parent->name);
6934 if (strncmp (p, field->parent->name, len))
6939 if (strcmp (p, field->name))
6941 switch (rdv->type) {
6943 return &rdv->value.i1;
6945 return &rdv->value.i2;
6947 return &rdv->value.i4;
6956 add_readonly_value (MonoAotOptions *opts, const char *val)
6961 /* the format of val is:
6962 * namespace.typename.fieldname=type/value
6963 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6965 fval = strrchr (val, '/');
6967 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6970 tval = strrchr (val, '=');
6972 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6975 rdv = g_new0 (ReadOnlyValue, 1);
6976 rdv->name = (char *)g_malloc0 (tval - val + 1);
6977 memcpy (rdv->name, val, tval - val);
6980 if (strncmp (tval, "i1", 2) == 0) {
6981 rdv->value.i1 = atoi (fval);
6982 rdv->type = MONO_TYPE_I1;
6983 } else if (strncmp (tval, "i2", 2) == 0) {
6984 rdv->value.i2 = atoi (fval);
6985 rdv->type = MONO_TYPE_I2;
6986 } else if (strncmp (tval, "i4", 2) == 0) {
6987 rdv->value.i4 = atoi (fval);
6988 rdv->type = MONO_TYPE_I4;
6990 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6993 rdv->next = readonly_values;
6994 readonly_values = rdv;
6998 clean_path (gchar * path)
7003 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
7006 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
7013 wrap_path (gchar * path)
7019 // If the string contains no spaces, just return the original string.
7020 if (strstr (path, " ") == NULL)
7023 // If the string is already wrapped in quotes, return it.
7024 len = strlen (path);
7025 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
7028 // If the string contains spaces, then wrap it in quotes.
7029 gchar *clean = g_strdup_printf ("\"%s\"", path);
7034 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
7036 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
7038 ptrdiff_t len = end-start;
7040 g_ptr_array_add (args, g_strndup (start, len));
7044 mono_aot_split_options (const char *aot_options)
7046 enum MonoAotOptionState {
7047 MONO_AOT_OPTION_STATE_DEFAULT,
7048 MONO_AOT_OPTION_STATE_STRING,
7049 MONO_AOT_OPTION_STATE_ESCAPE,
7052 GPtrArray *args = g_ptr_array_new ();
7053 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
7054 gchar const *opt_start = aot_options;
7055 gboolean end_of_string = FALSE;
7058 g_return_val_if_fail (aot_options != NULL, NULL);
7060 while ((cur = *aot_options) != '\0') {
7061 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
7066 // If we find a quote, then if we're in the default case then
7067 // it means we've found the start of a string, if not then it
7068 // means we've found the end of the string and should switch
7069 // back to the default case.
7071 case MONO_AOT_OPTION_STATE_DEFAULT:
7072 state = MONO_AOT_OPTION_STATE_STRING;
7074 case MONO_AOT_OPTION_STATE_STRING:
7075 state = MONO_AOT_OPTION_STATE_DEFAULT;
7077 case MONO_AOT_OPTION_STATE_ESCAPE:
7078 g_assert_not_reached ();
7083 // If we've found an escaping operator, then this means we
7084 // should not process the next character if inside a string.
7085 if (state == MONO_AOT_OPTION_STATE_STRING)
7086 state = MONO_AOT_OPTION_STATE_ESCAPE;
7089 // If we're in the default state then this means we've found
7090 // an option, store it for later processing.
7091 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7099 // If the next character is end of string, then process the last option.
7100 if (*(aot_options) == '\0') {
7101 end_of_string = TRUE;
7107 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7108 opt_start = ++aot_options;
7111 goto restart; // Check for null and continue loop
7118 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7122 args = mono_aot_split_options (aot_options ? aot_options : "");
7123 for (int i = 0; i < args->len; ++i) {
7124 const char *arg = (const char *)g_ptr_array_index (args, i);
7126 if (str_begins_with (arg, "outfile=")) {
7127 opts->outfile = g_strdup (arg + strlen ("outfile="));
7128 } else if (str_begins_with (arg, "llvm-outfile=")) {
7129 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7130 } else if (str_begins_with (arg, "temp-path=")) {
7131 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7132 } else if (str_begins_with (arg, "save-temps")) {
7133 opts->save_temps = TRUE;
7134 } else if (str_begins_with (arg, "keep-temps")) {
7135 opts->save_temps = TRUE;
7136 } else if (str_begins_with (arg, "write-symbols")) {
7137 opts->write_symbols = TRUE;
7138 } else if (str_begins_with (arg, "no-write-symbols")) {
7139 opts->write_symbols = FALSE;
7140 } else if (str_begins_with (arg, "metadata-only")) {
7141 opts->metadata_only = TRUE;
7142 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7143 opts->bind_to_runtime_version = TRUE;
7144 } else if (str_begins_with (arg, "full")) {
7145 opts->mode = MONO_AOT_MODE_FULL;
7146 } else if (str_begins_with (arg, "hybrid")) {
7147 opts->mode = MONO_AOT_MODE_HYBRID;
7148 } else if (str_begins_with (arg, "threads=")) {
7149 opts->nthreads = atoi (arg + strlen ("threads="));
7150 } else if (str_begins_with (arg, "static")) {
7151 opts->static_link = TRUE;
7152 opts->no_dlsym = TRUE;
7153 } else if (str_begins_with (arg, "asmonly")) {
7154 opts->asm_only = TRUE;
7155 } else if (str_begins_with (arg, "asmwriter")) {
7156 opts->asm_writer = TRUE;
7157 } else if (str_begins_with (arg, "nodebug")) {
7158 opts->nodebug = TRUE;
7159 } else if (str_begins_with (arg, "dwarfdebug")) {
7160 opts->dwarf_debug = TRUE;
7161 } else if (str_begins_with (arg, "nopagetrampolines")) {
7162 opts->use_trampolines_page = FALSE;
7163 } else if (str_begins_with (arg, "ntrampolines=")) {
7164 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7165 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7166 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7167 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7168 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7169 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7170 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7171 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7172 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7173 } else if (str_begins_with (arg, "tool-prefix=")) {
7174 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7175 } else if (str_begins_with (arg, "ld-flags=")) {
7176 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7177 } else if (str_begins_with (arg, "soft-debug")) {
7178 opts->soft_debug = TRUE;
7179 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7180 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7181 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7182 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7183 } else if (str_begins_with (arg, "msym-dir=")) {
7184 debug_options.no_seq_points_compact_data = FALSE;
7185 opts->gen_msym_dir = TRUE;
7186 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7187 } else if (str_begins_with (arg, "direct-pinvoke")) {
7188 opts->direct_pinvoke = TRUE;
7189 } else if (str_begins_with (arg, "direct-icalls")) {
7190 opts->direct_icalls = TRUE;
7191 } else if (str_begins_with (arg, "no-direct-calls")) {
7192 opts->no_direct_calls = TRUE;
7193 } else if (str_begins_with (arg, "print-skipped")) {
7194 opts->print_skipped_methods = TRUE;
7195 } else if (str_begins_with (arg, "stats")) {
7197 } else if (str_begins_with (arg, "no-instances")) {
7198 opts->no_instances = TRUE;
7199 } else if (str_begins_with (arg, "log-generics")) {
7200 opts->log_generics = TRUE;
7201 } else if (str_begins_with (arg, "log-instances=")) {
7202 opts->log_instances = TRUE;
7203 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7204 } else if (str_begins_with (arg, "log-instances")) {
7205 opts->log_instances = TRUE;
7206 } else if (str_begins_with (arg, "internal-logfile=")) {
7207 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7208 } else if (str_begins_with (arg, "mtriple=")) {
7209 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7210 } else if (str_begins_with (arg, "llvm-path=")) {
7211 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7212 } else if (!strcmp (arg, "llvm")) {
7214 } else if (str_begins_with (arg, "readonly-value=")) {
7215 add_readonly_value (opts, arg + strlen ("readonly-value="));
7216 } else if (str_begins_with (arg, "info")) {
7217 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7219 } else if (str_begins_with (arg, "gc-maps")) {
7220 mini_gc_enable_gc_maps_for_aot ();
7221 } else if (str_begins_with (arg, "dump")) {
7222 opts->dump_json = TRUE;
7223 } else if (str_begins_with (arg, "llvmonly")) {
7224 opts->mode = MONO_AOT_MODE_FULL;
7226 opts->llvm_only = TRUE;
7227 } else if (str_begins_with (arg, "data-outfile=")) {
7228 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7229 } else if (str_begins_with (arg, "profile=")) {
7230 opts->profile_files = g_list_append (opts->profile_files, g_strdup (arg + strlen ("profile=")));
7231 } else if (!strcmp (arg, "profile-only")) {
7232 opts->profile_only = TRUE;
7233 } else if (!strcmp (arg, "verbose")) {
7234 opts->verbose = TRUE;
7235 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7236 printf ("Supported options for --aot:\n");
7237 printf (" outfile=\n");
7238 printf (" llvm-outfile=\n");
7239 printf (" llvm-path=\n");
7240 printf (" temp-path=\n");
7241 printf (" save-temps\n");
7242 printf (" keep-temps\n");
7243 printf (" write-symbols\n");
7244 printf (" metadata-only\n");
7245 printf (" bind-to-runtime-version\n");
7247 printf (" threads=\n");
7248 printf (" static\n");
7249 printf (" asmonly\n");
7250 printf (" asmwriter\n");
7251 printf (" nodebug\n");
7252 printf (" dwarfdebug\n");
7253 printf (" ntrampolines=\n");
7254 printf (" nrgctx-trampolines=\n");
7255 printf (" nimt-trampolines=\n");
7256 printf (" ngsharedvt-trampolines=\n");
7257 printf (" tool-prefix=\n");
7258 printf (" readonly-value=\n");
7259 printf (" soft-debug\n");
7260 printf (" msym-dir=\n");
7261 printf (" gc-maps\n");
7262 printf (" print-skipped\n");
7263 printf (" no-instances\n");
7264 printf (" stats\n");
7267 printf (" verbose\n");
7268 printf (" help/?\n");
7271 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7275 g_free ((gpointer) arg);
7278 if (opts->use_trampolines_page) {
7279 opts->ntrampolines = 0;
7280 opts->nrgctx_trampolines = 0;
7281 opts->nimt_trampolines = 0;
7282 opts->ngsharedvt_arg_trampolines = 0;
7285 g_ptr_array_free (args, /*free_seg=*/TRUE);
7289 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7291 MonoMethod *method = (MonoMethod*)key;
7292 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7293 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7294 MonoJumpInfoToken *new_ji;
7296 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7297 new_ji->image = ji->image;
7298 new_ji->token = ji->token;
7299 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7303 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7305 if (klass->type_token)
7307 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7310 return can_encode_class (acfg, klass->element_class);
7315 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7317 if (method->wrapper_type) {
7318 switch (method->wrapper_type) {
7319 case MONO_WRAPPER_NONE:
7320 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7321 case MONO_WRAPPER_XDOMAIN_INVOKE:
7322 case MONO_WRAPPER_STFLD:
7323 case MONO_WRAPPER_LDFLD:
7324 case MONO_WRAPPER_LDFLDA:
7325 case MONO_WRAPPER_STELEMREF:
7326 case MONO_WRAPPER_PROXY_ISINST:
7327 case MONO_WRAPPER_ALLOC:
7328 case MONO_WRAPPER_REMOTING_INVOKE:
7329 case MONO_WRAPPER_UNKNOWN:
7330 case MONO_WRAPPER_WRITE_BARRIER:
7331 case MONO_WRAPPER_DELEGATE_INVOKE:
7332 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7333 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7334 case MONO_WRAPPER_SYNCHRONIZED:
7336 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7337 case MONO_WRAPPER_CASTCLASS: {
7338 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7347 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7351 if (!method->token) {
7352 /* The method is part of a constructed type like Int[,].Set (). */
7353 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7354 if (method->klass->rank)
7364 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7366 switch (patch_info->type) {
7367 case MONO_PATCH_INFO_METHOD:
7368 case MONO_PATCH_INFO_METHODCONST:
7369 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7370 MonoMethod *method = patch_info->data.method;
7372 return can_encode_method (acfg, method);
7374 case MONO_PATCH_INFO_VTABLE:
7375 case MONO_PATCH_INFO_CLASS:
7376 case MONO_PATCH_INFO_IID:
7377 case MONO_PATCH_INFO_ADJUSTED_IID:
7378 if (!can_encode_class (acfg, patch_info->data.klass)) {
7379 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7383 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7384 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7385 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7390 case MONO_PATCH_INFO_RGCTX_FETCH:
7391 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7392 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7394 if (!can_encode_method (acfg, entry->method))
7396 if (!can_encode_patch (acfg, entry->data))
7408 is_concrete_type (MonoType *t)
7413 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7415 if (t->type == MONO_TYPE_GENERICINST) {
7416 MonoGenericContext *orig_ctx;
7417 MonoGenericInst *inst;
7420 if (!MONO_TYPE_ISSTRUCT (t))
7422 klass = mono_class_from_mono_type (t);
7423 orig_ctx = &mono_class_get_generic_class (klass)->context;
7425 inst = orig_ctx->class_inst;
7427 for (i = 0; i < inst->type_argc; ++i) {
7428 arg = mini_get_underlying_type (inst->type_argv [i]);
7429 if (!is_concrete_type (arg))
7433 inst = orig_ctx->method_inst;
7435 for (i = 0; i < inst->type_argc; ++i) {
7436 arg = mini_get_underlying_type (inst->type_argv [i]);
7437 if (!is_concrete_type (arg))
7445 /* LOCKING: Assumes the loader lock is held */
7447 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7449 MonoMethod *wrapper;
7450 gboolean concrete = TRUE;
7451 gboolean add_in = gsharedvt_in;
7452 gboolean add_out = gsharedvt_out;
7454 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7456 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7459 if (!add_in && !add_out)
7462 if (mini_is_gsharedvt_variable_signature (sig))
7466 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7468 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7470 if (!sig->has_type_parameters) {
7471 //printf ("%s\n", mono_signature_full_name (sig));
7474 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7475 add_extra_method (acfg, wrapper);
7477 if (gsharedvt_out) {
7478 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7479 add_extra_method (acfg, wrapper);
7482 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7483 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7486 //printf ("%s\n", mono_signature_full_name (sig));
7488 copy->ret = mini_get_underlying_type (sig->ret);
7489 if (!is_concrete_type (copy->ret))
7491 for (i = 0; i < sig->param_count; ++i) {
7492 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7493 if (!is_concrete_type (copy->params [i]))
7497 copy->has_type_parameters = 0;
7500 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7501 add_extra_method (acfg, wrapper);
7504 if (gsharedvt_out) {
7505 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7506 add_extra_method (acfg, wrapper);
7509 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7517 * AOT compile a given method.
7518 * This function might be called by multiple threads, so it must be thread-safe.
7521 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7524 MonoJumpInfo *patch_info;
7527 MonoMethod *wrapped;
7531 if (acfg->aot_opts.metadata_only)
7534 mono_acfg_lock (acfg);
7535 index = get_method_index (acfg, method);
7536 mono_acfg_unlock (acfg);
7538 /* fixme: maybe we can also precompile wrapper methods */
7539 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7540 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7541 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7542 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7546 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7549 wrapped = mono_marshal_method_from_wrapper (method);
7550 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7551 // FIXME: The wrapper should be generic too, but it is not
7554 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7557 if (acfg->aot_opts.profile_only && !method->is_inflated && !g_hash_table_lookup (acfg->profile_methods, method))
7560 InterlockedIncrement (&acfg->stats.mcount);
7563 if (method->is_generic || mono_class_is_gtd (method->klass)) {
7564 InterlockedIncrement (&acfg->stats.genericcount);
7569 //acfg->aot_opts.print_skipped_methods = TRUE;
7572 * Since these methods are the only ones which are compiled with
7573 * AOT support, and they are not used by runtime startup/shutdown code,
7574 * the runtime will not see AOT methods during AOT compilation,so it
7575 * does not need to support them by creating a fake GOT etc.
7577 flags = JIT_FLAG_AOT;
7578 if (mono_aot_mode_is_full (&acfg->aot_opts))
7579 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7581 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7582 if (acfg->aot_opts.llvm_only)
7583 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7584 if (acfg->aot_opts.no_direct_calls)
7585 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7586 if (acfg->aot_opts.direct_pinvoke)
7587 flags = (JitFlags)(flags | JIT_FLAG_DIRECT_PINVOKE);
7589 jit_timer = mono_time_track_start ();
7590 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7591 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7593 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7594 if (acfg->aot_opts.print_skipped_methods)
7595 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7596 InterlockedIncrement (&acfg->stats.genericcount);
7599 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7600 if (acfg->aot_opts.print_skipped_methods)
7601 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7602 /* Let the exception happen at runtime */
7606 if (cfg->disable_aot) {
7607 if (acfg->aot_opts.print_skipped_methods)
7608 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7609 InterlockedIncrement (&acfg->stats.ocount);
7612 cfg->method_index = index;
7614 /* Nullify patches which need no aot processing */
7615 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7616 switch (patch_info->type) {
7617 case MONO_PATCH_INFO_LABEL:
7618 case MONO_PATCH_INFO_BB:
7619 patch_info->type = MONO_PATCH_INFO_NONE;
7626 /* Collect method->token associations from the cfg */
7627 mono_acfg_lock (acfg);
7628 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7629 mono_acfg_unlock (acfg);
7630 g_hash_table_destroy (cfg->token_info_hash);
7631 cfg->token_info_hash = NULL;
7634 * Check for absolute addresses.
7637 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7638 switch (patch_info->type) {
7639 case MONO_PATCH_INFO_ABS:
7640 /* unable to handle this */
7649 if (acfg->aot_opts.print_skipped_methods)
7650 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7651 InterlockedIncrement (&acfg->stats.abscount);
7655 /* Lock for the rest of the code */
7656 mono_acfg_lock (acfg);
7659 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7660 else if (cfg->gshared)
7661 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7662 else if (cfg->method->wrapper_type)
7663 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7665 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7668 * Check for methods/klasses we can't encode.
7671 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7672 if (!can_encode_patch (acfg, patch_info))
7677 if (acfg->aot_opts.print_skipped_methods)
7678 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7679 acfg->stats.ocount++;
7680 mono_acfg_unlock (acfg);
7684 if (!cfg->compile_llvm)
7685 acfg->has_jitted_code = TRUE;
7687 if (method->is_inflated && acfg->aot_opts.log_instances) {
7688 if (acfg->instances_logfile)
7689 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7691 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7694 /* Adds generic instances referenced by this method */
7696 * The depth is used to avoid infinite loops when generic virtual recursion is
7699 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7700 if (!acfg->aot_opts.no_instances && depth < 32 && mono_aot_mode_is_full (&acfg->aot_opts)) {
7701 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7702 switch (patch_info->type) {
7703 case MONO_PATCH_INFO_RGCTX_FETCH:
7704 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7705 case MONO_PATCH_INFO_METHOD: {
7706 MonoMethod *m = NULL;
7708 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7709 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7711 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7712 m = e->data->data.method;
7714 m = patch_info->data.method;
7719 if (m->is_inflated && mono_aot_mode_is_full (&acfg->aot_opts)) {
7720 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7721 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7722 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7723 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7724 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7725 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7727 add_extra_method_with_depth (acfg, m, depth + 1);
7728 add_types_from_method_header (acfg, m);
7731 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7733 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7734 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7736 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7737 add_extra_method_with_depth (acfg, m, depth + 1);
7741 case MONO_PATCH_INFO_VTABLE: {
7742 MonoClass *klass = patch_info->data.klass;
7744 if (mono_class_is_ginst (klass) && !mini_class_is_generic_sharable (klass))
7745 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7748 case MONO_PATCH_INFO_SFLDA: {
7749 MonoClass *klass = patch_info->data.field->parent;
7751 /* The .cctor needs to run at runtime. */
7752 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))
7753 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7762 /* Determine whenever the method has GOT slots */
7763 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7764 switch (patch_info->type) {
7765 case MONO_PATCH_INFO_GOT_OFFSET:
7766 case MONO_PATCH_INFO_NONE:
7767 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7768 case MONO_PATCH_INFO_GC_NURSERY_START:
7769 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7771 case MONO_PATCH_INFO_IMAGE:
7772 /* The assembly is stored in GOT slot 0 */
7773 if (patch_info->data.image != acfg->image)
7774 cfg->has_got_slots = TRUE;
7777 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7778 cfg->has_got_slots = TRUE;
7783 if (!cfg->has_got_slots)
7784 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7786 /* Add gsharedvt wrappers for signatures used by the method */
7787 if (acfg->aot_opts.llvm_only) {
7790 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7791 /* These only need out wrappers */
7792 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7794 for (l = cfg->signatures; l; l = l->next) {
7795 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7797 /* These only need in wrappers */
7798 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7803 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7805 /* Make a copy of the patch info which is in the mempool */
7807 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7809 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7810 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7813 patches = new_patch_info;
7815 patches_end->next = new_patch_info;
7816 patches_end = new_patch_info;
7818 cfg->patch_info = patches;
7820 /* Make a copy of the unwind info */
7822 GSList *l, *unwind_ops;
7826 for (l = cfg->unwind_ops; l; l = l->next) {
7827 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7828 memcpy (op, l->data, sizeof (MonoUnwindOp));
7829 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7831 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7833 /* Make a copy of the argument/local info */
7836 MonoInst **args, **locals;
7837 MonoMethodSignature *sig;
7838 MonoMethodHeader *header;
7841 sig = mono_method_signature (method);
7842 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7843 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7844 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7845 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7849 header = mono_method_get_header_checked (method, &error);
7850 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7851 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7852 for (i = 0; i < header->num_locals; ++i) {
7853 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7854 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7856 mono_metadata_free_mh (header);
7857 cfg->locals = locals;
7860 /* Free some fields used by cfg to conserve memory */
7861 mono_empty_compile (cfg);
7863 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7865 while (index >= acfg->cfgs_size) {
7866 MonoCompile **new_cfgs;
7869 new_size = acfg->cfgs_size * 2;
7870 new_cfgs = g_new0 (MonoCompile*, new_size);
7871 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7872 g_free (acfg->cfgs);
7873 acfg->cfgs = new_cfgs;
7874 acfg->cfgs_size = new_size;
7876 acfg->cfgs [index] = cfg;
7878 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7880 mono_update_jit_stats (cfg);
7883 if (cfg->orig_method->wrapper_type)
7884 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7887 mono_acfg_unlock (acfg);
7889 InterlockedIncrement (&acfg->stats.ccount);
7892 static mono_thread_start_return_t WINAPI
7893 compile_thread_main (gpointer user_data)
7895 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [0];
7896 GPtrArray *methods = ((GPtrArray **)user_data) [1];
7900 MonoInternalThread *internal = mono_thread_internal_current ();
7901 mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "AOT compiler"), TRUE, FALSE, &error);
7902 mono_error_assert_ok (&error);
7904 for (i = 0; i < methods->len; ++i)
7905 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7910 /* Used by the LLVM backend */
7912 mono_aot_get_got_offset (MonoJumpInfo *ji)
7914 return get_got_offset (llvm_acfg, TRUE, ji);
7918 * mono_aot_is_shared_got_offset:
7920 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7921 * when the AOT image is loaded.
7924 mono_aot_is_shared_got_offset (int offset)
7926 return offset < llvm_acfg->nshared_got_entries;
7930 mono_aot_get_method_name (MonoCompile *cfg)
7932 if (llvm_acfg->aot_opts.static_link)
7933 /* Include the assembly name too to avoid duplicate symbol errors */
7934 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7936 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7940 * mono_aot_is_linkonce_method:
7942 * Return whenever METHOD should be emitted with linkonce linkage,
7943 * eliminating duplicate copies when compiling in static mode.
7946 mono_aot_is_linkonce_method (MonoMethod *method)
7952 // FIXME: Add more cases
7953 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7955 info = mono_marshal_get_wrapper_info (method);
7956 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7963 append_mangled_type (GString *s, MonoType *t)
7966 g_string_append_printf (s, "b");
7968 case MONO_TYPE_VOID:
7969 g_string_append_printf (s, "void_");
7972 g_string_append_printf (s, "i1");
7975 g_string_append_printf (s, "u1");
7978 g_string_append_printf (s, "i2");
7981 g_string_append_printf (s, "u2");
7984 g_string_append_printf (s, "i4");
7987 g_string_append_printf (s, "u4");
7990 g_string_append_printf (s, "i8");
7993 g_string_append_printf (s, "u8");
7996 g_string_append_printf (s, "ii");
7999 g_string_append_printf (s, "ui");
8002 g_string_append_printf (s, "fl");
8005 g_string_append_printf (s, "do");
8008 char *fullname = mono_type_full_name (t);
8014 * Have to create a mangled name which is:
8018 temp = g_string_new ("");
8019 len = strlen (fullname);
8020 for (i = 0; i < len; ++i) {
8021 char c = fullname [i];
8023 g_string_append_c (temp, c);
8024 } else if (c == '_') {
8025 g_string_append_c (temp, '_');
8026 g_string_append_c (temp, '_');
8028 g_string_append_c (temp, '_');
8029 g_string_append_printf (temp, "%x", (int)c);
8032 temps = g_string_free (temp, FALSE);
8033 /* Include the length to avoid different length type names aliasing each other */
8034 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8043 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8048 supported = append_mangled_type (s, sig->ret);
8052 g_string_append_printf (s, "this_");
8053 for (i = 0; i < sig->param_count; ++i) {
8054 supported = append_mangled_type (s, sig->params [i]);
8063 * mono_aot_get_mangled_method_name:
8065 * Return a unique mangled name for METHOD, or NULL.
8068 mono_aot_get_mangled_method_name (MonoMethod *method)
8074 // FIXME: Add more cases
8075 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8077 info = mono_marshal_get_wrapper_info (method);
8078 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8081 s = g_string_new ("");
8083 g_string_append_printf (s, "aot_method_w_");
8085 switch (info->subtype) {
8086 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8087 g_string_append_printf (s, "gsharedvt_in_");
8089 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8090 g_string_append_printf (s, "gsharedvt_out_");
8093 g_assert_not_reached ();
8097 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8099 g_string_free (s, TRUE);
8103 return g_string_free (s, FALSE);
8107 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8109 return is_direct_callable (llvm_acfg, NULL, patch_info);
8113 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8115 MonoPltEntry *plt_entry;
8117 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8118 plt_entry->llvm_used = FALSE;
8122 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8124 const char *sym = NULL;
8126 if (llvm_acfg->aot_opts.direct_icalls) {
8127 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8128 /* Call to a C function implementing a jit icall */
8129 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8130 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8131 MonoMethod *method = (MonoMethod *)data;
8132 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8133 sym = mono_lookup_icall_symbol (method);
8134 else if (llvm_acfg->aot_opts.direct_pinvoke)
8135 sym = get_pinvoke_import (llvm_acfg, method);
8138 return g_strdup (sym);
8144 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8146 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8147 MonoPltEntry *plt_entry;
8148 const char *sym = NULL;
8151 ji->data.target = data;
8153 if (!can_encode_patch (llvm_acfg, ji))
8156 if (llvm_acfg->aot_opts.direct_icalls) {
8157 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8158 /* Call to a C function implementing a jit icall */
8159 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8160 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8161 MonoMethod *method = (MonoMethod *)data;
8162 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8163 sym = mono_lookup_icall_symbol (method);
8166 return g_strdup (sym);
8169 plt_entry = get_plt_entry (llvm_acfg, ji);
8170 plt_entry->llvm_used = TRUE;
8172 #if defined(TARGET_MACH)
8173 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8175 return g_strdup_printf (plt_entry->llvm_symbol);
8180 mono_aot_get_method_index (MonoMethod *method)
8182 g_assert (llvm_acfg);
8183 return get_method_index (llvm_acfg, method);
8187 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8191 mono_acfg_lock (llvm_acfg);
8192 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8193 mono_acfg_unlock (llvm_acfg);
8199 execute_system (const char * command)
8203 #if defined(HOST_WIN32) && defined(HAVE_SYSTEM)
8204 // We need an extra set of quotes around the whole command to properly handle commands
8205 // with spaces since internally the command is called through "cmd /c.
8206 char * quoted_command = g_strdup_printf ("\"%s\"", command);
8208 int size = MultiByteToWideChar (CP_UTF8, 0 , quoted_command , -1, NULL , 0);
8209 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8210 MultiByteToWideChar (CP_UTF8, 0, quoted_command, -1, wstr , size);
8211 status = _wsystem (wstr);
8214 g_free (quoted_command);
8215 #elif defined (HAVE_SYSTEM)
8216 status = system (command);
8218 g_assert_not_reached ();
8229 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8233 emit_llvm_file (MonoAotCompile *acfg)
8235 char *command, *opts, *tempbc, *optbc, *output_fname;
8237 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8238 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8239 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8241 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8242 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8245 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8248 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8249 * a lot of time, and doesn't seem to save much space.
8250 * The following optimizations cannot be enabled:
8252 * - 'jump-threading' changes our blockaddress references to int constants.
8253 * - 'basiccg' fails because it contains:
8254 * if (CS && !isa<IntrinsicInst>(II)) {
8255 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8256 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8257 * The opt list below was produced by taking the output of:
8258 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8259 * then removing tailcallelim + the global opts.
8260 * strip-dead-prototypes deletes unused intrinsics definitions.
8262 /* The dse pass is disabled because of #13734 and #17616 */
8264 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8265 * // If we have no DataLayout information around, then the size of the store
8266 * // is inferrable from the pointee type. If they are the same type, then
8267 * // we know that the store is safe.
8268 * if (AA.getDataLayout() == 0 &&
8269 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8270 * return OverwriteComplete;
8271 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8273 if (acfg->aot_opts.llvm_only)
8274 // FIXME: This doesn't work yet
8275 opts = g_strdup ("");
8277 #if LLVM_API_VERSION > 100
8278 opts = g_strdup ("-O2 -disable-tail-calls");
8280 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");
8282 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8283 aot_printf (acfg, "Executing opt: %s\n", command);
8284 if (execute_system (command) != 0)
8288 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8289 /* Nothing else to do */
8292 if (acfg->aot_opts.llvm_only) {
8293 /* Use the stock clang from xcode */
8295 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);
8297 aot_printf (acfg, "Executing clang: %s\n", command);
8298 if (execute_system (command) != 0)
8303 if (!acfg->llc_args)
8304 acfg->llc_args = g_string_new ("");
8306 /* Verbose asm slows down llc greatly */
8307 g_string_append (acfg->llc_args, " -asm-verbose=false");
8309 if (acfg->aot_opts.mtriple)
8310 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8312 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8314 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8316 #if LLVM_API_VERSION > 100
8317 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8320 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8321 /* ios requires PIC code now */
8322 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8324 if (llvm_acfg->aot_opts.static_link)
8325 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8327 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8330 if (acfg->llvm_owriter) {
8331 /* Emit an object file directly */
8332 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8333 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8335 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8337 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8338 g_free (output_fname);
8340 aot_printf (acfg, "Executing llc: %s\n", command);
8342 if (execute_system (command) != 0)
8349 emit_code (MonoAotCompile *acfg)
8351 int oindex, i, prev_index;
8352 gboolean saved_unbox_info = FALSE;
8353 char symbol [MAX_SYMBOL_SIZE];
8355 if (acfg->aot_opts.llvm_only)
8358 #if defined(TARGET_POWERPC64)
8359 sprintf (symbol, ".Lgot_addr");
8360 emit_section_change (acfg, ".text", 0);
8361 emit_alignment (acfg, 8);
8362 emit_label (acfg, symbol);
8363 emit_pointer (acfg, acfg->got_symbol);
8367 * This global symbol is used to compute the address of each method using the
8368 * code_offsets array. It is also used to compute the memory ranges occupied by
8369 * AOT code, so it must be equal to the address of the first emitted method.
8371 emit_section_change (acfg, ".text", 0);
8372 emit_alignment_code (acfg, 8);
8373 emit_info_symbol (acfg, "jit_code_start");
8376 * Emit some padding so the local symbol for the first method doesn't have the
8377 * same address as 'methods'.
8379 emit_padding (acfg, 16);
8381 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8385 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8387 cfg = acfg->cfgs [i];
8392 method = cfg->orig_method;
8394 /* Emit unbox trampoline */
8395 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8396 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8398 emit_section_change (acfg, ".text", 0);
8400 if (acfg->thumb_mixed && cfg->compile_llvm) {
8401 emit_set_thumb_mode (acfg);
8402 fprintf (acfg->fp, "\n.thumb_func\n");
8405 emit_label (acfg, symbol);
8407 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8409 if (acfg->thumb_mixed && cfg->compile_llvm)
8410 emit_set_arm_mode (acfg);
8412 if (!saved_unbox_info) {
8413 char user_symbol [128];
8415 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8417 emit_label (acfg, "ut_end");
8419 unwind_ops = mono_unwind_get_cie_program ();
8420 save_unwind_info (acfg, user_symbol, unwind_ops);
8421 mono_free_unwind_info (unwind_ops);
8423 /* Save the unbox trampoline size */
8424 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8426 saved_unbox_info = TRUE;
8430 if (cfg->compile_llvm)
8431 acfg->stats.llvm_count ++;
8433 emit_method_code (acfg, cfg);
8436 emit_section_change (acfg, ".text", 0);
8437 emit_alignment_code (acfg, 8);
8438 emit_info_symbol (acfg, "jit_code_end");
8440 /* To distinguish it from the next symbol */
8441 emit_padding (acfg, 4);
8444 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8445 * from optimizing them away, since it doesn't see that code_offsets references them.
8446 * JITted methods don't need this since they are referenced using assembler local
8448 * FIXME: This is why write-symbols doesn't work on OSX ?
8450 if (acfg->llvm && acfg->need_no_dead_strip) {
8451 fprintf (acfg->fp, "\n");
8452 for (i = 0; i < acfg->nmethods; ++i) {
8453 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8454 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8459 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8460 * This is PIE code, and the linker can update it if needed.
8463 sprintf (symbol, "method_addresses");
8464 emit_section_change (acfg, ".text", 1);
8465 emit_alignment_code (acfg, 8);
8466 emit_info_symbol (acfg, symbol);
8467 if (acfg->aot_opts.write_symbols)
8468 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8469 emit_unset_mode (acfg);
8470 if (acfg->need_no_dead_strip)
8471 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8473 for (i = 0; i < acfg->nmethods; ++i) {
8474 #ifdef MONO_ARCH_AOT_SUPPORTED
8477 if (acfg->cfgs [i]) {
8478 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8480 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8485 sprintf (symbol, "method_addresses_end");
8486 emit_label (acfg, symbol);
8489 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8490 sprintf (symbol, "unbox_trampolines");
8491 emit_section_change (acfg, RODATA_SECT, 0);
8492 emit_alignment (acfg, 8);
8493 emit_info_symbol (acfg, symbol);
8496 for (i = 0; i < acfg->nmethods; ++i) {
8501 cfg = acfg->cfgs [i];
8505 method = cfg->orig_method;
8507 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8508 index = get_method_index (acfg, method);
8510 emit_int32 (acfg, index);
8511 /* Make sure the table is sorted by index */
8512 g_assert (index > prev_index);
8516 sprintf (symbol, "unbox_trampolines_end");
8517 emit_info_symbol (acfg, symbol);
8518 emit_int32 (acfg, 0);
8520 /* Emit a separate table with the trampoline addresses/offsets */
8521 sprintf (symbol, "unbox_trampoline_addresses");
8522 emit_section_change (acfg, ".text", 0);
8523 emit_alignment_code (acfg, 8);
8524 emit_info_symbol (acfg, symbol);
8526 for (i = 0; i < acfg->nmethods; ++i) {
8531 cfg = acfg->cfgs [i];
8535 method = cfg->orig_method;
8537 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8538 #ifdef MONO_ARCH_AOT_SUPPORTED
8541 index = get_method_index (acfg, method);
8542 sprintf (symbol, "ut_%d", index);
8544 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8548 emit_int32 (acfg, 0);
8552 emit_info (MonoAotCompile *acfg)
8557 offsets = g_new0 (gint32, acfg->nmethods);
8559 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8560 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8562 if (acfg->cfgs [i]) {
8563 emit_method_info (acfg, acfg->cfgs [i]);
8564 offsets [i] = acfg->cfgs [i]->method_info_offset;
8570 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8575 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8577 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8578 #define mix(a,b,c) { \
8579 a -= c; a ^= rot(c, 4); c += b; \
8580 b -= a; b ^= rot(a, 6); a += c; \
8581 c -= b; c ^= rot(b, 8); b += a; \
8582 a -= c; a ^= rot(c,16); c += b; \
8583 b -= a; b ^= rot(a,19); a += c; \
8584 c -= b; c ^= rot(b, 4); b += a; \
8586 #define final(a,b,c) { \
8587 c ^= b; c -= rot(b,14); \
8588 a ^= c; a -= rot(c,11); \
8589 b ^= a; b -= rot(a,25); \
8590 c ^= b; c -= rot(b,16); \
8591 a ^= c; a -= rot(c,4); \
8592 b ^= a; b -= rot(a,14); \
8593 c ^= b; c -= rot(b,24); \
8597 mono_aot_type_hash (MonoType *t1)
8599 guint hash = t1->type;
8601 hash |= t1->byref << 6; /* do not collide with t1->type values */
8603 case MONO_TYPE_VALUETYPE:
8604 case MONO_TYPE_CLASS:
8605 case MONO_TYPE_SZARRAY:
8606 /* check if the distribution is good enough */
8607 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8609 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8610 case MONO_TYPE_ARRAY:
8611 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8612 case MONO_TYPE_GENERICINST:
8613 return ((hash << 5) - hash) ^ 0;
8620 * mono_aot_method_hash:
8622 * Return a hash code for methods which only depends on metadata.
8625 mono_aot_method_hash (MonoMethod *method)
8627 MonoMethodSignature *sig;
8631 guint32 *hashes_start, *hashes;
8633 MonoGenericInst *class_ginst = NULL;
8634 MonoGenericInst *ginst = NULL;
8636 /* Similar to the hash in mono_method_get_imt_slot () */
8638 sig = mono_method_signature (method);
8640 if (mono_class_is_ginst (method->klass))
8641 class_ginst = mono_class_get_generic_class (method->klass)->context.class_inst;
8642 if (method->is_inflated)
8643 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8645 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8646 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8647 hashes = hashes_start;
8649 /* Some wrappers are assigned to random classes */
8650 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8651 klass = method->klass;
8653 klass = mono_defaults.object_class;
8655 if (!method->wrapper_type) {
8658 if (mono_class_is_ginst (klass))
8659 full_name = mono_type_full_name (&mono_class_get_generic_class (klass)->container_class->byval_arg);
8661 full_name = mono_type_full_name (&klass->byval_arg);
8663 hashes [0] = mono_metadata_str_hash (full_name);
8667 hashes [0] = mono_metadata_str_hash (klass->name);
8668 hashes [1] = mono_metadata_str_hash (klass->name_space);
8670 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8671 /* The method name includes a stringified pointer */
8674 hashes [2] = mono_metadata_str_hash (method->name);
8675 hashes [3] = method->wrapper_type;
8676 hashes [4] = mono_aot_type_hash (sig->ret);
8678 for (i = 0; i < sig->param_count; i++) {
8679 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8682 for (i = 0; i < class_ginst->type_argc; ++i)
8683 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8686 for (i = 0; i < ginst->type_argc; ++i)
8687 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8689 g_assert (hindex == hashes_count);
8691 /* Setup internal state */
8692 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8694 /* Handle most of the hashes */
8695 while (hashes_count > 3) {
8704 /* Handle the last 3 hashes (all the case statements fall through) */
8705 switch (hashes_count) {
8706 case 3 : c += hashes [2];
8707 case 2 : b += hashes [1];
8708 case 1 : a += hashes [0];
8710 case 0: /* nothing left to add */
8714 g_free (hashes_start);
8723 * mono_aot_get_array_helper_from_wrapper;
8725 * Get the helper method in Array called by an array wrapper method.
8728 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8732 MonoGenericContext ctx;
8733 MonoType *args [16];
8734 char *mname, *iname, *s, *s2, *helper_name = NULL;
8736 prefix = "System.Collections.Generic";
8737 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8738 s2 = strstr (s, "`1.");
8744 //printf ("X: %s %s\n", iname, mname);
8746 if (!strcmp (iname, "IList"))
8747 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8749 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8750 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8752 g_free (helper_name);
8755 if (m->is_generic) {
8757 memset (&ctx, 0, sizeof (ctx));
8758 args [0] = &method->klass->element_class->byval_arg;
8759 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8760 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8761 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8767 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8769 typedef struct HashEntry {
8770 guint32 key, value, index;
8771 struct HashEntry *next;
8775 * emit_extra_methods:
8777 * Emit methods which are not in the METHOD table, like wrappers.
8780 emit_extra_methods (MonoAotCompile *acfg)
8782 int i, table_size, buf_size;
8784 guint32 *info_offsets;
8787 HashEntry *entry, *new_entry;
8788 int nmethods, max_chain_length;
8791 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8793 /* Emit method info */
8795 for (i = 0; i < acfg->extra_methods->len; ++i) {
8796 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8797 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8803 p = buf = (guint8 *)g_malloc (buf_size);
8807 method = cfg->method_to_register;
8809 encode_method_ref (acfg, method, p, &p);
8811 g_assert ((p - buf) < buf_size);
8813 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8818 * Construct a chained hash table for mapping indexes in extra_method_info to
8821 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8822 table = g_ptr_array_sized_new (table_size);
8823 for (i = 0; i < table_size; ++i)
8824 g_ptr_array_add (table, NULL);
8825 chain_lengths = g_new0 (int, table_size);
8826 max_chain_length = 0;
8827 for (i = 0; i < acfg->extra_methods->len; ++i) {
8828 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8829 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8835 key = info_offsets [i];
8836 value = get_method_index (acfg, method);
8838 hash = mono_aot_method_hash (method) % table_size;
8839 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8841 chain_lengths [hash] ++;
8842 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8844 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8845 new_entry->key = key;
8846 new_entry->value = value;
8848 entry = (HashEntry *)g_ptr_array_index (table, hash);
8849 if (entry == NULL) {
8850 new_entry->index = hash;
8851 g_ptr_array_index (table, hash) = new_entry;
8854 entry = entry->next;
8856 entry->next = new_entry;
8857 new_entry->index = table->len;
8858 g_ptr_array_add (table, new_entry);
8861 g_free (chain_lengths);
8863 //printf ("MAX: %d\n", max_chain_length);
8865 buf_size = table->len * 12 + 4;
8866 p = buf = (guint8 *)g_malloc (buf_size);
8867 encode_int (table_size, p, &p);
8869 for (i = 0; i < table->len; ++i) {
8870 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8872 if (entry == NULL) {
8873 encode_int (0, p, &p);
8874 encode_int (0, p, &p);
8875 encode_int (0, p, &p);
8877 //g_assert (entry->key > 0);
8878 encode_int (entry->key, p, &p);
8879 encode_int (entry->value, p, &p);
8881 encode_int (entry->next->index, p, &p);
8883 encode_int (0, p, &p);
8886 g_assert (p - buf <= buf_size);
8888 /* Emit the table */
8889 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8894 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8895 * This is used by mono_aot_find_jit_info ().
8897 buf_size = acfg->extra_methods->len * 8 + 4;
8898 p = buf = (guint8 *)g_malloc (buf_size);
8899 encode_int (acfg->extra_methods->len, p, &p);
8900 for (i = 0; i < acfg->extra_methods->len; ++i) {
8901 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8903 encode_int (get_method_index (acfg, method), p, &p);
8904 encode_int (info_offsets [i], p, &p);
8906 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8909 g_free (info_offsets);
8910 g_ptr_array_free (table, TRUE);
8914 generate_aotid (guint8* aotid)
8916 gpointer rand_handle;
8920 rand_handle = mono_rand_init (NULL, 0);
8922 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8923 mono_error_assert_ok (&error);
8925 mono_rand_close (rand_handle);
8929 emit_exception_info (MonoAotCompile *acfg)
8933 SeqPointData sp_data;
8934 gboolean seq_points_to_file = FALSE;
8936 offsets = g_new0 (gint32, acfg->nmethods);
8937 for (i = 0; i < acfg->nmethods; ++i) {
8938 if (acfg->cfgs [i]) {
8939 MonoCompile *cfg = acfg->cfgs [i];
8941 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8942 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8943 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8944 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8945 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8947 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8948 offsets [i] = cfg->ex_info_offset;
8950 if (method_seq_points_to_file) {
8951 if (!seq_points_to_file) {
8952 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8953 seq_points_to_file = TRUE;
8955 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8962 if (seq_points_to_file) {
8963 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8964 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8965 char *image_basename = g_path_get_basename (acfg->image->name);
8966 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8967 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8969 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8970 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8974 mono_seq_point_data_write (&sp_data, aot_file_path);
8975 mono_seq_point_data_free (&sp_data);
8979 g_free (image_basename);
8981 g_free (aot_file_path);
8984 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8989 emit_unwind_info (MonoAotCompile *acfg)
8994 if (acfg->aot_opts.llvm_only) {
8995 g_assert (acfg->unwind_ops->len == 0);
9000 * The unwind info contains a lot of duplicates so we emit each unique
9001 * entry once, and only store the offset from the start of the table in the
9005 sprintf (symbol, "unwind_info");
9006 emit_section_change (acfg, RODATA_SECT, 1);
9007 emit_alignment (acfg, 8);
9008 emit_info_symbol (acfg, symbol);
9010 for (i = 0; i < acfg->unwind_ops->len; ++i) {
9011 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
9012 guint8 *unwind_info;
9013 guint32 unwind_info_len;
9017 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9020 encode_value (unwind_info_len, p, &p);
9021 emit_bytes (acfg, buf, p - buf);
9022 emit_bytes (acfg, unwind_info, unwind_info_len);
9024 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9029 emit_class_info (MonoAotCompile *acfg)
9034 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9035 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9036 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9038 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);
9042 typedef struct ClassNameTableEntry {
9043 guint32 token, index;
9044 struct ClassNameTableEntry *next;
9045 } ClassNameTableEntry;
9048 emit_class_name_table (MonoAotCompile *acfg)
9050 int i, table_size, buf_size;
9051 guint32 token, hash;
9056 ClassNameTableEntry *entry, *new_entry;
9059 * Construct a chained hash table for mapping class names to typedef tokens.
9061 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9062 table = g_ptr_array_sized_new (table_size);
9063 for (i = 0; i < table_size; ++i)
9064 g_ptr_array_add (table, NULL);
9065 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9067 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9068 klass = mono_class_get_checked (acfg->image, token, &error);
9070 mono_error_cleanup (&error);
9073 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9074 hash = mono_metadata_str_hash (full_name) % table_size;
9077 /* FIXME: Allocate from the mempool */
9078 new_entry = g_new0 (ClassNameTableEntry, 1);
9079 new_entry->token = token;
9081 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9082 if (entry == NULL) {
9083 new_entry->index = hash;
9084 g_ptr_array_index (table, hash) = new_entry;
9087 entry = entry->next;
9089 entry->next = new_entry;
9090 new_entry->index = table->len;
9091 g_ptr_array_add (table, new_entry);
9095 /* Emit the table */
9096 buf_size = table->len * 4 + 4;
9097 p = buf = (guint8 *)g_malloc0 (buf_size);
9099 /* FIXME: Optimize memory usage */
9100 g_assert (table_size < 65000);
9101 encode_int16 (table_size, p, &p);
9102 g_assert (table->len < 65000);
9103 for (i = 0; i < table->len; ++i) {
9104 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9106 if (entry == NULL) {
9107 encode_int16 (0, p, &p);
9108 encode_int16 (0, p, &p);
9110 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9112 encode_int16 (entry->next->index, p, &p);
9114 encode_int16 (0, p, &p);
9118 g_assert (p - buf <= buf_size);
9119 g_ptr_array_free (table, TRUE);
9121 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9127 emit_image_table (MonoAotCompile *acfg)
9133 * The image table is small but referenced in a lot of places.
9134 * So we emit it at once, and reference its elements by an index.
9136 buf_size = acfg->image_table->len * 28 + 4;
9137 for (i = 0; i < acfg->image_table->len; i++) {
9138 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9139 MonoAssemblyName *aname = &image->assembly->aname;
9141 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9144 buf = p = (guint8 *)g_malloc0 (buf_size);
9145 encode_int (acfg->image_table->len, p, &p);
9146 for (i = 0; i < acfg->image_table->len; i++) {
9147 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9148 MonoAssemblyName *aname = &image->assembly->aname;
9150 /* FIXME: Support multi-module assemblies */
9151 g_assert (image->assembly->image == image);
9153 encode_string (image->assembly_name, p, &p);
9154 encode_string (image->guid, p, &p);
9155 encode_string (aname->culture ? aname->culture : "", p, &p);
9156 encode_string ((const char*)aname->public_key_token, p, &p);
9158 while (GPOINTER_TO_UINT (p) % 8 != 0)
9161 encode_int (aname->flags, p, &p);
9162 encode_int (aname->major, p, &p);
9163 encode_int (aname->minor, p, &p);
9164 encode_int (aname->build, p, &p);
9165 encode_int (aname->revision, p, &p);
9167 g_assert (p - buf <= buf_size);
9169 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9175 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9177 int i, first_plt_got_patch = 0, buf_size;
9179 guint32 *got_info_offsets;
9180 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9182 /* Add the patches needed by the PLT to the GOT */
9184 acfg->plt_got_offset_base = acfg->got_offset;
9185 first_plt_got_patch = info->got_patches->len;
9186 for (i = 1; i < acfg->plt_offset; ++i) {
9187 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9189 g_ptr_array_add (info->got_patches, plt_entry->ji);
9191 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9194 acfg->got_offset += acfg->plt_offset;
9199 * - optimize offsets table.
9200 * - reduce number of exported symbols.
9201 * - emit info for a klass only once.
9202 * - determine when a method uses a GOT slot which is guaranteed to be already
9204 * - clean up and document the code.
9205 * - use String.Empty in class libs.
9208 /* Encode info required to decode shared GOT entries */
9209 buf_size = info->got_patches->len * 128;
9210 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9211 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9213 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9215 if (acfg->plt_offset)
9216 acfg->plt_got_info_offsets [0] = 0;
9218 for (i = 0; i < info->got_patches->len; ++i) {
9219 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9224 encode_value (ji->type, p, &p);
9226 encode_patch (acfg, ji, p, &p);
9227 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9228 g_assert (p - buf <= buf_size);
9229 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9231 if (!llvm && i >= first_plt_got_patch)
9232 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9233 acfg->stats.got_info_size += p - buf;
9236 /* Emit got_info_offsets table */
9238 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9239 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);
9243 emit_got (MonoAotCompile *acfg)
9245 char symbol [MAX_SYMBOL_SIZE];
9247 if (acfg->aot_opts.llvm_only)
9250 /* Don't make GOT global so accesses to it don't need relocations */
9251 sprintf (symbol, "%s", acfg->got_symbol);
9254 emit_unset_mode (acfg);
9255 fprintf (acfg->fp, ".section __DATA, __bss\n");
9256 emit_alignment (acfg, 8);
9258 emit_info_symbol (acfg, "jit_got");
9259 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9261 emit_section_change (acfg, ".bss", 0);
9262 emit_alignment (acfg, 8);
9263 if (acfg->aot_opts.write_symbols)
9264 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9265 emit_label (acfg, symbol);
9267 emit_info_symbol (acfg, "jit_got");
9268 if (acfg->got_offset > 0)
9269 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9272 sprintf (symbol, "got_end");
9273 emit_label (acfg, symbol);
9276 typedef struct GlobalsTableEntry {
9277 guint32 value, index;
9278 struct GlobalsTableEntry *next;
9279 } GlobalsTableEntry;
9281 #ifdef TARGET_WIN32_MSVC
9282 #define DLL_ENTRY_POINT "DllMain"
9285 emit_library_info (MonoAotCompile *acfg)
9287 // Only include for shared libraries linked directly from generated object.
9288 if (link_shared_library (acfg)) {
9290 char symbol [MAX_SYMBOL_SIZE];
9292 // Ask linker to export all global symbols.
9293 emit_section_change (acfg, ".drectve", 0);
9294 for (guint i = 0; i < acfg->globals->len; ++i) {
9295 name = (char *)g_ptr_array_index (acfg->globals, i);
9296 g_assert (name != NULL);
9297 sprintf_s (symbol, MAX_SYMBOL_SIZE, " /EXPORT:%s", name);
9298 emit_string (acfg, symbol);
9301 // Emit DLLMain function, needed by MSVC linker for DLL's.
9302 // NOTE, DllMain should not go into exports above.
9303 emit_section_change (acfg, ".text", 0);
9304 emit_global (acfg, DLL_ENTRY_POINT, TRUE);
9305 emit_label (acfg, DLL_ENTRY_POINT);
9307 // Simple implementation of DLLMain, just returning TRUE.
9308 // For more information about DLLMain: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx
9309 fprintf (acfg->fp, "movl $1, %%eax\n");
9310 fprintf (acfg->fp, "ret\n");
9312 // Inform linker about our dll entry function.
9313 emit_section_change (acfg, ".drectve", 0);
9314 emit_string (acfg, "/ENTRY:" DLL_ENTRY_POINT);
9322 emit_library_info (MonoAotCompile *acfg)
9329 emit_globals (MonoAotCompile *acfg)
9335 GlobalsTableEntry *entry, *new_entry;
9337 if (!acfg->aot_opts.static_link)
9340 if (acfg->aot_opts.llvm_only) {
9341 g_assert (acfg->globals->len == 0);
9346 * When static linking, we emit a table containing our globals.
9350 * Construct a chained hash table for mapping global names to their index in
9351 * the globals table.
9353 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9354 table = g_ptr_array_sized_new (table_size);
9355 for (i = 0; i < table_size; ++i)
9356 g_ptr_array_add (table, NULL);
9357 for (i = 0; i < acfg->globals->len; ++i) {
9358 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9360 hash = mono_metadata_str_hash (name) % table_size;
9362 /* FIXME: Allocate from the mempool */
9363 new_entry = g_new0 (GlobalsTableEntry, 1);
9364 new_entry->value = i;
9366 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9367 if (entry == NULL) {
9368 new_entry->index = hash;
9369 g_ptr_array_index (table, hash) = new_entry;
9372 entry = entry->next;
9374 entry->next = new_entry;
9375 new_entry->index = table->len;
9376 g_ptr_array_add (table, new_entry);
9380 /* Emit the table */
9381 sprintf (symbol, ".Lglobals_hash");
9382 emit_section_change (acfg, RODATA_SECT, 0);
9383 emit_alignment (acfg, 8);
9384 emit_label (acfg, symbol);
9386 /* FIXME: Optimize memory usage */
9387 g_assert (table_size < 65000);
9388 emit_int16 (acfg, table_size);
9389 for (i = 0; i < table->len; ++i) {
9390 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9392 if (entry == NULL) {
9393 emit_int16 (acfg, 0);
9394 emit_int16 (acfg, 0);
9396 emit_int16 (acfg, entry->value + 1);
9398 emit_int16 (acfg, entry->next->index);
9400 emit_int16 (acfg, 0);
9404 /* Emit the names */
9405 for (i = 0; i < acfg->globals->len; ++i) {
9406 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9408 sprintf (symbol, "name_%d", i);
9409 emit_section_change (acfg, RODATA_SECT, 1);
9411 emit_alignment (acfg, 4);
9413 emit_label (acfg, symbol);
9414 emit_string (acfg, name);
9417 /* Emit the globals table */
9418 sprintf (symbol, "globals");
9419 emit_section_change (acfg, ".data", 0);
9420 /* This is not a global, since it is accessed by the init function */
9421 emit_alignment (acfg, 8);
9422 emit_info_symbol (acfg, symbol);
9424 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9425 emit_pointer (acfg, symbol);
9427 for (i = 0; i < acfg->globals->len; ++i) {
9428 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9430 sprintf (symbol, "name_%d", i);
9431 emit_pointer (acfg, symbol);
9433 g_assert (strlen (name) < sizeof (symbol));
9434 sprintf (symbol, "%s", name);
9435 emit_pointer (acfg, symbol);
9437 /* Null terminate the table */
9438 emit_int32 (acfg, 0);
9439 emit_int32 (acfg, 0);
9443 emit_mem_end (MonoAotCompile *acfg)
9447 if (acfg->aot_opts.llvm_only)
9450 sprintf (symbol, "mem_end");
9451 emit_section_change (acfg, ".text", 1);
9452 emit_alignment_code (acfg, 8);
9453 emit_label (acfg, symbol);
9457 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9461 info->version = MONO_AOT_FILE_VERSION;
9462 info->plt_got_offset_base = acfg->plt_got_offset_base;
9463 info->got_size = acfg->got_offset * sizeof (gpointer);
9464 info->plt_size = acfg->plt_offset;
9465 info->nmethods = acfg->nmethods;
9466 info->flags = acfg->flags;
9467 info->opts = acfg->opts;
9468 info->simd_opts = acfg->simd_opts;
9469 info->gc_name_index = acfg->gc_name_offset;
9470 info->datafile_size = acfg->datafile_offset;
9471 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9472 info->table_offsets [i] = acfg->table_offsets [i];
9473 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9474 info->num_trampolines [i] = acfg->num_trampolines [i];
9475 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9476 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9477 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9478 info->trampoline_size [i] = acfg->trampoline_size [i];
9479 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9481 info->double_align = MONO_ABI_ALIGNOF (double);
9482 info->long_align = MONO_ABI_ALIGNOF (gint64);
9483 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9484 info->tramp_page_size = acfg->tramp_page_size;
9485 info->nshared_got_entries = acfg->nshared_got_entries;
9486 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9487 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9489 memcpy(&info->aotid, acfg->image->aotid, 16);
9493 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9495 char symbol [MAX_SYMBOL_SIZE];
9497 const char **symbols;
9499 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9501 symbols [sindex ++] = acfg->got_symbol;
9503 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9504 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9506 symbols [sindex ++] = NULL;
9507 symbols [sindex ++] = NULL;
9509 /* llvm_get_method */
9510 symbols [sindex ++] = NULL;
9511 /* llvm_get_unbox_tramp */
9512 symbols [sindex ++] = NULL;
9513 if (!acfg->aot_opts.llvm_only) {
9514 symbols [sindex ++] = "jit_code_start";
9515 symbols [sindex ++] = "jit_code_end";
9516 symbols [sindex ++] = "method_addresses";
9518 symbols [sindex ++] = NULL;
9519 symbols [sindex ++] = NULL;
9520 symbols [sindex ++] = NULL;
9522 if (acfg->data_outfile) {
9523 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9524 symbols [sindex ++] = NULL;
9526 symbols [sindex ++] = "blob";
9527 symbols [sindex ++] = "class_name_table";
9528 symbols [sindex ++] = "class_info_offsets";
9529 symbols [sindex ++] = "method_info_offsets";
9530 symbols [sindex ++] = "ex_info_offsets";
9531 symbols [sindex ++] = "extra_method_info_offsets";
9532 symbols [sindex ++] = "extra_method_table";
9533 symbols [sindex ++] = "got_info_offsets";
9535 symbols [sindex ++] = "llvm_got_info_offsets";
9537 symbols [sindex ++] = NULL;
9538 symbols [sindex ++] = "image_table";
9540 symbols [sindex ++] = "mem_end";
9541 symbols [sindex ++] = "assembly_guid";
9542 symbols [sindex ++] = "runtime_version";
9543 if (acfg->num_trampoline_got_entries) {
9544 symbols [sindex ++] = "specific_trampolines";
9545 symbols [sindex ++] = "static_rgctx_trampolines";
9546 symbols [sindex ++] = "imt_trampolines";
9547 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9549 symbols [sindex ++] = NULL;
9550 symbols [sindex ++] = NULL;
9551 symbols [sindex ++] = NULL;
9552 symbols [sindex ++] = NULL;
9554 if (acfg->aot_opts.static_link) {
9555 symbols [sindex ++] = "globals";
9557 symbols [sindex ++] = NULL;
9559 symbols [sindex ++] = "assembly_name";
9560 symbols [sindex ++] = "plt";
9561 symbols [sindex ++] = "plt_end";
9562 symbols [sindex ++] = "unwind_info";
9563 if (!acfg->aot_opts.llvm_only) {
9564 symbols [sindex ++] = "unbox_trampolines";
9565 symbols [sindex ++] = "unbox_trampolines_end";
9566 symbols [sindex ++] = "unbox_trampoline_addresses";
9568 symbols [sindex ++] = NULL;
9569 symbols [sindex ++] = NULL;
9570 symbols [sindex ++] = NULL;
9573 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9575 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9576 emit_section_change (acfg, ".data", 0);
9577 emit_alignment (acfg, 8);
9578 emit_label (acfg, symbol);
9579 if (!acfg->aot_opts.static_link)
9580 emit_global (acfg, symbol, FALSE);
9582 /* The data emitted here must match MonoAotFileInfo. */
9584 emit_int32 (acfg, info->version);
9585 emit_int32 (acfg, info->dummy);
9588 * We emit pointers to our data structures instead of emitting global symbols which
9589 * point to them, to reduce the number of globals, and because using globals leads to
9590 * various problems (i.e. arm/thumb).
9592 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9593 emit_pointer (acfg, symbols [i]);
9595 emit_int32 (acfg, info->plt_got_offset_base);
9596 emit_int32 (acfg, info->got_size);
9597 emit_int32 (acfg, info->plt_size);
9598 emit_int32 (acfg, info->nmethods);
9599 emit_int32 (acfg, info->flags);
9600 emit_int32 (acfg, info->opts);
9601 emit_int32 (acfg, info->simd_opts);
9602 emit_int32 (acfg, info->gc_name_index);
9603 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9604 emit_int32 (acfg, info->double_align);
9605 emit_int32 (acfg, info->long_align);
9606 emit_int32 (acfg, info->generic_tramp_num);
9607 emit_int32 (acfg, info->tramp_page_size);
9608 emit_int32 (acfg, info->nshared_got_entries);
9609 emit_int32 (acfg, info->datafile_size);
9611 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9612 emit_int32 (acfg, info->table_offsets [i]);
9613 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9614 emit_int32 (acfg, info->num_trampolines [i]);
9615 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9616 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9617 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9618 emit_int32 (acfg, info->trampoline_size [i]);
9619 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9620 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9622 emit_bytes (acfg, info->aotid, 16);
9624 if (acfg->aot_opts.static_link) {
9625 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9626 emit_alignment (acfg, sizeof (gpointer));
9627 emit_label (acfg, acfg->static_linking_symbol);
9628 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9633 * Emit a structure containing all the information not stored elsewhere.
9636 emit_file_info (MonoAotCompile *acfg)
9639 MonoAotFileInfo *info;
9641 if (acfg->aot_opts.bind_to_runtime_version) {
9642 build_info = mono_get_runtime_build_info ();
9643 emit_string_symbol (acfg, "runtime_version", build_info);
9644 g_free (build_info);
9646 emit_string_symbol (acfg, "runtime_version", "");
9649 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9651 /* Emit a string holding the assembly name */
9652 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9654 info = g_new0 (MonoAotFileInfo, 1);
9655 init_aot_file_info (acfg, info);
9657 if (acfg->aot_opts.static_link) {
9658 char symbol [MAX_SYMBOL_SIZE];
9662 * Emit a global symbol which can be passed by an embedding app to
9663 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9666 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9668 /* Get rid of characters which cannot occur in symbols */
9670 for (p = symbol; *p; ++p) {
9671 if (!(isalnum (*p) || *p == '_'))
9674 acfg->static_linking_symbol = g_strdup (symbol);
9678 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9680 emit_aot_file_info (acfg, info);
9684 emit_blob (MonoAotCompile *acfg)
9686 acfg->blob_closed = TRUE;
9688 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9692 emit_objc_selectors (MonoAotCompile *acfg)
9697 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9702 * cat > foo.m << EOF
9705 * return @selector(print:);
9710 mono_img_writer_emit_unset_mode (acfg->w);
9711 g_assert (acfg->fp);
9712 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9713 fprintf (acfg->fp, ".align 3\n");
9714 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9715 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9716 emit_label (acfg, symbol);
9717 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9718 emit_pointer (acfg, symbol);
9721 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9722 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9723 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9724 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9727 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9728 fprintf (acfg->fp, ".align 3\n");
9729 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9730 fprintf (acfg->fp, ".long 0\n");
9731 fprintf (acfg->fp, ".long 16\n");
9735 emit_dwarf_info (MonoAotCompile *acfg)
9737 #ifdef EMIT_DWARF_INFO
9741 /* DIEs for methods */
9742 for (i = 0; i < acfg->nmethods; ++i) {
9743 MonoCompile *cfg = acfg->cfgs [i];
9748 // FIXME: LLVM doesn't define .Lme_...
9749 if (cfg->compile_llvm)
9752 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9754 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 ()));
9760 collect_methods (MonoAotCompile *acfg)
9763 MonoImage *image = acfg->image;
9765 /* Collect methods */
9766 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9769 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9771 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9774 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9775 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9776 mono_error_cleanup (&error);
9780 /* Load all methods eagerly to skip the slower lazy loading code */
9781 mono_class_setup_methods (method->klass);
9783 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9784 /* Compile the wrapper instead */
9785 /* We do this here instead of add_wrappers () because it is easy to do it here */
9786 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9790 /* FIXME: Some mscorlib methods don't have debug info */
9792 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9793 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9794 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9795 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9796 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9797 if (!mono_debug_lookup_method (method)) {
9798 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9805 if (method->is_generic || mono_class_is_gtd (method->klass))
9806 /* Compile the ref shared version instead */
9807 method = mini_get_shared_method (method);
9809 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9810 add_method_with_index (acfg, method, i, FALSE);
9811 acfg->method_index ++;
9814 /* gsharedvt methods */
9815 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9818 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9820 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9823 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9824 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9826 if (method->is_generic || mono_class_is_gtd (method->klass)) {
9827 MonoMethod *gshared;
9829 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9830 add_extra_method (acfg, gshared);
9834 if (mono_aot_mode_is_full (&acfg->aot_opts))
9835 add_generic_instances (acfg);
9837 if (mono_aot_mode_is_full (&acfg->aot_opts))
9838 add_wrappers (acfg);
9843 compile_methods (MonoAotCompile *acfg)
9847 if (acfg->aot_opts.nthreads > 0) {
9851 MonoThreadHandle *thread_handle;
9852 gpointer *user_data;
9853 MonoMethod **methods;
9855 methods_len = acfg->methods->len;
9857 len = acfg->methods->len / acfg->aot_opts.nthreads;
9860 * Partition the list of methods into fragments, and hand it to threads to
9863 threads = g_ptr_array_new ();
9864 /* Make a copy since acfg->methods is modified by compile_method () */
9865 methods = g_new0 (MonoMethod*, methods_len);
9866 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9867 for (i = 0; i < methods_len; ++i)
9868 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9870 while (i < methods_len) {
9872 MonoInternalThread *thread;
9874 frag = g_ptr_array_new ();
9875 for (j = 0; j < len; ++j) {
9876 if (i < methods_len) {
9877 g_ptr_array_add (frag, methods [i]);
9882 user_data = g_new0 (gpointer, 3);
9883 user_data [0] = acfg;
9884 user_data [1] = frag;
9886 thread = mono_thread_create_internal (mono_domain_get (), compile_thread_main, (gpointer) user_data, MONO_THREAD_CREATE_FLAGS_NONE, &error);
9887 mono_error_assert_ok (&error);
9889 thread_handle = mono_threads_open_thread_handle (thread->handle);
9890 g_ptr_array_add (threads, thread_handle);
9894 for (i = 0; i < threads->len; ++i) {
9895 mono_thread_info_wait_one_handle (g_ptr_array_index (threads, i), MONO_INFINITE_WAIT, FALSE);
9896 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9902 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9903 for (i = methods_len; i < acfg->methods->len; ++i) {
9904 /* This can add new methods to acfg->methods */
9905 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9910 compile_asm (MonoAotCompile *acfg)
9912 char *command, *objfile;
9913 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9914 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9915 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9917 #ifdef TARGET_WIN32_MSVC
9918 #define AS_OPTIONS "-c -x assembler"
9919 #elif defined(TARGET_AMD64) && !defined(TARGET_MACH)
9920 #define AS_OPTIONS "--64"
9921 #elif defined(TARGET_POWERPC64)
9922 #define AS_OPTIONS "-a64 -mppc64"
9923 #elif defined(sparc) && SIZEOF_VOID_P == 8
9924 #define AS_OPTIONS "-xarch=v9"
9925 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9926 #define AS_OPTIONS "-arch i386"
9928 #define AS_OPTIONS ""
9931 #ifdef __native_client_codegen__
9932 #if defined(TARGET_AMD64)
9933 #define AS_NAME "nacl64-as"
9935 #define AS_NAME "nacl-as"
9937 #elif defined(TARGET_OSX)
9938 #define AS_NAME "clang"
9939 #elif defined(TARGET_WIN32_MSVC)
9940 #define AS_NAME "clang.exe"
9942 #define AS_NAME "as"
9945 #ifdef TARGET_WIN32_MSVC
9946 #define AS_OBJECT_FILE_SUFFIX "obj"
9948 #define AS_OBJECT_FILE_SUFFIX "o"
9952 #define LD_NAME "ld"
9953 #define LD_OPTIONS "-shared -G"
9954 #elif defined(__ppc__) && defined(TARGET_MACH)
9955 #define LD_NAME "gcc"
9956 #define LD_OPTIONS "-dynamiclib"
9957 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9958 #define LD_NAME "clang"
9959 #define LD_OPTIONS "--shared"
9960 #elif defined(TARGET_WIN32_MSVC)
9961 #define LD_NAME "link.exe"
9962 #define LD_OPTIONS "/DLL /MACHINE:X64 /NOLOGO"
9963 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9964 #define LD_NAME "gcc"
9965 #define LD_OPTIONS "-shared"
9966 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9967 #define LD_NAME "clang"
9968 #define LD_OPTIONS "-m32 -dynamiclib"
9969 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9970 #define LD_NAME "gcc"
9971 #define LD_OPTIONS "--shared"
9972 #elif defined(TARGET_POWERPC64)
9973 #define LD_OPTIONS "-m elf64ppc"
9977 #define LD_OPTIONS ""
9980 if (acfg->aot_opts.asm_only) {
9981 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9982 if (acfg->aot_opts.static_link)
9983 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9985 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9989 if (acfg->aot_opts.static_link) {
9990 if (acfg->aot_opts.outfile)
9991 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9993 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->image->name);
9995 objfile = g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname);
9999 g_string_append (acfg->as_args, "-c -x assembler");
10002 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10003 acfg->as_args ? acfg->as_args->str : "",
10004 wrap_path (objfile), wrap_path (acfg->tmpfname));
10005 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10006 if (execute_system (command) != 0) {
10012 if (acfg->llvm && !acfg->llvm_owriter) {
10013 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
10014 acfg->as_args ? acfg->as_args->str : "",
10015 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
10016 aot_printf (acfg, "Executing the native assembler: %s\n", command);
10017 if (execute_system (command) != 0) {
10026 if (acfg->aot_opts.static_link) {
10027 aot_printf (acfg, "Output file: '%s'.\n", objfile);
10028 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
10033 if (acfg->aot_opts.outfile)
10034 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10036 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
10038 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
10041 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
10043 llvm_ofile = g_strdup ("");
10046 /* replace the ; flags separators with spaces */
10047 g_strdelimit (ld_flags, ";", ' ');
10049 if (acfg->aot_opts.llvm_only)
10050 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
10052 #ifdef TARGET_WIN32_MSVC
10053 g_assert (tmp_outfile_name != NULL);
10054 g_assert (objfile != NULL);
10055 command = g_strdup_printf ("\"%s%s\" %s %s /OUT:\"%s\" \"%s\"", tool_prefix, LD_NAME, LD_OPTIONS,
10056 ld_flags, tmp_outfile_name, objfile);
10057 #elif defined(LD_NAME)
10058 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
10059 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10060 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10063 if (acfg->aot_opts.tool_prefix) {
10064 /* Cross compiling */
10065 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
10066 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10067 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10069 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
10070 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
10071 wrap_path (g_strdup_printf ("%s." AS_OBJECT_FILE_SUFFIX, acfg->tmpfname)), ld_flags);
10073 if (acfg->aot_opts.llvm_only) {
10074 command = g_strdup_printf ("clang++ %s", args);
10076 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
10081 aot_printf (acfg, "Executing the native linker: %s\n", command);
10082 if (execute_system (command) != 0) {
10083 g_free (tmp_outfile_name);
10084 g_free (outfile_name);
10093 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10094 printf ("Stripping the binary: %s\n", com);
10095 execute_system (com);
10098 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10100 * gas generates 'mapping symbols' each time code and data is mixed, which
10101 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10103 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10104 aot_printf (acfg, "Stripping the binary: %s\n", command);
10105 if (execute_system (command) != 0) {
10106 g_free (tmp_outfile_name);
10107 g_free (outfile_name);
10114 if (0 != rename (tmp_outfile_name, outfile_name)) {
10115 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10116 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10117 unlink (outfile_name);
10118 rename (tmp_outfile_name, outfile_name);
10122 #if defined(TARGET_MACH)
10123 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10124 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10125 if (execute_system (command) != 0) {
10130 if (!acfg->aot_opts.save_temps)
10133 g_free (tmp_outfile_name);
10134 g_free (outfile_name);
10137 if (acfg->aot_opts.save_temps)
10138 aot_printf (acfg, "Retained input file.\n");
10140 unlink (acfg->tmpfname);
10146 profread_byte (FILE *infile)
10151 res = fread (&i, 1, 1, infile);
10152 g_assert (res == 1);
10157 profread_int (FILE *infile)
10161 res = fread (&i, 4, 1, infile);
10162 g_assert (res == 1);
10167 profread_string (FILE *infile)
10173 len = profread_int (infile);
10174 if (len + 1 > 1024)
10175 pbuf = g_malloc (len + 1);
10178 res = fread (pbuf, 1, len, infile);
10179 g_assert (res == len);
10182 return g_strdup (buf);
10188 load_profile_file (MonoAotCompile *acfg, char *filename)
10192 int res, len, version;
10195 infile = fopen (filename, "r");
10197 fprintf (stderr, "Unable to open file '%s': %s.\n", filename, strerror (errno));
10201 printf ("Using profile data file '%s'\n", filename);
10203 sprintf (magic, AOT_PROFILER_MAGIC);
10204 len = strlen (magic);
10205 res = fread (buf, 1, len, infile);
10206 magic [len] = '\0';
10208 if ((res != len) || strcmp (buf, magic) != 0) {
10209 printf ("Profile file has wrong header: '%s'.\n", buf);
10213 guint32 expected_version = (AOT_PROFILER_MAJOR_VERSION << 16) | AOT_PROFILER_MINOR_VERSION;
10214 version = profread_int (infile);
10215 if (version != expected_version) {
10216 printf ("Profile file has wrong version 0x%4x, expected 0x%4x.\n", version, expected_version);
10221 ProfileData *data = g_new0 (ProfileData, 1);
10222 data->images = g_hash_table_new (NULL, NULL);
10223 data->classes = g_hash_table_new (NULL, NULL);
10224 data->ginsts = g_hash_table_new (NULL, NULL);
10225 data->methods = g_hash_table_new (NULL, NULL);
10228 int type = profread_byte (infile);
10229 int id = profread_int (infile);
10231 if (type == AOTPROF_RECORD_NONE)
10235 case AOTPROF_RECORD_IMAGE: {
10236 ImageProfileData *idata = g_new0 (ImageProfileData, 1);
10237 idata->name = profread_string (infile);
10238 char *mvid = profread_string (infile);
10240 g_hash_table_insert (data->images, GINT_TO_POINTER (id), idata);
10243 case AOTPROF_RECORD_GINST: {
10245 int len = profread_int (infile);
10247 GInstProfileData *gdata = g_new0 (GInstProfileData, 1);
10249 gdata->argv = g_new0 (ClassProfileData*, len);
10251 for (i = 0; i < len; ++i) {
10252 int class_id = profread_int (infile);
10254 gdata->argv [i] = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10255 g_assert (gdata->argv [i]);
10257 g_hash_table_insert (data->ginsts, GINT_TO_POINTER (id), gdata);
10260 case AOTPROF_RECORD_TYPE: {
10261 int type = profread_byte (infile);
10264 case MONO_TYPE_CLASS: {
10265 int image_id = profread_int (infile);
10266 int ginst_id = profread_int (infile);
10267 char *class_name = profread_string (infile);
10269 ImageProfileData *image = g_hash_table_lookup (data->images, GINT_TO_POINTER (image_id));
10272 char *p = strrchr (class_name, '.');
10276 ClassProfileData *cdata = g_new0 (ClassProfileData, 1);
10277 cdata->image = image;
10278 cdata->ns = g_strdup (class_name);
10279 cdata->name = g_strdup (p + 1);
10281 if (ginst_id != -1) {
10282 cdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10283 g_assert (cdata->inst);
10285 g_free (class_name);
10287 g_hash_table_insert (data->classes, GINT_TO_POINTER (id), cdata);
10291 case MONO_TYPE_SZARRAY: {
10292 int elem_id = profread_int (infile);
10298 g_assert_not_reached ();
10303 case AOTPROF_RECORD_METHOD: {
10304 int class_id = profread_int (infile);
10305 int ginst_id = profread_int (infile);
10306 int param_count = profread_int (infile);
10307 char *method_name = profread_string (infile);
10308 char *sig = profread_string (infile);
10310 ClassProfileData *klass = g_hash_table_lookup (data->classes, GINT_TO_POINTER (class_id));
10313 MethodProfileData *mdata = g_new0 (MethodProfileData, 1);
10315 mdata->klass = klass;
10316 mdata->name = method_name;
10317 mdata->signature = sig;
10318 mdata->param_count = param_count;
10320 if (ginst_id != -1) {
10321 mdata->inst = g_hash_table_lookup (data->ginsts, GINT_TO_POINTER (ginst_id));
10322 g_assert (mdata->inst);
10324 g_hash_table_insert (data->methods, GINT_TO_POINTER (id), mdata);
10328 printf ("%d\n", type);
10329 g_assert_not_reached ();
10335 acfg->profile_data = g_list_append (acfg->profile_data, data);
10339 resolve_class (ClassProfileData *cdata);
10342 resolve_ginst (GInstProfileData *inst_data)
10346 if (inst_data->inst)
10349 for (i = 0; i < inst_data->argc; ++i) {
10350 resolve_class (inst_data->argv [i]);
10351 if (!inst_data->argv [i]->klass)
10354 MonoType **args = g_new0 (MonoType*, inst_data->argc);
10355 for (i = 0; i < inst_data->argc; ++i)
10356 args [i] = &inst_data->argv [i]->klass->byval_arg;
10358 inst_data->inst = mono_metadata_get_generic_inst (inst_data->argc, args);
10362 resolve_class (ClassProfileData *cdata)
10367 if (!cdata->image->image)
10370 klass = mono_class_from_name_checked (cdata->image->image, cdata->ns, cdata->name, &error);
10372 //printf ("[%s] %s.%s\n", cdata->image->name, cdata->ns, cdata->name);
10376 resolve_ginst (cdata->inst);
10377 if (!cdata->inst->inst)
10379 MonoGenericContext ctx;
10381 memset (&ctx, 0, sizeof (ctx));
10382 ctx.class_inst = cdata->inst->inst;
10383 cdata->klass = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
10385 cdata->klass = klass;
10390 * Resolve the profile data to the corresponding loaded classes/methods etc. if possible.
10393 resolve_profile_data (MonoAotCompile *acfg, ProfileData *data)
10395 GHashTableIter iter;
10396 gpointer key, value;
10403 GPtrArray *assemblies = mono_domain_get_assemblies (mono_get_root_domain (), FALSE);
10404 g_hash_table_iter_init (&iter, data->images);
10405 while (g_hash_table_iter_next (&iter, &key, &value)) {
10406 ImageProfileData *idata = (ImageProfileData*)value;
10408 for (i = 0; i < assemblies->len; ++i) {
10409 MonoAssembly *ass = g_ptr_array_index (assemblies, i);
10411 if (!strcmp (ass->aname.name, idata->name)) {
10412 idata->image = ass->image;
10417 g_ptr_array_free (assemblies, TRUE);
10420 g_hash_table_iter_init (&iter, data->classes);
10421 while (g_hash_table_iter_next (&iter, &key, &value)) {
10422 ClassProfileData *cdata = (ClassProfileData*)value;
10424 if (!cdata->image->image) {
10425 if (acfg->aot_opts.verbose)
10426 printf ("Unable to load class '%s.%s' because its image '%s' is not loaded.\n", cdata->ns, cdata->name, cdata->image->name);
10430 resolve_class (cdata);
10433 printf ("%s %s %s\n", cdata->ns, cdata->name, mono_class_full_name (cdata->klass));
10438 g_hash_table_iter_init (&iter, data->methods);
10439 while (g_hash_table_iter_next (&iter, &key, &value)) {
10440 MethodProfileData *mdata = (MethodProfileData*)value;
10445 resolve_class (mdata->klass);
10446 klass = mdata->klass->klass;
10448 if (acfg->aot_opts.verbose)
10449 printf ("Unable to load method '%s' because its class '%s.%s' is not loaded.\n", mdata->name, mdata->klass->ns, mdata->klass->name);
10453 while ((m = mono_class_get_methods (klass, &miter))) {
10456 if (strcmp (m->name, mdata->name))
10458 MonoMethodSignature *sig = mono_method_signature (m);
10461 if (sig->param_count != mdata->param_count)
10464 resolve_ginst (mdata->inst);
10465 if (!mdata->inst->inst)
10467 MonoGenericContext ctx;
10469 memset (&ctx, 0, sizeof (ctx));
10470 ctx.method_inst = mdata->inst->inst;
10472 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
10475 sig = mono_method_signature_checked (m, &error);
10476 if (!is_ok (&error)) {
10477 mono_error_cleanup (&error);
10481 char *sig_str = mono_signature_full_name (sig);
10482 gboolean match = !strcmp (sig_str, mdata->signature);
10487 //printf ("%s\n", mono_method_full_name (m, 1));
10491 if (!mdata->method) {
10492 if (acfg->aot_opts.verbose)
10493 printf ("Unable to load method '%s' from class '%s', not found.\n", mdata->name, mono_class_full_name (klass));
10499 inst_references_image (MonoGenericInst *inst, MonoImage *image)
10503 for (i = 0; i < inst->type_argc; ++i) {
10504 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10505 if (k->image == image)
10507 if (mono_class_is_ginst (k)) {
10508 MonoGenericInst *kinst = mono_class_get_context (k)->class_inst;
10509 if (inst_references_image (kinst, image))
10517 is_local_inst (MonoGenericInst *inst, MonoImage *image)
10521 for (i = 0; i < inst->type_argc; ++i) {
10522 MonoClass *k = mono_class_from_mono_type (inst->type_argv [i]);
10523 if (!MONO_TYPE_IS_PRIMITIVE (inst->type_argv [i]) && k->image != image)
10530 add_profile_instances (MonoAotCompile *acfg, ProfileData *data)
10532 GHashTableIter iter;
10533 gpointer key, value;
10539 if (acfg->aot_opts.profile_only) {
10540 /* Add methods referenced by the profile */
10541 g_hash_table_iter_init (&iter, data->methods);
10542 while (g_hash_table_iter_next (&iter, &key, &value)) {
10543 MethodProfileData *mdata = (MethodProfileData*)value;
10544 MonoMethod *m = mdata->method;
10548 if (m->is_inflated)
10550 add_extra_method (acfg, m);
10551 g_hash_table_insert (acfg->profile_methods, m, m);
10557 * Add method instances 'related' to this assembly to the AOT image.
10559 g_hash_table_iter_init (&iter, data->methods);
10560 while (g_hash_table_iter_next (&iter, &key, &value)) {
10561 MethodProfileData *mdata = (MethodProfileData*)value;
10562 MonoMethod *m = mdata->method;
10563 MonoGenericContext *ctx;
10567 if (!m->is_inflated)
10570 ctx = mono_method_get_context (m);
10571 /* For simplicity, add instances which reference the assembly we are compiling */
10572 if (((ctx->class_inst && inst_references_image (ctx->class_inst, acfg->image)) ||
10573 (ctx->method_inst && inst_references_image (ctx->method_inst, acfg->image))) &&
10574 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10575 //printf ("%s\n", mono_method_full_name (m, TRUE));
10576 add_extra_method (acfg, m);
10578 } else if (m->klass->image == acfg->image &&
10579 ((ctx->class_inst && is_local_inst (ctx->class_inst, acfg->image)) ||
10580 (ctx->method_inst && is_local_inst (ctx->method_inst, acfg->image))) &&
10581 !mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) {
10582 /* Add instances where the gtd is in the assembly and its inflated with types from this assembly or corlib */
10583 //printf ("%s\n", mono_method_full_name (m, TRUE));
10584 add_extra_method (acfg, m);
10588 * FIXME: We might skip some instances, for example:
10589 * Foo<Bar> won't be compiled when compiling Foo's assembly since it doesn't match the first case,
10590 * and it won't be compiled when compiling Bar's assembly if Foo's assembly is not loaded.
10594 printf ("Added %d methods from profile.\n", count);
10598 init_got_info (GotInfo *info)
10602 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10603 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10604 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10605 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10606 info->got_patches = g_ptr_array_new ();
10609 static MonoAotCompile*
10610 acfg_create (MonoAssembly *ass, guint32 opts)
10612 MonoImage *image = ass->image;
10613 MonoAotCompile *acfg;
10615 acfg = g_new0 (MonoAotCompile, 1);
10616 acfg->methods = g_ptr_array_new ();
10617 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10618 acfg->method_depth = g_hash_table_new (NULL, NULL);
10619 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10620 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10621 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10622 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10623 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10624 acfg->image_hash = g_hash_table_new (NULL, NULL);
10625 acfg->image_table = g_ptr_array_new ();
10626 acfg->globals = g_ptr_array_new ();
10627 acfg->image = image;
10629 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10630 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10631 acfg->mempool = mono_mempool_new ();
10632 acfg->extra_methods = g_ptr_array_new ();
10633 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10634 acfg->unwind_ops = g_ptr_array_new ();
10635 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10636 acfg->method_order = g_ptr_array_new ();
10637 acfg->export_names = g_hash_table_new (NULL, NULL);
10638 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10639 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10640 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10641 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10642 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10643 acfg->profile_methods = g_hash_table_new (NULL, NULL);
10644 mono_os_mutex_init_recursive (&acfg->mutex);
10646 init_got_info (&acfg->got_info);
10647 init_got_info (&acfg->llvm_got_info);
10653 got_info_free (GotInfo *info)
10657 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10658 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10659 g_free (info->patch_to_got_offset_by_type);
10660 g_hash_table_destroy (info->patch_to_got_offset);
10661 g_ptr_array_free (info->got_patches, TRUE);
10665 acfg_free (MonoAotCompile *acfg)
10669 mono_img_writer_destroy (acfg->w);
10670 for (i = 0; i < acfg->nmethods; ++i)
10671 if (acfg->cfgs [i])
10672 mono_destroy_compile (acfg->cfgs [i]);
10674 g_free (acfg->cfgs);
10676 g_free (acfg->static_linking_symbol);
10677 g_free (acfg->got_symbol);
10678 g_free (acfg->plt_symbol);
10679 g_ptr_array_free (acfg->methods, TRUE);
10680 g_ptr_array_free (acfg->image_table, TRUE);
10681 g_ptr_array_free (acfg->globals, TRUE);
10682 g_ptr_array_free (acfg->unwind_ops, TRUE);
10683 g_hash_table_destroy (acfg->method_indexes);
10684 g_hash_table_destroy (acfg->method_depth);
10685 g_hash_table_destroy (acfg->plt_offset_to_entry);
10686 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10687 if (acfg->patch_to_plt_entry [i])
10688 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10690 g_free (acfg->patch_to_plt_entry);
10691 g_hash_table_destroy (acfg->method_to_cfg);
10692 g_hash_table_destroy (acfg->token_info_hash);
10693 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10694 g_hash_table_destroy (acfg->image_hash);
10695 g_hash_table_destroy (acfg->unwind_info_offsets);
10696 g_hash_table_destroy (acfg->method_label_hash);
10697 if (acfg->typespec_classes)
10698 g_hash_table_destroy (acfg->typespec_classes);
10699 g_hash_table_destroy (acfg->export_names);
10700 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10701 g_hash_table_destroy (acfg->klass_blob_hash);
10702 g_hash_table_destroy (acfg->method_blob_hash);
10703 got_info_free (&acfg->got_info);
10704 got_info_free (&acfg->llvm_got_info);
10705 mono_mempool_destroy (acfg->mempool);
10709 #define WRAPPER(e,n) n,
10710 static const char* const
10711 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10712 #include "mono/metadata/wrapper-types.h"
10716 static G_GNUC_UNUSED const char*
10717 get_wrapper_type_name (int type)
10719 return wrapper_type_names [type];
10725 static void aot_dump (MonoAotCompile *acfg)
10731 mono_json_writer_init (&writer);
10733 mono_json_writer_object_begin(&writer);
10736 mono_json_writer_indent (&writer);
10737 mono_json_writer_object_key(&writer, "methods");
10738 mono_json_writer_array_begin (&writer);
10741 for (i = 0; i < acfg->nmethods; ++i) {
10743 MonoMethod *method;
10746 cfg = acfg->cfgs [i];
10750 method = cfg->orig_method;
10752 mono_json_writer_indent (&writer);
10753 mono_json_writer_object_begin(&writer);
10755 mono_json_writer_indent (&writer);
10756 mono_json_writer_object_key(&writer, "name");
10757 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10759 mono_json_writer_indent (&writer);
10760 mono_json_writer_object_key(&writer, "signature");
10761 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10763 mono_json_writer_indent (&writer);
10764 mono_json_writer_object_key(&writer, "code_size");
10765 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10767 klass = method->klass;
10769 mono_json_writer_indent (&writer);
10770 mono_json_writer_object_key(&writer, "class");
10771 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10773 mono_json_writer_indent (&writer);
10774 mono_json_writer_object_key(&writer, "namespace");
10775 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10777 mono_json_writer_indent (&writer);
10778 mono_json_writer_object_key(&writer, "wrapper_type");
10779 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10781 mono_json_writer_indent_pop (&writer);
10782 mono_json_writer_indent (&writer);
10783 mono_json_writer_object_end (&writer);
10784 mono_json_writer_printf (&writer, ",\n");
10787 mono_json_writer_indent_pop (&writer);
10788 mono_json_writer_indent (&writer);
10789 mono_json_writer_array_end (&writer);
10790 mono_json_writer_printf (&writer, ",\n");
10794 mono_json_writer_indent_push (&writer);
10795 mono_json_writer_indent (&writer);
10796 mono_json_writer_object_key(&writer, "plt");
10797 mono_json_writer_array_begin (&writer);
10799 for (i = 0; i < acfg->plt_offset; ++i) {
10800 MonoPltEntry *plt_entry = NULL;
10805 * The first plt entry is unused.
10809 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10810 ji = plt_entry->ji;
10812 mono_json_writer_indent (&writer);
10813 mono_json_writer_printf (&writer, "{ ");
10814 mono_json_writer_object_key(&writer, "symbol");
10815 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10818 mono_json_writer_indent_pop (&writer);
10819 mono_json_writer_indent (&writer);
10820 mono_json_writer_array_end (&writer);
10821 mono_json_writer_printf (&writer, ",\n");
10826 mono_json_writer_indent_push (&writer);
10827 mono_json_writer_indent (&writer);
10828 mono_json_writer_object_key(&writer, "got");
10829 mono_json_writer_array_begin (&writer);
10831 mono_json_writer_indent_push (&writer);
10832 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10833 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10835 mono_json_writer_indent (&writer);
10836 mono_json_writer_printf (&writer, "{ ");
10837 mono_json_writer_object_key(&writer, "patch_name");
10838 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10841 mono_json_writer_indent_pop (&writer);
10842 mono_json_writer_indent (&writer);
10843 mono_json_writer_array_end (&writer);
10844 mono_json_writer_printf (&writer, ",\n");
10847 mono_json_writer_indent_pop (&writer);
10848 mono_json_writer_indent (&writer);
10849 mono_json_writer_object_end (&writer);
10851 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10852 dumpfile = fopen (dumpname, "w+");
10855 fprintf (dumpfile, "%s", writer.text->str);
10858 mono_json_writer_destroy (&writer);
10861 static const char *preinited_jit_icalls[] = {
10862 "mono_aot_init_llvm_method",
10863 "mono_aot_init_gshared_method_this",
10864 "mono_aot_init_gshared_method_mrgctx",
10865 "mono_aot_init_gshared_method_vtable",
10866 "mono_llvm_throw_corlib_exception",
10867 "mono_init_vtable_slot",
10868 "mono_helper_ldstr_mscorlib"
10872 add_preinit_got_slots (MonoAotCompile *acfg)
10878 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10879 * during method initialization etc.
10882 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10883 ji->type = MONO_PATCH_INFO_IMAGE;
10884 ji->data.image = acfg->image;
10885 get_got_offset (acfg, FALSE, ji);
10886 get_got_offset (acfg, TRUE, ji);
10888 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10889 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10890 get_got_offset (acfg, FALSE, ji);
10891 get_got_offset (acfg, TRUE, ji);
10893 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10894 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10895 get_got_offset (acfg, FALSE, ji);
10896 get_got_offset (acfg, TRUE, ji);
10898 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10899 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10900 get_got_offset (acfg, FALSE, ji);
10901 get_got_offset (acfg, TRUE, ji);
10903 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10904 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10905 get_got_offset (acfg, FALSE, ji);
10906 get_got_offset (acfg, TRUE, ji);
10908 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10909 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10910 get_got_offset (acfg, FALSE, ji);
10911 get_got_offset (acfg, TRUE, ji);
10913 for (i = 0; i < TLS_KEY_NUM; i++) {
10914 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10915 ji->type = MONO_PATCH_INFO_GET_TLS_TRAMP;
10916 ji->data.index = i;
10917 get_got_offset (acfg, FALSE, ji);
10918 get_got_offset (acfg, TRUE, ji);
10920 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10921 ji->type = MONO_PATCH_INFO_SET_TLS_TRAMP;
10922 ji->data.index = i;
10923 get_got_offset (acfg, FALSE, ji);
10924 get_got_offset (acfg, TRUE, ji);
10927 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10928 ji->type = MONO_PATCH_INFO_JIT_THREAD_ATTACH;
10929 get_got_offset (acfg, FALSE, ji);
10930 get_got_offset (acfg, TRUE, ji);
10932 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10933 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10934 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10935 ji->data.name = preinited_jit_icalls [i];
10936 get_got_offset (acfg, FALSE, ji);
10937 get_got_offset (acfg, TRUE, ji);
10940 acfg->nshared_got_entries = acfg->got_offset;
10944 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10946 MonoImage *image = ass->image;
10949 MonoAotCompile *acfg;
10950 char *outfile_name, *tmp_outfile_name, *p;
10951 char llvm_stats_msg [256];
10955 acfg = acfg_create (ass, opts);
10957 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10958 acfg->aot_opts.write_symbols = TRUE;
10959 acfg->aot_opts.ntrampolines = 4096;
10960 acfg->aot_opts.nrgctx_trampolines = 4096;
10961 acfg->aot_opts.nimt_trampolines = 512;
10962 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10963 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10964 acfg->aot_opts.llvm_path = g_strdup ("");
10965 acfg->aot_opts.temp_path = g_strdup ("");
10967 acfg->aot_opts.use_trampolines_page = TRUE;
10970 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10972 if (acfg->aot_opts.logfile) {
10973 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10976 if (acfg->aot_opts.data_outfile) {
10977 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10978 if (!acfg->data_outfile) {
10979 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10982 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10985 //acfg->aot_opts.print_skipped_methods = TRUE;
10987 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10988 if (acfg->opts & MONO_OPT_GSHAREDVT) {
10989 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10992 if (acfg->aot_opts.llvm_only) {
10993 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10997 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10998 acfg->opts |= MONO_OPT_GSHAREDVT;
11001 #if !defined(ENABLE_LLVM)
11002 if (acfg->aot_opts.llvm_only) {
11003 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
11008 if (acfg->opts & MONO_OPT_GSHAREDVT)
11009 mono_set_generic_sharing_vt_supported (TRUE);
11011 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
11013 generate_aotid ((guint8*) &acfg->image->aotid);
11015 char *aotid = mono_guid_to_string (acfg->image->aotid);
11016 aot_printf (acfg, "AOTID %s\n", aotid);
11019 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
11020 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
11021 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
11026 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
11027 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
11031 if (acfg->aot_opts.static_link)
11032 acfg->aot_opts.asm_writer = TRUE;
11034 if (acfg->aot_opts.soft_debug) {
11035 MonoDebugOptions *opt = mini_get_debug_options ();
11037 opt->mdb_optimizations = TRUE;
11038 opt->gen_sdb_seq_points = TRUE;
11040 if (!mono_debug_enabled ()) {
11041 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
11044 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
11047 if (mono_use_llvm || acfg->aot_opts.llvm) {
11049 acfg->aot_opts.asm_writer = TRUE;
11050 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
11052 if (acfg->aot_opts.soft_debug) {
11053 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
11059 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
11060 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outfile= option.\n");
11065 if (mono_aot_mode_is_full (&acfg->aot_opts))
11066 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
11068 if (mono_threads_is_coop_enabled ())
11069 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
11071 if (acfg->aot_opts.instances_logfile_path) {
11072 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
11073 if (!acfg->instances_logfile) {
11074 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
11079 if (acfg->aot_opts.profile_files) {
11082 for (l = acfg->aot_opts.profile_files; l; l = l->next) {
11083 load_profile_file (acfg, (char*)l->data);
11090 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
11091 g_ptr_array_add (acfg->method_order,GUINT_TO_POINTER (method_index));
11095 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
11096 #ifdef MONO_ARCH_GSHARED_SUPPORTED
11097 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
11099 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
11100 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
11101 if (acfg->opts & MONO_OPT_GSHAREDVT)
11102 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
11105 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
11109 if (mono_use_llvm || acfg->aot_opts.llvm) {
11112 * Emit all LLVM code into a separate assembly/object file and link with it
11115 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
11116 acfg->llvm_owriter = TRUE;
11117 } else if (acfg->aot_opts.llvm_outfile) {
11118 int len = strlen (acfg->aot_opts.llvm_outfile);
11120 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
11121 acfg->llvm_owriter = TRUE;
11125 if (acfg->llvm && acfg->thumb_mixed)
11126 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
11127 if (acfg->aot_opts.llvm_only)
11128 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
11130 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
11131 /* Get rid of characters which cannot occur in symbols */
11132 for (p = acfg->assembly_name_sym; *p; ++p) {
11133 if (!(isalnum (*p) || *p == '_'))
11137 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
11138 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
11139 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
11141 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
11142 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
11145 acfg->method_index = 1;
11147 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
11148 mono_set_partial_sharing_supported (TRUE);
11150 res = collect_methods (acfg);
11157 for (l = acfg->profile_data; l; l = l->next)
11158 resolve_profile_data (acfg, (ProfileData*)l->data);
11159 for (l = acfg->profile_data; l; l = l->next)
11160 add_profile_instances (acfg, (ProfileData*)l->data);
11163 acfg->cfgs_size = acfg->methods->len + 32;
11164 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
11166 /* PLT offset 0 is reserved for the PLT trampoline */
11167 acfg->plt_offset = 1;
11168 add_preinit_got_slots (acfg);
11173 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
11179 compile_methods (acfg);
11183 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
11189 if (acfg->aot_opts.asm_only) {
11190 if (acfg->aot_opts.outfile) {
11191 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11192 acfg->tmpbasename = g_strdup (acfg->tmpfname);
11194 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
11195 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11197 g_assert (acfg->aot_opts.llvm_outfile);
11198 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11199 if (acfg->llvm_owriter)
11200 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
11202 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
11204 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
11205 g_strdup_printf ("%s", "temp") :
11206 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
11208 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
11209 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
11210 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
11215 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
11216 if (acfg->aot_opts.outfile)
11217 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
11219 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
11220 acfg->fp = fopen (acfg->tmpfname, "w+");
11222 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
11223 acfg->fp = fdopen (i, "w+");
11225 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
11226 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
11230 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
11232 tmp_outfile_name = NULL;
11233 outfile_name = NULL;
11235 /* Compute symbols for methods */
11236 for (i = 0; i < acfg->nmethods; ++i) {
11237 if (acfg->cfgs [i]) {
11238 MonoCompile *cfg = acfg->cfgs [i];
11239 int method_index = get_method_index (acfg, cfg->orig_method);
11241 if (COMPILE_LLVM (cfg))
11242 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
11243 else if (acfg->global_symbols || acfg->llvm)
11244 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
11246 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
11247 cfg->asm_debug_symbol = cfg->asm_symbol;
11251 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
11253 * CLANG supports GAS .file/.loc directives, so emit line number information this way
11255 acfg->gas_line_numbers = TRUE;
11258 #ifdef EMIT_DWARF_INFO
11259 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
11260 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
11261 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
11264 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
11266 #endif /* EMIT_DWARF_INFO */
11269 mono_img_writer_emit_start (acfg->w);
11272 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
11278 emit_extra_methods (acfg);
11280 emit_trampolines (acfg);
11282 emit_class_name_table (acfg);
11284 emit_got_info (acfg, FALSE);
11286 emit_got_info (acfg, TRUE);
11288 emit_exception_info (acfg);
11290 emit_unwind_info (acfg);
11292 emit_class_info (acfg);
11296 emit_image_table (acfg);
11302 * The managed allocators are GC specific, so can't use an AOT image created by one GC
11305 const char *gc_name = mono_gc_get_gc_name ();
11306 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
11311 emit_objc_selectors (acfg);
11313 emit_globals (acfg);
11315 emit_file_info (acfg);
11317 emit_library_info (acfg);
11320 emit_dwarf_info (acfg);
11321 mono_dwarf_writer_close (acfg->dwarf);
11324 emit_mem_end (acfg);
11326 if (acfg->need_pt_gnu_stack) {
11327 /* This is required so the .so doesn't have an executable stack */
11328 /* The bin writer already emits this */
11329 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
11332 if (acfg->aot_opts.data_outfile)
11333 fclose (acfg->data_outfile);
11339 res = emit_llvm_file (acfg);
11347 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
11350 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
11352 strcpy (llvm_stats_msg, "");
11354 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;
11356 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",
11357 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
11358 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
11359 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
11360 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
11361 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
11362 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,
11363 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
11364 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
11365 (int)(acfg->got_offset * sizeof (gpointer)));
11366 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
11367 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
11369 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
11370 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
11371 if (acfg->stats.genericcount)
11372 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
11373 if (acfg->stats.abscount)
11374 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
11375 if (acfg->stats.lmfcount)
11376 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
11377 if (acfg->stats.ocount)
11378 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
11382 res = mono_img_writer_emit_writeout (acfg->w);
11387 res = compile_asm (acfg);
11394 acfg->stats.link_time = TV_ELAPSED (atv, btv);
11396 if (acfg->aot_opts.stats) {
11399 aot_printf (acfg, "GOT slot distribution:\n");
11400 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
11401 if (acfg->stats.got_slot_types [i])
11402 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]);
11403 aot_printf (acfg, "\nMethod stats:\n");
11404 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
11405 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
11406 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
11407 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
11410 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);
11412 if (acfg->aot_opts.dump_json)
11425 mono_aot_readonly_field_override (MonoClassField *field)
11431 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
11437 mono_aot_is_shared_got_offset (int offset)