2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
11 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include <sys/types.h>
35 #include <mono/metadata/abi-details.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/class.h>
38 #include <mono/metadata/object.h>
39 #include <mono/metadata/tokentype.h>
40 #include <mono/metadata/appdomain.h>
41 #include <mono/metadata/debug-helpers.h>
42 #include <mono/metadata/assembly.h>
43 #include <mono/metadata/metadata-internals.h>
44 #include <mono/metadata/reflection-internals.h>
45 #include <mono/metadata/marshal.h>
46 #include <mono/metadata/gc-internals.h>
47 #include <mono/metadata/mempool-internals.h>
48 #include <mono/metadata/mono-endian.h>
49 #include <mono/metadata/threads-types.h>
50 #include <mono/utils/mono-logger-internals.h>
51 #include <mono/utils/mono-compiler.h>
52 #include <mono/utils/mono-time.h>
53 #include <mono/utils/mono-mmap.h>
54 #include <mono/utils/mono-rand.h>
55 #include <mono/utils/json.h>
56 #include <mono/utils/mono-threads-coop.h>
58 #include "aot-compiler.h"
59 #include "seq-points.h"
60 #include "image-writer.h"
61 #include "dwarfwriter.h"
63 #include "mini-llvm.h"
65 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
67 #if defined(__linux__) || defined(__native_client_codegen__)
68 #define RODATA_SECT ".rodata"
69 #elif defined(TARGET_MACH)
70 #define RODATA_SECT ".section __TEXT, __const"
72 #define RODATA_SECT ".text"
75 #define TV_DECLARE(name) gint64 name
76 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
77 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
79 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
80 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
81 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
83 /* predefined values for static readonly fields without needed to run the .cctor */
84 typedef struct _ReadOnlyValue ReadOnlyValue;
85 struct _ReadOnlyValue {
88 int type; /* to be used later for typechecking to prevent user errors */
97 static ReadOnlyValue *readonly_values;
99 typedef struct MonoAotOptions {
104 gboolean write_symbols;
105 gboolean metadata_only;
106 gboolean bind_to_runtime_version;
109 gboolean static_link;
113 gboolean dwarf_debug;
115 gboolean log_generics;
116 gboolean log_instances;
117 gboolean gen_msym_dir;
118 char *gen_msym_dir_path;
119 gboolean direct_pinvoke;
120 gboolean direct_icalls;
121 gboolean no_direct_calls;
122 gboolean use_trampolines_page;
123 gboolean no_instances;
129 int nrgctx_trampolines;
130 int nimt_trampolines;
131 int ngsharedvt_arg_trampolines;
132 int nrgctx_fetch_trampolines;
133 gboolean print_skipped_methods;
140 char *instances_logfile_path;
147 METHOD_CAT_GSHAREDVT,
153 typedef struct MonoAotStats {
154 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
155 gint64 code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, plt_size;
156 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
157 int got_slots, offsets_size;
158 int method_categories [METHOD_CAT_NUM];
159 int got_slot_types [MONO_PATCH_INFO_NUM];
160 int got_slot_info_sizes [MONO_PATCH_INFO_NUM];
161 int jit_time, gen_time, link_time;
164 typedef struct GotInfo {
165 GHashTable *patch_to_got_offset;
166 GHashTable **patch_to_got_offset_by_type;
167 GPtrArray *got_patches;
170 typedef struct MonoAotCompile {
173 GHashTable *method_indexes;
174 GHashTable *method_depth;
177 GHashTable **patch_to_plt_entry;
178 GHashTable *plt_offset_to_entry;
179 //GHashTable *patch_to_got_offset;
180 //GHashTable **patch_to_got_offset_by_type;
181 //GPtrArray *got_patches;
182 GotInfo got_info, llvm_got_info;
183 GHashTable *image_hash;
184 GHashTable *method_to_cfg;
185 GHashTable *token_info_hash;
186 GHashTable *method_to_pinvoke_import;
187 GPtrArray *extra_methods;
188 GPtrArray *image_table;
190 GPtrArray *method_order;
191 GHashTable *export_names;
192 /* Maps MonoClass* -> blob offset */
193 GHashTable *klass_blob_hash;
194 /* Maps MonoMethod* -> blob offset */
195 GHashTable *method_blob_hash;
196 GHashTable *gsharedvt_in_signatures;
197 GHashTable *gsharedvt_out_signatures;
198 guint32 *plt_got_info_offsets;
199 guint32 got_offset, llvm_got_offset, plt_offset, plt_got_offset_base, nshared_got_entries;
200 /* Number of GOT entries reserved for trampolines */
201 guint32 num_trampoline_got_entries;
202 guint32 tramp_page_size;
204 guint32 table_offsets [MONO_AOT_TABLE_NUM];
205 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
206 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
207 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
208 guint32 tramp_page_code_offsets [MONO_AOT_TRAMP_NUM];
210 MonoAotOptions aot_opts;
214 MonoMemPool *mempool;
217 char *static_linking_symbol;
219 gboolean gas_line_numbers;
220 /* Whenever to emit an object file directly from llc */
221 gboolean llvm_owriter;
223 MonoDwarfWriter *dwarf;
230 GHashTable *unwind_info_offsets;
231 GPtrArray *unwind_ops;
232 guint32 unwind_info_offset;
235 char *llvm_got_symbol;
237 char *llvm_eh_frame_symbol;
238 GHashTable *method_label_hash;
239 const char *temp_prefix;
240 const char *user_symbol_prefix;
241 const char *llvm_label_prefix;
242 const char *inst_directive;
244 guint32 label_generator;
246 gboolean has_jitted_code;
247 MonoAotFileFlags flags;
248 MonoDynamicStream blob;
249 gboolean blob_closed;
250 GHashTable *typespec_classes;
253 char *assembly_name_sym;
254 GHashTable *plt_entry_debug_sym_cache;
255 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
256 GHashTable *ginst_hash;
257 GHashTable *dwarf_ln_filenames;
258 gboolean global_symbols;
259 int objc_selector_index, objc_selector_index_2;
260 GPtrArray *objc_selectors;
261 GHashTable *objc_selector_to_index;
263 FILE *instances_logfile;
271 char *symbol, *llvm_symbol, *debug_sym;
273 gboolean jit_used, llvm_used;
276 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
277 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
279 /* This points to the current acfg in LLVM mode */
280 static MonoAotCompile *llvm_acfg;
282 #ifdef HAVE_ARRAY_ELEM_INIT
283 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
284 #define MSGSTRFIELD1(line) str##line
285 static const struct msgstr_t {
286 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
287 #include "patch-info.h"
290 #define PATCH_INFO(a,b) b,
291 #include "patch-info.h"
294 static const gint16 opidx [] = {
295 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
296 #include "patch-info.h"
300 static G_GNUC_UNUSED const char*
301 get_patch_name (int info)
303 return (const char*)&opstr + opidx [info];
307 #define PATCH_INFO(a,b) b,
308 static const char* const
309 patch_types [MONO_PATCH_INFO_NUM + 1] = {
310 #include "patch-info.h"
314 static G_GNUC_UNUSED const char*
315 get_patch_name (int info)
317 return patch_types [info];
323 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
326 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
329 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
335 output = acfg->logfile;
339 va_start (args, format);
340 vfprintf (output, format, args);
345 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
351 output = acfg->logfile;
355 va_start (args, format);
356 vfprintf (output, format, args);
361 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
366 if (mono_error_ok (error))
370 output = acfg->logfile;
374 va_start (args, format);
375 vfprintf (output, format, args);
377 mono_error_cleanup (error);
379 g_error ("FullAOT cannot continue if there are loader errors");
382 /* Wrappers around the image writer functions */
384 #define MAX_SYMBOL_SIZE 256
386 static inline const char *
387 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
389 gsize needed_size = length;
391 g_assert (NULL != symbol);
392 g_assert (NULL != mangled_symbol);
393 g_assert (0 != length);
395 #if defined(TARGET_WIN32) && defined(TARGET_X86)
396 if (symbol && '_' != symbol [0]) {
397 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
399 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
402 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
405 g_assert (0 <= needed_size && needed_size < length);
406 return mangled_symbol;
410 mangle_symbol_alloc (const char * symbol)
412 g_assert (NULL != symbol);
414 #if defined(TARGET_WIN32) && defined(TARGET_X86)
415 if (symbol && '_' != symbol [0]) {
416 return g_strdup_printf ("_%s", symbol);
419 return g_strdup_printf ("%s", symbol);
422 return g_strdup_printf ("%s", symbol);
427 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
429 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
432 #if defined(TARGET_WIN32) && defined(TARGET_X86)
435 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
437 const char * mangled_symbol_name = name;
438 char * mangled_symbol_name_alloc = NULL;
441 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
442 mangled_symbol_name = mangled_symbol_name_alloc;
445 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
446 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
448 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
450 if (NULL != mangled_symbol_name_alloc) {
451 g_free (mangled_symbol_name_alloc);
458 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
460 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
466 emit_label (MonoAotCompile *acfg, const char *name)
468 mono_img_writer_emit_label (acfg->w, name);
472 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
474 mono_img_writer_emit_bytes (acfg->w, buf, size);
478 emit_string (MonoAotCompile *acfg, const char *value)
480 mono_img_writer_emit_string (acfg->w, value);
484 emit_line (MonoAotCompile *acfg)
486 mono_img_writer_emit_line (acfg->w);
490 emit_alignment (MonoAotCompile *acfg, int size)
492 mono_img_writer_emit_alignment (acfg->w, size);
496 emit_alignment_code (MonoAotCompile *acfg, int size)
498 if (acfg->align_pad_value)
499 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
501 mono_img_writer_emit_alignment (acfg->w, size);
505 emit_padding (MonoAotCompile *acfg, int size)
510 if (acfg->align_pad_value) {
511 for (i = 0; i < 16; ++i)
512 buf [i] = acfg->align_pad_value;
514 memset (buf, 0, sizeof (buf));
517 for (i = 0; i < size; i += 16) {
519 emit_bytes (acfg, buf, size - i);
521 emit_bytes (acfg, buf, 16);
526 emit_pointer (MonoAotCompile *acfg, const char *target)
528 mono_img_writer_emit_pointer (acfg->w, target);
532 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
534 if (prefix [0] != '\0') {
535 char *s = g_strdup_printf ("%s%s", prefix, target);
536 mono_img_writer_emit_pointer (acfg->w, s);
539 mono_img_writer_emit_pointer (acfg->w, target);
544 emit_int16 (MonoAotCompile *acfg, int value)
546 mono_img_writer_emit_int16 (acfg->w, value);
550 emit_int32 (MonoAotCompile *acfg, int value)
552 mono_img_writer_emit_int32 (acfg->w, value);
556 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
558 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
562 emit_zero_bytes (MonoAotCompile *acfg, int num)
564 mono_img_writer_emit_zero_bytes (acfg->w, num);
568 emit_byte (MonoAotCompile *acfg, guint8 val)
570 mono_img_writer_emit_byte (acfg->w, val);
573 #if defined(TARGET_WIN32) && defined(TARGET_X86)
575 static G_GNUC_UNUSED void
576 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
578 const char * mangled_symbol_name = name;
579 char * mangled_symbol_name_alloc = NULL;
581 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
582 mangled_symbol_name = mangled_symbol_name_alloc;
584 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
585 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
587 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
589 if (NULL != mangled_symbol_name_alloc) {
590 g_free (mangled_symbol_name_alloc);
596 static G_GNUC_UNUSED void
597 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
599 mono_img_writer_emit_global (acfg->w, name, func);
605 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
607 if (acfg->aot_opts.no_dlsym) {
608 g_ptr_array_add (acfg->globals, g_strdup (name));
609 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
611 emit_global_inner (acfg, name, func);
616 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
618 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
621 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
623 emit_info_symbol (MonoAotCompile *acfg, const char *name)
625 char symbol [MAX_SYMBOL_SIZE];
628 emit_label (acfg, name);
629 /* LLVM generated code references this */
630 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
631 emit_label (acfg, symbol);
632 emit_global_inner (acfg, symbol, FALSE);
634 emit_label (acfg, name);
639 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
642 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
646 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
648 /* On apple, all symbols need to be aligned to avoid warnings from ld */
649 emit_alignment (acfg, 4);
651 mono_img_writer_emit_label (acfg->w, name);
652 mono_img_writer_emit_string (acfg->w, value);
655 static G_GNUC_UNUSED void
656 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
659 guint8 b = value & 0x7f;
661 if (value != 0) /* more bytes to come */
667 static G_GNUC_UNUSED void
668 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
671 gboolean negative = (value < 0);
678 /* the following is unnecessary if the
679 * implementation of >>= uses an arithmetic rather
680 * than logical shift for a signed left operand
684 value |= - ((gint64)1 <<(size - 7));
685 /* sign bit of byte is second high order bit (0x40) */
686 if ((value == 0 && !(byte & 0x40)) ||
687 (value == -1 && (byte & 0x40)))
691 emit_byte (acfg, byte);
695 static G_GNUC_UNUSED void
696 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
701 guint8 b = value & 0x7f;
703 if (value != 0) /* more bytes to come */
711 static G_GNUC_UNUSED void
712 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
715 gboolean negative = (value < 0);
723 /* the following is unnecessary if the
724 * implementation of >>= uses an arithmetic rather
725 * than logical shift for a signed left operand
729 value |= - (1 <<(size - 7));
730 /* sign bit of byte is second high order bit (0x40) */
731 if ((value == 0 && !(byte & 0x40)) ||
732 (value == -1 && (byte & 0x40)))
743 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
746 buf [0] = (val >> 0) & 0xff;
747 buf [1] = (val >> 8) & 0xff;
748 buf [2] = (val >> 16) & 0xff;
749 buf [3] = (val >> 24) & 0xff;
755 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
757 buf [0] = (val >> 0) & 0xff;
758 buf [1] = (val >> 8) & 0xff;
764 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
766 int len = strlen (s);
768 memcpy (buf, s, len + 1);
769 *endbuf = buf + len + 1;
773 emit_unset_mode (MonoAotCompile *acfg)
775 mono_img_writer_emit_unset_mode (acfg->w);
778 static G_GNUC_UNUSED void
779 emit_set_thumb_mode (MonoAotCompile *acfg)
781 emit_unset_mode (acfg);
782 fprintf (acfg->fp, ".code 16\n");
785 static G_GNUC_UNUSED void
786 emit_set_arm_mode (MonoAotCompile *acfg)
788 emit_unset_mode (acfg);
789 fprintf (acfg->fp, ".code 32\n");
793 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
798 g_assert (size % 4 == 0);
799 emit_unset_mode (acfg);
800 for (i = 0; i < size; i += 4)
801 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
803 emit_bytes (acfg, buf, size);
807 /* ARCHITECTURE SPECIFIC CODE */
809 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
810 #define EMIT_DWARF_INFO 1
813 #if defined(TARGET_ARM)
814 #define AOT_FUNC_ALIGNMENT 4
816 #define AOT_FUNC_ALIGNMENT 16
819 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
820 #define PPC_LD_OP "ld"
821 #define PPC_LDX_OP "ldx"
823 #define PPC_LD_OP "lwz"
824 #define PPC_LDX_OP "lwzx"
828 #define AOT_TARGET_STR "AMD64"
833 #define AOT_TARGET_STR "ARM (MACH)"
835 #define AOT_TARGET_STR "ARM (!MACH)"
841 #define AOT_TARGET_STR "ARM64 (MACH)"
843 #define AOT_TARGET_STR "ARM64 (!MACH)"
847 #ifdef TARGET_POWERPC64
848 #ifdef __mono_ilp32__
849 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
851 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
854 #ifdef TARGET_POWERPC
855 #ifdef __mono_ilp32__
856 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
858 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
865 #define AOT_TARGET_STR "X86 (WIN32)"
866 #elif defined(__native_client_codegen__)
867 #define AOT_TARGET_STR "X86 (native client codegen)"
869 #define AOT_TARGET_STR "X86 (!native client codegen)"
873 #ifndef AOT_TARGET_STR
874 #define AOT_TARGET_STR ""
878 arch_init (MonoAotCompile *acfg)
880 acfg->llc_args = g_string_new ("");
881 acfg->as_args = g_string_new ("");
884 * The prefix LLVM likes to put in front of symbol names on darwin.
885 * The mach-os specs require this for globals, but LLVM puts them in front of all
886 * symbols. We need to handle this, since we need to refer to LLVM generated
889 acfg->llvm_label_prefix = "";
890 acfg->user_symbol_prefix = "";
892 #if defined(TARGET_X86)
893 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
896 #if defined(TARGET_AMD64)
897 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
899 acfg->align_pad_value = 0x90;
903 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
904 g_string_append (acfg->llc_args, "-mattr=+v6");
906 #if defined(ARM_FPU_VFP_HARD)
907 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
908 g_string_append (acfg->as_args, " -mfpu=vfp3");
909 #elif defined(ARM_FPU_VFP)
910 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
911 g_string_append (acfg->as_args, " -mfpu=vfp3");
913 g_string_append (acfg->llc_args, " -soft-float");
916 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
917 acfg->thumb_mixed = TRUE;
919 if (acfg->aot_opts.mtriple)
920 mono_arch_set_target (acfg->aot_opts.mtriple);
924 acfg->inst_directive = ".inst";
925 if (acfg->aot_opts.mtriple)
926 mono_arch_set_target (acfg->aot_opts.mtriple);
930 acfg->user_symbol_prefix = "_";
931 acfg->llvm_label_prefix = "_";
932 acfg->inst_directive = ".word";
933 acfg->need_no_dead_strip = TRUE;
934 acfg->aot_opts.gnu_asm = TRUE;
937 #if defined(__linux__) && !defined(TARGET_ARM)
938 acfg->need_pt_gnu_stack = TRUE;
942 acfg->global_symbols = TRUE;
949 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
951 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
956 emit_unset_mode (acfg);
958 offset = (int)(got_slot * sizeof (gpointer));
960 /* clang's integrated assembler */
961 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
962 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
963 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
966 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
967 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
968 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
973 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
978 emit_unset_mode (acfg);
981 reg = arm_get_ldr_lit_reg (code);
983 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
984 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
985 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
991 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
994 emit_unset_mode (acfg);
995 if (ji && ji->relocation == MONO_R_ARM64_B) {
996 fprintf (acfg->fp, "b %s\n", target);
999 g_assert (ji->relocation == MONO_R_ARM64_BL);
1000 fprintf (acfg->fp, "bl %s\n", target);
1006 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1010 /* ldr rt, target */
1011 reg = arm_get_ldr_lit_reg (code);
1012 arm64_emit_load_got_slot (acfg, reg, got_slot);
1017 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1019 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1020 fprintf (acfg->fp, "br x16\n");
1021 /* Used by mono_aot_get_plt_info_offset () */
1022 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1026 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1032 /* The common code */
1035 /* The trampoline address is in IP0 */
1036 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1037 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1038 /* Compute the data slot address */
1039 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1040 /* Trampoline argument */
1041 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1043 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1044 arm_brx (code, ARMREG_IP0);
1047 emit_code_bytes (acfg, buf, code - buf);
1053 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1059 count = (pagesize - common_tramp_size) / specific_tramp_size;
1060 for (i = 0; i < count; ++i) {
1062 arm_adrx (code, ARMREG_IP0, code);
1063 /* Branch to the generic code */
1064 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1065 /* This has to be 2 pointers long */
1068 g_assert (code - buf == specific_tramp_size);
1069 emit_code_bytes (acfg, buf, code - buf);
1074 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1078 guint8 *labels [16];
1079 int common_tramp_size;
1080 int specific_tramp_size = 2 * 8;
1084 if (!acfg->aot_opts.use_trampolines_page)
1088 /* Have to match the target pagesize */
1091 pagesize = mono_pagesize ();
1093 acfg->tramp_page_size = pagesize;
1095 /* The specific trampolines */
1096 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1097 emit_alignment (acfg, pagesize);
1098 emit_global (acfg, symbol, TRUE);
1099 emit_label (acfg, symbol);
1101 /* The common code */
1102 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1103 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1105 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1107 /* The rgctx trampolines */
1108 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1109 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1110 emit_alignment (acfg, pagesize);
1111 emit_global (acfg, symbol, TRUE);
1112 emit_label (acfg, symbol);
1114 /* The common code */
1115 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1116 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1118 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1120 /* The gsharedvt arg trampolines */
1121 /* These are the same as the specific trampolines */
1122 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1123 emit_alignment (acfg, pagesize);
1124 emit_global (acfg, symbol, TRUE);
1125 emit_label (acfg, symbol);
1127 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1128 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1130 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1132 /* The IMT trampolines */
1133 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1134 emit_alignment (acfg, pagesize);
1135 emit_global (acfg, symbol, TRUE);
1136 emit_label (acfg, symbol);
1140 /* The trampoline address is in IP0 */
1141 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1142 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1143 /* Compute the data slot address */
1144 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1145 /* Trampoline argument */
1146 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1148 /* Same as arch_emit_imt_thunk () */
1150 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1151 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1153 arm_bcc (code, ARMCOND_EQ, 0);
1155 /* End-of-loop check */
1157 arm_cbzx (code, ARMREG_IP0, 0);
1160 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1161 arm_b (code, labels [0]);
1164 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1165 /* Load vtable slot addr */
1166 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1167 /* Load vtable slot */
1168 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1169 arm_brx (code, ARMREG_IP0);
1172 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1173 /* Load fail addr */
1174 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1175 arm_brx (code, ARMREG_IP0);
1177 emit_code_bytes (acfg, buf, code - buf);
1179 common_tramp_size = code - buf;
1180 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = common_tramp_size;
1182 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1186 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1188 /* Load argument from second GOT slot */
1189 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1190 /* Load generic trampoline address from first GOT slot */
1191 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1192 fprintf (acfg->fp, "br x16\n");
1193 *tramp_size = 7 * 4;
1197 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1199 emit_unset_mode (acfg);
1200 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1201 fprintf (acfg->fp, "b %s\n", call_target);
1205 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1207 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1209 /* Load argument from first GOT slot */
1210 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1211 /* Load generic trampoline address from second GOT slot */
1212 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1213 fprintf (acfg->fp, "br x16\n");
1214 *tramp_size = 7 * 4;
1218 arm64_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1221 guint8 *code, *labels [16];
1223 /* Load parameter from GOT slot into ip1 */
1224 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1228 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1229 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1231 arm_bcc (code, ARMCOND_EQ, 0);
1233 /* End-of-loop check */
1235 arm_cbzx (code, ARMREG_IP0, 0);
1238 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1239 arm_b (code, labels [0]);
1242 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1243 /* Load vtable slot addr */
1244 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1245 /* Load vtable slot */
1246 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1247 arm_brx (code, ARMREG_IP0);
1250 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1251 /* Load fail addr */
1252 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1253 arm_brx (code, ARMREG_IP0);
1255 emit_code_bytes (acfg, buf, code - buf);
1257 *tramp_size = code - buf + (3 * 4);
1261 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1263 /* Similar to the specific trampolines, but the address is in the second slot */
1264 /* Load argument from first GOT slot */
1265 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1266 /* Load generic trampoline address from second GOT slot */
1267 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1268 fprintf (acfg->fp, "br x16\n");
1269 *tramp_size = 7 * 4;
1275 #ifdef MONO_ARCH_AOT_SUPPORTED
1277 * arch_emit_direct_call:
1279 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1283 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1285 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1286 /* Need to make sure this is exactly 5 bytes long */
1287 emit_unset_mode (acfg);
1288 fprintf (acfg->fp, "call %s\n", target);
1290 #elif defined(TARGET_ARM)
1291 emit_unset_mode (acfg);
1293 fprintf (acfg->fp, "blx %s\n", target);
1295 fprintf (acfg->fp, "bl %s\n", target);
1297 #elif defined(TARGET_ARM64)
1298 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1299 #elif defined(TARGET_POWERPC)
1300 emit_unset_mode (acfg);
1301 fprintf (acfg->fp, "bl %s\n", target);
1304 g_assert_not_reached ();
1311 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1313 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1314 * in in the 2. slot of every GOT, and require every method to place the GOT
1315 * address in r30, even when it doesn't access the GOT otherwise. This way,
1316 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1321 * PPC64 uses function descriptors which greatly complicate all code, since
1322 * these are used very inconsistently in the runtime. Some functions like
1323 * mono_compile_method () return ftn descriptors, while others like the
1324 * trampoline creation functions do not.
1325 * We assume that all GOT slots contain function descriptors, and create
1326 * descriptors in aot-runtime.c when needed.
1327 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1328 * from function descriptors, we could do the same, but it would require
1329 * rewriting all the ppc/aot code to handle function descriptors properly.
1330 * So instead, we use the same approach as on PPC32.
1331 * This is a horrible mess, but fixing it would probably lead to an even bigger
1337 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1340 #ifdef MONO_ARCH_AOT_SUPPORTED
1342 * arch_emit_got_offset:
1344 * The memory pointed to by CODE should hold native code for computing the GOT
1345 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1346 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1349 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1351 #if defined(TARGET_POWERPC64)
1352 emit_unset_mode (acfg);
1354 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1355 * unsupported relocations. So we store the got address into the .Lgot_addr
1356 * symbol which is in the text segment, compute its address, and load it.
1358 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1359 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1360 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1361 fprintf (acfg->fp, "add 30, 30, 0\n");
1362 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1363 acfg->label_generator ++;
1365 #elif defined(TARGET_POWERPC)
1366 emit_unset_mode (acfg);
1367 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1368 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1369 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1370 acfg->label_generator ++;
1373 guint32 offset = mono_arch_get_patch_offset (code);
1374 emit_bytes (acfg, code, offset);
1375 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1377 *code_size = offset + 4;
1382 * arch_emit_got_access:
1384 * The memory pointed to by CODE should hold native code for loading a GOT
1385 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1386 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1389 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1392 /* mov reg, got+offset(%rip) */
1394 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1398 /* Decode reg, see amd64_mov_reg_membase () */
1399 rex_r = code [0] & AMD64_REX_R;
1400 g_assert (code [0] == 0x49 + rex_r);
1401 g_assert (code [1] == 0x8b);
1402 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1404 emit_unset_mode (acfg);
1405 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1408 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1409 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1410 *code_size = mono_arch_get_patch_offset (code) + 4;
1412 #elif defined(TARGET_X86)
1413 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1414 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1415 *code_size = mono_arch_get_patch_offset (code) + 4;
1416 #elif defined(TARGET_ARM)
1417 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1418 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1419 *code_size = mono_arch_get_patch_offset (code) + 4;
1420 #elif defined(TARGET_ARM64)
1421 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1422 arm64_emit_got_access (acfg, code, got_slot, code_size);
1423 #elif defined(TARGET_POWERPC)
1428 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1430 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1431 g_assert (code - buf == 8);
1432 emit_bytes (acfg, buf, code - buf);
1433 *code_size = code - buf;
1436 g_assert_not_reached ();
1442 #ifdef MONO_ARCH_AOT_SUPPORTED
1444 * arch_emit_objc_selector_ref:
1446 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1449 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1451 #if defined(TARGET_ARM)
1452 char symbol1 [MAX_SYMBOL_SIZE];
1453 char symbol2 [MAX_SYMBOL_SIZE];
1454 int lindex = acfg->objc_selector_index_2 ++;
1456 /* Emit ldr.imm/b */
1457 emit_bytes (acfg, code, 8);
1459 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1460 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1462 emit_label (acfg, symbol1);
1463 mono_img_writer_emit_unset_mode (acfg->w);
1464 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1467 #elif defined(TARGET_ARM64)
1468 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1470 g_assert_not_reached ();
1476 * arch_emit_plt_entry:
1478 * Emit code for the PLT entry.
1479 * The plt entry should look like this:
1480 * <indirect jump to GOT_SYMBOL + OFFSET>
1481 * <INFO_OFFSET embedded into the instruction stream>
1484 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1486 #if defined(TARGET_X86)
1487 /* jmp *<offset>(%ebx) */
1488 emit_byte (acfg, 0xff);
1489 emit_byte (acfg, 0xa3);
1490 emit_int32 (acfg, offset);
1491 /* Used by mono_aot_get_plt_info_offset */
1492 emit_int32 (acfg, info_offset);
1493 #elif defined(TARGET_AMD64)
1494 emit_unset_mode (acfg);
1495 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1496 /* Used by mono_aot_get_plt_info_offset */
1497 emit_int32 (acfg, info_offset);
1498 acfg->stats.plt_size += 10;
1499 #elif defined(TARGET_ARM)
1504 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1505 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1506 emit_bytes (acfg, buf, code - buf);
1507 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1508 /* Used by mono_aot_get_plt_info_offset */
1509 emit_int32 (acfg, info_offset);
1510 #elif defined(TARGET_ARM64)
1511 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1512 #elif defined(TARGET_POWERPC)
1513 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1514 emit_unset_mode (acfg);
1515 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1516 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1517 fprintf (acfg->fp, "add 11, 11, 30\n");
1518 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1519 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1520 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1521 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1523 fprintf (acfg->fp, "mtctr 11\n");
1524 fprintf (acfg->fp, "bctr\n");
1525 emit_int32 (acfg, info_offset);
1527 g_assert_not_reached ();
1532 * arch_emit_llvm_plt_entry:
1534 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1535 * This is only needed on arm to handle thumb interop.
1538 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1540 #if defined(TARGET_ARM)
1541 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1542 /* The caller already transitioned to thumb */
1543 /* The code below should be 12 bytes long */
1544 /* clang has trouble encoding these instructions, so emit the binary */
1546 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1547 /* thumb can't encode ld pc, [pc, ip] */
1548 fprintf (acfg->fp, "add ip, pc, ip\n");
1549 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1550 fprintf (acfg->fp, "bx ip\n");
1552 emit_set_thumb_mode (acfg);
1553 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1554 fprintf (acfg->fp, ".2byte 0x44fc\n");
1555 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1556 fprintf (acfg->fp, ".2byte 0x4760\n");
1557 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1558 emit_int32 (acfg, info_offset);
1559 emit_unset_mode (acfg);
1560 emit_set_arm_mode (acfg);
1562 g_assert_not_reached ();
1566 /* Save unwind_info in the module and emit the offset to the information at symbol */
1567 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1569 guint32 uw_offset, encoded_len;
1572 emit_section_change (acfg, RODATA_SECT, 0);
1573 emit_global (acfg, symbol, FALSE);
1574 emit_label (acfg, symbol);
1576 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1577 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1579 emit_int32 (acfg, uw_offset);
1583 * arch_emit_specific_trampoline_pages:
1585 * Emits a page full of trampolines: each trampoline uses its own address to
1586 * lookup both the generic trampoline code and the data argument.
1587 * This page can be remapped in process multiple times so we can get an
1588 * unlimited number of trampolines.
1589 * Specifically this implementation uses the following trick: two memory pages
1590 * are allocated, with the first containing the data and the second containing the trampolines.
1591 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1592 * implementation does all the lifting.
1593 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1594 * on the arm 32 bit system.
1597 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1599 #if defined(TARGET_ARM)
1602 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1604 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1605 GSList *unwind_ops = NULL;
1606 #define COMMON_TRAMP_SIZE 16
1607 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1608 int imm8, rot_amount;
1611 if (!acfg->aot_opts.use_trampolines_page)
1614 acfg->tramp_page_size = pagesize;
1616 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1617 emit_alignment (acfg, pagesize);
1618 emit_global (acfg, symbol, TRUE);
1619 emit_label (acfg, symbol);
1621 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1623 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1624 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1625 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1626 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1628 g_assert (code - buf == COMMON_TRAMP_SIZE);
1631 emit_bytes (acfg, buf, code - buf);
1633 for (i = 0; i < count; ++i) {
1635 ARM_PUSH (code, 0x5fff);
1637 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1638 g_assert (code - buf == 8);
1639 emit_bytes (acfg, buf, code - buf);
1642 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1643 * the instruction pointer address, so the generic trampoline at the start of the page
1644 * subtracts 4096 to get to the data page and loads the values
1645 * We again fit the generic trampiline in 16 bytes.
1647 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1648 emit_global (acfg, symbol, TRUE);
1649 emit_label (acfg, symbol);
1651 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1652 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1653 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1654 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1656 g_assert (code - buf == COMMON_TRAMP_SIZE);
1659 emit_bytes (acfg, buf, code - buf);
1661 for (i = 0; i < count; ++i) {
1663 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1665 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1666 g_assert (code - buf == 8);
1667 emit_bytes (acfg, buf, code - buf);
1671 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1673 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1674 emit_global (acfg, symbol, TRUE);
1675 emit_label (acfg, symbol);
1677 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1678 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1679 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1680 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1681 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1682 g_assert (code - buf == COMMON_TRAMP_SIZE);
1684 emit_bytes (acfg, buf, code - buf);
1686 for (i = 0; i < count; ++i) {
1688 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1690 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1691 g_assert (code - buf == 8);
1692 emit_bytes (acfg, buf, code - buf);
1695 /* now the imt trampolines: each specific trampolines puts in the ip register
1696 * the instruction pointer address, so the generic trampoline at the start of the page
1697 * subtracts 4096 to get to the data page and loads the values
1699 #define IMT_TRAMP_SIZE 72
1700 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1701 emit_global (acfg, symbol, TRUE);
1702 emit_label (acfg, symbol);
1704 /* Need at least two free registers, plus a slot for storing the pc */
1705 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1707 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1708 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1709 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1711 /* The IMT method is in v5, r0 has the imt array address */
1714 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1715 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1716 imt_found_check = code;
1717 ARM_B_COND (code, ARMCOND_EQ, 0);
1719 /* End-of-loop check */
1720 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1721 loop_end_check = code;
1722 ARM_B_COND (code, ARMCOND_EQ, 0);
1725 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1726 loop_branch_back = code;
1728 arm_patch (loop_branch_back, loop_start);
1731 arm_patch (imt_found_check, code);
1732 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1733 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1734 /* Save it to the third stack slot */
1735 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1736 /* Restore the registers and branch */
1737 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1740 arm_patch (loop_end_check, code);
1741 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1742 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1743 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1747 g_assert (code - buf == IMT_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 - IMT_TRAMP_SIZE - 8 * (i + 1));
1755 g_assert (code - buf == 8);
1756 emit_bytes (acfg, buf, code - buf);
1759 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1760 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1761 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT_THUNK] = 72;
1762 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1764 /* Unwind info for specifc trampolines */
1765 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1766 /* We unwind to the original caller, from the stack, since lr is clobbered */
1767 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1768 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1769 save_unwind_info (acfg, symbol, unwind_ops);
1770 mono_free_unwind_info (unwind_ops);
1772 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1773 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1774 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1775 save_unwind_info (acfg, symbol, unwind_ops);
1776 mono_free_unwind_info (unwind_ops);
1778 /* Unwind info for rgctx trampolines */
1779 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1780 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1781 save_unwind_info (acfg, symbol, unwind_ops);
1783 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1784 save_unwind_info (acfg, symbol, unwind_ops);
1785 mono_free_unwind_info (unwind_ops);
1787 /* Unwind info for gsharedvt trampolines */
1788 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1789 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1790 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1791 save_unwind_info (acfg, symbol, unwind_ops);
1792 mono_free_unwind_info (unwind_ops);
1794 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1795 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1796 save_unwind_info (acfg, symbol, unwind_ops);
1797 mono_free_unwind_info (unwind_ops);
1799 /* Unwind info for imt trampolines */
1800 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1801 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1802 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1803 save_unwind_info (acfg, symbol, unwind_ops);
1804 mono_free_unwind_info (unwind_ops);
1806 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1807 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1808 save_unwind_info (acfg, symbol, unwind_ops);
1809 mono_free_unwind_info (unwind_ops);
1810 #elif defined(TARGET_ARM64)
1811 arm64_emit_specific_trampoline_pages (acfg);
1816 * arch_emit_specific_trampoline:
1818 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1819 * two GOT slots which contain the generic trampoline address and the trampoline
1820 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1823 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1826 * The trampolines created here are variations of the specific
1827 * trampolines created in mono_arch_create_specific_trampoline (). The
1829 * - the generic trampoline address is taken from a got slot.
1830 * - the offset of the got slot where the trampoline argument is stored
1831 * is embedded in the instruction stream, and the generic trampoline
1832 * can load the argument by loading the offset, adding it to the
1833 * address of the trampoline to get the address of the got slot, and
1834 * loading the argument from there.
1835 * - all the trampolines should be of the same length.
1837 #if defined(TARGET_AMD64)
1838 /* This should be exactly 8 bytes long */
1840 /* call *<offset>(%rip) */
1842 emit_unset_mode (acfg);
1843 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1844 emit_zero_bytes (acfg, 2);
1846 emit_byte (acfg, '\x41');
1847 emit_byte (acfg, '\xff');
1848 emit_byte (acfg, '\x15');
1849 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1850 emit_zero_bytes (acfg, 1);
1852 #elif defined(TARGET_ARM)
1856 /* This should be exactly 20 bytes long */
1859 ARM_PUSH (code, 0x5fff);
1860 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1861 /* Load the value from the GOT */
1862 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1864 ARM_BLX_REG (code, ARMREG_R1);
1866 g_assert (code - buf == 16);
1869 emit_bytes (acfg, buf, code - buf);
1871 * Only one offset is needed, since the second one would be equal to the
1874 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1875 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1876 #elif defined(TARGET_ARM64)
1877 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1878 #elif defined(TARGET_POWERPC)
1886 * PPC has no ip relative addressing, so we need to compute the address
1887 * of the mscorlib got. That is slow and complex, so instead, we store it
1888 * in the second got slot of every aot image. The caller already computed
1889 * the address of its got and placed it into r30.
1891 emit_unset_mode (acfg);
1892 /* Load mscorlib got address */
1893 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1894 /* Load generic trampoline address */
1895 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1896 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1897 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1898 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1899 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1901 fprintf (acfg->fp, "mtctr 11\n");
1902 /* Load trampoline argument */
1903 /* On ppc, we pass it normally to the generic trampoline */
1904 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1905 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1906 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1907 /* Branch to generic trampoline */
1908 fprintf (acfg->fp, "bctr\n");
1910 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1911 *tramp_size = 10 * 4;
1913 *tramp_size = 9 * 4;
1915 #elif defined(TARGET_X86)
1919 /* Similar to the PPC code above */
1921 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1924 /* Load mscorlib got address */
1925 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1926 /* Push trampoline argument */
1927 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1928 /* Load generic trampoline address */
1929 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1930 /* Branch to generic trampoline */
1931 x86_jump_reg (code, X86_ECX);
1933 emit_bytes (acfg, buf, code - buf);
1936 g_assert (code - buf == *tramp_size);
1938 g_assert_not_reached ();
1943 * arch_emit_unbox_trampoline:
1945 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1946 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1949 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1951 #if defined(TARGET_AMD64)
1956 this_reg = mono_arch_get_this_arg_reg (NULL);
1958 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1960 emit_bytes (acfg, buf, code - buf);
1963 emit_unset_mode (acfg);
1964 fprintf (acfg->fp, "jmp %s\n", call_target);
1966 emit_byte (acfg, '\xe9');
1967 emit_symbol_diff (acfg, call_target, ".", -4);
1969 #elif defined(TARGET_X86)
1976 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1978 emit_bytes (acfg, buf, code - buf);
1981 emit_byte (acfg, '\xe9');
1982 emit_symbol_diff (acfg, call_target, ".", -4);
1983 #elif defined(TARGET_ARM)
1987 if (acfg->thumb_mixed && cfg->compile_llvm) {
1988 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1989 fprintf (acfg->fp, "b %s\n", call_target);
1990 fprintf (acfg->fp, ".arm\n");
1991 fprintf (acfg->fp, ".align 2\n");
1997 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1999 emit_bytes (acfg, buf, code - buf);
2000 /* jump to method */
2001 if (acfg->thumb_mixed && cfg->compile_llvm)
2002 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2004 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2005 #elif defined(TARGET_ARM64)
2006 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2007 #elif defined(TARGET_POWERPC)
2010 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2011 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2013 g_assert_not_reached ();
2018 * arch_emit_static_rgctx_trampoline:
2020 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2021 * two GOT slots which contain the rgctx argument, and the method to jump to.
2022 * TRAMP_SIZE is set to the size of the emitted trampoline.
2023 * These kinds of trampolines cannot be enumerated statically, since there could
2024 * be one trampoline per method instantiation, so we emit the same code for all
2025 * trampolines, and parameterize them using two GOT slots.
2028 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2030 #if defined(TARGET_AMD64)
2031 /* This should be exactly 13 bytes long */
2035 emit_unset_mode (acfg);
2036 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2037 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2039 /* mov <OFFSET>(%rip), %r10 */
2040 emit_byte (acfg, '\x4d');
2041 emit_byte (acfg, '\x8b');
2042 emit_byte (acfg, '\x15');
2043 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2045 /* jmp *<offset>(%rip) */
2046 emit_byte (acfg, '\xff');
2047 emit_byte (acfg, '\x25');
2048 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2050 #elif defined(TARGET_ARM)
2054 /* This should be exactly 24 bytes long */
2057 /* Load rgctx value */
2058 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2059 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2060 /* Load branch addr + branch */
2061 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2062 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2064 g_assert (code - buf == 16);
2067 emit_bytes (acfg, buf, code - buf);
2068 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2069 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2070 #elif defined(TARGET_ARM64)
2071 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2072 #elif defined(TARGET_POWERPC)
2080 * PPC has no ip relative addressing, so we need to compute the address
2081 * of the mscorlib got. That is slow and complex, so instead, we store it
2082 * in the second got slot of every aot image. The caller already computed
2083 * the address of its got and placed it into r30.
2085 emit_unset_mode (acfg);
2086 /* Load mscorlib got address */
2087 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2089 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2090 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2091 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2092 /* Load target address */
2093 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2094 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2095 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2096 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2097 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2098 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2100 fprintf (acfg->fp, "mtctr 11\n");
2101 /* Branch to the target address */
2102 fprintf (acfg->fp, "bctr\n");
2104 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2105 *tramp_size = 11 * 4;
2107 *tramp_size = 9 * 4;
2110 #elif defined(TARGET_X86)
2114 /* Similar to the PPC code above */
2116 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2119 /* Load mscorlib got address */
2120 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2122 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2123 /* Branch to the target address */
2124 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2126 emit_bytes (acfg, buf, code - buf);
2129 g_assert (code - buf == *tramp_size);
2131 g_assert_not_reached ();
2136 * arch_emit_imt_thunk:
2138 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
2139 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2140 * key is the IMT key, and ptr holds the address of a memory location holding
2141 * the address to branch to if the IMT arg matches the key. The array is
2142 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2144 * TRAMP_SIZE is set to the size of the emitted trampoline.
2147 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
2149 #if defined(TARGET_AMD64)
2151 guint8 *labels [16];
2153 guint8 *mov_buf_ptr = mov_buf;
2155 const int kSizeOfMove = 7;
2157 code = buf = (guint8 *)g_malloc (256);
2159 /* FIXME: Optimize this, i.e. use binary search etc. */
2160 /* Maybe move the body into a separate function (slower, but much smaller) */
2162 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2165 emit_unset_mode (acfg);
2166 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2170 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2172 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2175 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2177 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2180 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2181 amd64_jump_code (code, labels [0]);
2184 mono_amd64_patch (labels [2], code);
2185 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2186 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2189 mono_amd64_patch (labels [1], code);
2190 /* Load fail tramp */
2191 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2192 /* Check if there is a fail tramp */
2193 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2195 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2196 /* Jump to fail tramp */
2197 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2200 mono_amd64_patch (labels [3], code);
2201 x86_breakpoint (code);
2204 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2205 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2206 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2207 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2208 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2209 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2211 emit_bytes (acfg, buf, code - buf);
2213 *tramp_size = code - buf + kSizeOfMove;
2217 #elif defined(TARGET_X86)
2219 guint8 *labels [16];
2221 code = buf = g_malloc (256);
2223 /* Allocate a temporary stack slot */
2224 x86_push_reg (code, X86_EAX);
2226 x86_push_reg (code, X86_EAX);
2228 /* Load mscorlib got address */
2229 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2231 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2234 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2236 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2239 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2241 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2244 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2245 x86_jump_code (code, labels [0]);
2248 mono_x86_patch (labels [2], code);
2249 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2250 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2251 /* Save the target address to the temporary stack location */
2252 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2254 x86_pop_reg (code, X86_EAX);
2255 /* Jump to the target address */
2259 mono_x86_patch (labels [1], code);
2260 /* Load fail tramp */
2261 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2262 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2264 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2265 /* Jump to fail tramp */
2266 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2267 x86_pop_reg (code, X86_EAX);
2271 mono_x86_patch (labels [3], code);
2272 x86_breakpoint (code);
2274 emit_bytes (acfg, buf, code - buf);
2276 *tramp_size = code - buf;
2280 #elif defined(TARGET_ARM)
2282 guint8 *code, *code2, *labels [16];
2286 /* The IMT method is in v5 */
2288 /* Need at least two free registers, plus a slot for storing the pc */
2289 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2291 /* Load the parameter from the GOT */
2292 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2293 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2296 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2297 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2299 ARM_B_COND (code, ARMCOND_EQ, 0);
2301 /* End-of-loop check */
2302 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2304 ARM_B_COND (code, ARMCOND_EQ, 0);
2307 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2310 arm_patch (labels [4], labels [1]);
2313 arm_patch (labels [2], code);
2314 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2315 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2316 /* Save it to the third stack slot */
2317 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2318 /* Restore the registers and branch */
2319 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2322 arm_patch (labels [3], code);
2323 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2324 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2325 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2329 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2331 emit_bytes (acfg, buf, code - buf);
2332 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2334 *tramp_size = code - buf + 4;
2335 #elif defined(TARGET_ARM64)
2336 arm64_emit_imt_thunk (acfg, offset, tramp_size);
2337 #elif defined(TARGET_POWERPC)
2339 guint8 *code, *labels [16];
2343 /* Load the mscorlib got address */
2344 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2345 /* Load the parameter from the GOT */
2346 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2347 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2349 /* Load and check key */
2351 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2352 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2354 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2356 /* End-of-loop check */
2357 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2359 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2362 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2365 mono_ppc_patch (labels [4], labels [1]);
2368 mono_ppc_patch (labels [2], code);
2369 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2370 /* r12 now contains the value of the vtable slot */
2371 /* this is not a function descriptor on ppc64 */
2372 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2373 ppc_mtctr (code, ppc_r12);
2374 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2377 mono_ppc_patch (labels [3], code);
2381 *tramp_size = code - buf;
2383 emit_bytes (acfg, buf, code - buf);
2385 g_assert_not_reached ();
2390 #if defined (TARGET_AMD64)
2393 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2396 g_assert (acfg->fp);
2397 emit_unset_mode (acfg);
2399 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2406 * arch_emit_gsharedvt_arg_trampoline:
2408 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2409 * two GOT slots which contain the argument, and the code to jump to.
2410 * TRAMP_SIZE is set to the size of the emitted trampoline.
2411 * These kinds of trampolines cannot be enumerated statically, since there could
2412 * be one trampoline per method instantiation, so we emit the same code for all
2413 * trampolines, and parameterize them using two GOT slots.
2416 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2418 #if defined(TARGET_X86)
2422 /* Similar to the PPC code above */
2424 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2427 /* Load mscorlib got address */
2428 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2430 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2431 /* Branch to the target address */
2432 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2434 emit_bytes (acfg, buf, code - buf);
2437 g_assert (code - buf == *tramp_size);
2438 #elif defined(TARGET_ARM)
2442 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2443 /* Similar to arch_emit_specific_trampoline () */
2446 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2447 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2448 /* Load the arg value from the GOT */
2449 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2450 /* Load the addr from the GOT */
2451 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2453 ARM_BX (code, ARMREG_R1);
2455 g_assert (code - buf == 20);
2458 emit_bytes (acfg, buf, code - buf);
2459 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2460 #elif defined(TARGET_ARM64)
2461 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2462 #elif defined (TARGET_AMD64)
2464 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2465 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2466 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2467 fprintf (acfg->fp, "jmp *%%r11\n");
2471 g_assert_not_reached ();
2475 /* END OF ARCH SPECIFIC CODE */
2478 mono_get_field_token (MonoClassField *field)
2480 MonoClass *klass = field->parent;
2483 for (i = 0; i < klass->field.count; ++i) {
2484 if (field == &klass->fields [i])
2485 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2488 g_assert_not_reached ();
2493 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2497 //printf ("ENCODE: %d 0x%x.\n", value, value);
2500 * Same encoding as the one used in the metadata, extended to handle values
2501 * greater than 0x1fffffff.
2503 if ((value >= 0) && (value <= 127))
2505 else if ((value >= 0) && (value <= 16383)) {
2506 p [0] = 0x80 | (value >> 8);
2507 p [1] = value & 0xff;
2509 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2510 p [0] = (value >> 24) | 0xc0;
2511 p [1] = (value >> 16) & 0xff;
2512 p [2] = (value >> 8) & 0xff;
2513 p [3] = value & 0xff;
2518 p [1] = (value >> 24) & 0xff;
2519 p [2] = (value >> 16) & 0xff;
2520 p [3] = (value >> 8) & 0xff;
2521 p [4] = value & 0xff;
2529 stream_init (MonoDynamicStream *sh)
2532 sh->alloc_size = 4096;
2533 sh->data = (char *)g_malloc (4096);
2535 /* So offsets are > 0 */
2541 make_room_in_stream (MonoDynamicStream *stream, int size)
2543 if (size <= stream->alloc_size)
2546 while (stream->alloc_size <= size) {
2547 if (stream->alloc_size < 4096)
2548 stream->alloc_size = 4096;
2550 stream->alloc_size *= 2;
2553 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2557 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2561 make_room_in_stream (stream, stream->index + len);
2562 memcpy (stream->data + stream->index, data, len);
2563 idx = stream->index;
2564 stream->index += len;
2571 * Add data to the binary blob inside the aot image. Returns the offset inside the
2572 * blob where the data was stored.
2575 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2577 g_assert (!acfg->blob_closed);
2579 if (acfg->blob.alloc_size == 0)
2580 stream_init (&acfg->blob);
2582 return add_stream_data (&acfg->blob, (char*)data, data_len);
2586 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2591 if (acfg->blob.alloc_size == 0)
2592 stream_init (&acfg->blob);
2594 count = acfg->blob.index % align;
2596 /* we assume the stream data will be aligned */
2598 add_stream_data (&acfg->blob, buf, 4 - count);
2600 return add_stream_data (&acfg->blob, (char*)data, data_len);
2603 /* Emit a table of data into the aot image */
2605 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2607 if (acfg->data_outfile) {
2608 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2609 fwrite (data,1, size, acfg->data_outfile);
2610 acfg->datafile_offset += size;
2611 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2612 int align = 8 - size % 8;
2613 acfg->datafile_offset += align;
2614 guint8 align_buf [16];
2615 memset (&align_buf, 0, sizeof (align_buf));
2616 fwrite (align_buf, align, 1, acfg->data_outfile);
2617 } else if (acfg->llvm) {
2618 mono_llvm_emit_aot_data (symbol, data, size);
2620 emit_section_change (acfg, RODATA_SECT, 0);
2621 emit_alignment (acfg, 8);
2622 emit_label (acfg, symbol);
2623 emit_bytes (acfg, data, size);
2628 * emit_offset_table:
2630 * Emit a table of increasing offsets in a compact form using differential encoding.
2631 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2632 * group size, the more compact the table becomes, but the slower it becomes to compute
2633 * a given entry. Returns the size of the table.
2636 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2638 gint32 current_offset;
2639 int i, buf_size, ngroups, index_entry_size;
2641 guint8 *data_p, *data_buf;
2642 guint32 *index_offsets;
2644 ngroups = (noffsets + (group_size - 1)) / group_size;
2646 index_offsets = g_new0 (guint32, ngroups);
2648 buf_size = noffsets * 4;
2649 p = buf = (guint8 *)g_malloc0 (buf_size);
2652 for (i = 0; i < noffsets; ++i) {
2653 //printf ("D: %d -> %d\n", i, offsets [i]);
2654 if ((i % group_size) == 0) {
2655 index_offsets [i / group_size] = p - buf;
2656 /* Emit the full value for these entries */
2657 encode_value (offsets [i], p, &p);
2659 /* The offsets are allowed to be non-increasing */
2660 //g_assert (offsets [i] >= current_offset);
2661 encode_value (offsets [i] - current_offset, p, &p);
2663 current_offset = offsets [i];
2668 if (ngroups && index_offsets [ngroups - 1] < 65000)
2669 index_entry_size = 2;
2671 index_entry_size = 4;
2673 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2674 p = buf = (guint8 *)g_malloc0 (buf_size);
2676 /* Emit the header */
2677 encode_int (noffsets, p, &p);
2678 encode_int (group_size, p, &p);
2679 encode_int (ngroups, p, &p);
2680 encode_int (index_entry_size, p, &p);
2682 /* Emit the index */
2683 for (i = 0; i < ngroups; ++i) {
2684 if (index_entry_size == 2)
2685 encode_int16 (index_offsets [i], p, &p);
2687 encode_int (index_offsets [i], p, &p);
2690 memcpy (p, data_buf, data_p - data_buf);
2691 p += data_p - data_buf;
2693 g_assert (p - buf <= buf_size);
2695 emit_aot_data (acfg, table, symbol, buf, p - buf);
2700 return (int)(p - buf);
2704 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2708 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2712 index = g_hash_table_size (cfg->image_hash);
2713 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2714 g_ptr_array_add (cfg->image_table, image);
2720 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2723 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2725 /* FIXME: Search referenced images as well */
2726 if (!acfg->typespec_classes) {
2727 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2728 for (i = 0; i < len; i++) {
2730 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2731 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2732 if (!is_ok (&error)) {
2733 mono_error_cleanup (&error);
2736 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2739 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2743 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2746 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2749 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2752 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2755 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2760 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2764 if (klass->generic_class) {
2766 g_assert (klass->type_token);
2768 /* Find a typespec for a class if possible */
2769 token = find_typespec_for_class (acfg, klass);
2771 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2772 encode_value (token, p, &p);
2774 MonoClass *gclass = klass->generic_class->container_class;
2775 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2776 static int count = 0;
2779 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2780 encode_klass_ref (acfg, gclass, p, &p);
2781 encode_ginst (acfg, inst, p, &p);
2785 } else if (klass->type_token) {
2786 int iindex = get_image_index (acfg, klass->image);
2788 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2790 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2791 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2793 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2794 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2795 encode_value (get_image_index (acfg, klass->image), p, &p);
2797 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2798 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2799 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2801 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2803 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2804 if (par->gshared_constraint) {
2805 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2806 encode_type (acfg, par->gshared_constraint, p, &p);
2807 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2809 encode_value (klass->byval_arg.type, p, &p);
2810 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2812 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2814 if (!container->is_anonymous) {
2815 encode_value (container->is_method, p, &p);
2816 if (container->is_method)
2817 encode_method_ref (acfg, container->owner.method, p, &p);
2819 encode_klass_ref (acfg, container->owner.klass, p, &p);
2822 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2823 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2824 encode_type (acfg, &klass->byval_arg, p, &p);
2827 g_assert (klass->rank > 0);
2828 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2829 encode_value (klass->rank, p, &p);
2830 encode_klass_ref (acfg, klass->element_class, p, &p);
2838 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2839 * standard metadata encoding.
2842 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2844 gboolean shared = FALSE;
2847 * The encoding of generic instances is large so emit them only once.
2849 if (klass->generic_class) {
2851 g_assert (klass->type_token);
2853 /* Find a typespec for a class if possible */
2854 token = find_typespec_for_class (acfg, klass);
2857 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2862 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2866 buf2 = (guint8 *)g_malloc (1024);
2869 encode_klass_ref_inner (acfg, klass, p, &p);
2870 g_assert (p - buf2 < 1024);
2872 offset = add_to_blob (acfg, buf2, p - buf2);
2875 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2881 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2882 encode_value (offset, p, &p);
2887 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2891 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2893 guint32 token = mono_get_field_token (field);
2896 encode_klass_ref (cfg, field->parent, p, &p);
2897 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2898 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2903 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2908 encode_value (inst->type_argc, p, &p);
2909 for (i = 0; i < inst->type_argc; ++i)
2910 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2915 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2918 MonoGenericInst *inst;
2920 inst = context->class_inst;
2922 g_assert (inst->type_argc);
2923 encode_ginst (acfg, inst, p, &p);
2925 encode_value (0, p, &p);
2927 inst = context->method_inst;
2929 g_assert (inst->type_argc);
2930 encode_ginst (acfg, inst, p, &p);
2932 encode_value (0, p, &p);
2938 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2942 g_assert (t->num_mods == 0);
2943 /* t->attrs can be ignored */
2944 //g_assert (t->attrs == 0);
2947 *p = MONO_TYPE_PINNED;
2951 *p = MONO_TYPE_BYREF;
2959 case MONO_TYPE_VOID:
2960 case MONO_TYPE_BOOLEAN:
2961 case MONO_TYPE_CHAR:
2974 case MONO_TYPE_STRING:
2975 case MONO_TYPE_OBJECT:
2976 case MONO_TYPE_TYPEDBYREF:
2978 case MONO_TYPE_VALUETYPE:
2979 case MONO_TYPE_CLASS:
2980 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2982 case MONO_TYPE_SZARRAY:
2983 encode_klass_ref (acfg, t->data.klass, p, &p);
2986 encode_type (acfg, t->data.type, p, &p);
2988 case MONO_TYPE_GENERICINST: {
2989 MonoClass *gclass = t->data.generic_class->container_class;
2990 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2992 encode_klass_ref (acfg, gclass, p, &p);
2993 encode_ginst (acfg, inst, p, &p);
2996 case MONO_TYPE_ARRAY: {
2997 MonoArrayType *array = t->data.array;
3000 encode_klass_ref (acfg, array->eklass, p, &p);
3001 encode_value (array->rank, p, &p);
3002 encode_value (array->numsizes, p, &p);
3003 for (i = 0; i < array->numsizes; ++i)
3004 encode_value (array->sizes [i], p, &p);
3005 encode_value (array->numlobounds, p, &p);
3006 for (i = 0; i < array->numlobounds; ++i)
3007 encode_value (array->lobounds [i], p, &p);
3011 case MONO_TYPE_MVAR:
3012 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3015 g_assert_not_reached ();
3022 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3028 /* Similar to the metadata encoding */
3029 if (sig->generic_param_count)
3033 if (sig->explicit_this)
3035 flags |= (sig->call_convention & 0x0F);
3039 if (sig->generic_param_count)
3040 encode_value (sig->generic_param_count, p, &p);
3041 encode_value (sig->param_count, p, &p);
3043 encode_type (acfg, sig->ret, p, &p);
3044 for (i = 0; i < sig->param_count; ++i) {
3045 if (sig->sentinelpos == i) {
3046 *p = MONO_TYPE_SENTINEL;
3049 encode_type (acfg, sig->params [i], p, &p);
3055 #define MAX_IMAGE_INDEX 250
3058 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3060 guint32 image_index = get_image_index (acfg, method->klass->image);
3061 guint32 token = method->token;
3062 MonoJumpInfoToken *ji;
3066 * The encoding for most methods is as follows:
3067 * - image index encoded as a leb128
3068 * - token index encoded as a leb128
3069 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3070 * types of method encodings.
3073 /* Mark methods which can't use aot trampolines because they need the further
3074 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3076 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3077 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3078 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3080 if (method->wrapper_type) {
3081 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3083 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3085 encode_value (method->wrapper_type, p, &p);
3087 switch (method->wrapper_type) {
3088 case MONO_WRAPPER_REMOTING_INVOKE:
3089 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3090 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3093 m = mono_marshal_method_from_wrapper (method);
3095 encode_method_ref (acfg, m, p, &p);
3098 case MONO_WRAPPER_PROXY_ISINST:
3099 case MONO_WRAPPER_LDFLD:
3100 case MONO_WRAPPER_LDFLDA:
3101 case MONO_WRAPPER_STFLD:
3102 case MONO_WRAPPER_ISINST: {
3104 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3107 case MONO_WRAPPER_ALLOC: {
3108 /* The GC name is saved once in MonoAotFileInfo */
3109 g_assert (info->d.alloc.alloc_type != -1);
3110 encode_value (info->d.alloc.alloc_type, p, &p);
3113 case MONO_WRAPPER_WRITE_BARRIER: {
3117 case MONO_WRAPPER_STELEMREF: {
3119 encode_value (info->subtype, p, &p);
3120 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3121 encode_value (info->d.virtual_stelemref.kind, p, &p);
3124 case MONO_WRAPPER_UNKNOWN: {
3126 encode_value (info->subtype, p, &p);
3127 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3128 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3129 encode_klass_ref (acfg, method->klass, p, &p);
3130 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3131 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3132 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3133 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3134 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3135 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3136 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3137 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3140 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3142 encode_value (info->subtype, p, &p);
3143 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3144 strcpy ((char*)p, method->name);
3145 p += strlen (method->name) + 1;
3146 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3147 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3149 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3150 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3154 case MONO_WRAPPER_SYNCHRONIZED: {
3157 m = mono_marshal_method_from_wrapper (method);
3159 g_assert (m != method);
3160 encode_method_ref (acfg, m, p, &p);
3163 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3165 encode_value (info->subtype, p, &p);
3167 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3168 encode_value (info->d.element_addr.rank, p, &p);
3169 encode_value (info->d.element_addr.elem_size, p, &p);
3170 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3171 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3173 g_assert_not_reached ();
3177 case MONO_WRAPPER_CASTCLASS: {
3179 encode_value (info->subtype, p, &p);
3182 case MONO_WRAPPER_RUNTIME_INVOKE: {
3184 encode_value (info->subtype, p, &p);
3185 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3186 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3187 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3188 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3191 case MONO_WRAPPER_DELEGATE_INVOKE:
3192 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3193 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3194 if (method->is_inflated) {
3195 /* These wrappers are identified by their class */
3196 encode_value (1, p, &p);
3197 encode_klass_ref (acfg, method->klass, p, &p);
3199 MonoMethodSignature *sig = mono_method_signature (method);
3200 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3202 encode_value (0, p, &p);
3203 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3204 encode_value (info ? info->subtype : 0, p, &p);
3205 encode_signature (acfg, sig, p, &p);
3209 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3211 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3212 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3216 g_assert_not_reached ();
3218 } else if (mono_method_signature (method)->is_inflated) {
3220 * This is a generic method, find the original token which referenced it and
3222 * Obtain the token from information recorded by the JIT.
3224 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3226 image_index = get_image_index (acfg, ji->image);
3227 g_assert (image_index < MAX_IMAGE_INDEX);
3230 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3231 encode_value (image_index, p, &p);
3232 encode_value (token, p, &p);
3234 MonoMethod *declaring;
3235 MonoGenericContext *context = mono_method_get_context (method);
3237 g_assert (method->is_inflated);
3238 declaring = ((MonoMethodInflated*)method)->declaring;
3241 * This might be a non-generic method of a generic instance, which
3242 * doesn't have a token since the reference is generated by the JIT
3243 * like Nullable:Box/Unbox, or by generic sharing.
3245 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3246 /* Encode the klass */
3247 encode_klass_ref (acfg, method->klass, p, &p);
3248 /* Encode the method */
3249 image_index = get_image_index (acfg, method->klass->image);
3250 g_assert (image_index < MAX_IMAGE_INDEX);
3251 g_assert (declaring->token);
3252 token = declaring->token;
3253 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3254 encode_value (image_index, p, &p);
3255 encode_value (token, p, &p);
3256 encode_generic_context (acfg, context, p, &p);
3258 } else if (token == 0) {
3259 /* This might be a method of a constructed type like int[,].Set */
3260 /* Obtain the token from information recorded by the JIT */
3261 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3263 image_index = get_image_index (acfg, ji->image);
3264 g_assert (image_index < MAX_IMAGE_INDEX);
3267 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3268 encode_value (image_index, p, &p);
3269 encode_value (token, p, &p);
3272 g_assert (method->klass->rank);
3274 /* Encode directly */
3275 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3276 encode_klass_ref (acfg, method->klass, p, &p);
3277 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3278 encode_value (0, p, &p);
3279 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3280 encode_value (1, p, &p);
3281 else if (!strcmp (method->name, "Get"))
3282 encode_value (2, p, &p);
3283 else if (!strcmp (method->name, "Address"))
3284 encode_value (3, p, &p);
3285 else if (!strcmp (method->name, "Set"))
3286 encode_value (4, p, &p);
3288 g_assert_not_reached ();
3291 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3293 if (image_index >= MONO_AOT_METHODREF_MIN) {
3294 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3295 encode_value (image_index, p, &p);
3296 encode_value (mono_metadata_token_index (token), p, &p);
3298 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3305 compare_patches (gconstpointer a, gconstpointer b)
3309 i = (*(MonoJumpInfo**)a)->ip.i;
3310 j = (*(MonoJumpInfo**)b)->ip.i;
3321 static G_GNUC_UNUSED char*
3322 patch_to_string (MonoJumpInfo *patch_info)
3326 str = g_string_new ("");
3328 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3330 switch (patch_info->type) {
3331 case MONO_PATCH_INFO_VTABLE:
3332 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3337 g_string_append_printf (str, ")");
3338 return g_string_free (str, FALSE);
3344 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3347 static inline gboolean
3348 is_plt_patch (MonoJumpInfo *patch_info)
3350 switch (patch_info->type) {
3351 case MONO_PATCH_INFO_METHOD:
3352 case MONO_PATCH_INFO_INTERNAL_METHOD:
3353 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3354 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3355 case MONO_PATCH_INFO_RGCTX_FETCH:
3365 * Return the symbol identifying the plt entry PLT_OFFSET.
3368 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3372 * The Apple linker reorganizes object files, so it doesn't like branches to local
3373 * labels, since those have no relocations.
3375 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3377 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3384 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3386 static MonoPltEntry*
3387 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3390 gboolean synchronized = FALSE;
3391 static int synchronized_symbol_idx;
3393 if (!is_plt_patch (patch_info))
3396 if (!acfg->patch_to_plt_entry [patch_info->type])
3397 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3398 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3400 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3402 * Allocate a separate PLT slot for each such patch, since some plt
3403 * entries will refer to the method itself, and some will refer to the
3407 synchronized = TRUE;
3411 MonoJumpInfo *new_ji;
3413 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3415 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3416 res->plt_offset = acfg->plt_offset;
3418 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3419 if (acfg->aot_opts.write_symbols)
3420 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3422 /* Avoid duplicate symbols because we don't cache */
3423 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3425 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3426 synchronized_symbol_idx ++;
3429 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3431 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3433 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3435 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3437 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3438 //mono_print_ji (patch_info); printf ("\n");
3439 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3441 acfg->plt_offset ++;
3450 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3451 * JI could be found if it exists, otherwise allocates a new one.
3454 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3457 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3459 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3461 return got_offset - 1;
3464 got_offset = acfg->llvm_got_offset;
3465 acfg->llvm_got_offset ++;
3467 got_offset = acfg->got_offset;
3468 acfg->got_offset ++;
3471 acfg->stats.got_slots ++;
3472 acfg->stats.got_slot_types [ji->type] ++;
3474 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3475 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3476 g_ptr_array_add (info->got_patches, ji);
3481 /* Add a method to the list of methods which need to be emitted */
3483 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3486 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3487 g_ptr_array_add (acfg->methods, method);
3488 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3489 acfg->nmethods = acfg->methods->len + 1;
3492 if (method->wrapper_type || extra)
3493 g_ptr_array_add (acfg->extra_methods, method);
3497 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3499 /* One instantiation with valuetypes is generated for each async method */
3500 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3507 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3509 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3517 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3521 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3525 index = acfg->method_index;
3526 add_method_with_index (acfg, method, index, extra);
3528 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3530 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3532 acfg->method_index ++;
3538 add_method (MonoAotCompile *acfg, MonoMethod *method)
3540 return add_method_full (acfg, method, FALSE, 0);
3544 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3546 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3547 method = mini_get_shared_method (method);
3548 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3549 /* Use the gsharedvt version */
3550 method = mini_get_shared_method_full (method, TRUE, TRUE);
3552 if (acfg->aot_opts.log_generics)
3553 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3555 add_method_full (acfg, method, TRUE, depth);
3559 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3561 add_extra_method_with_depth (acfg, method, 0);
3565 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3567 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3568 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3569 MonoMethod *wrapper;
3575 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3576 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3579 add_method (acfg, wrapper);
3583 get_runtime_invoke_sig (MonoMethodSignature *sig)
3585 MonoMethodBuilder *mb;
3588 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3589 m = mono_mb_create_method (mb, sig, 16);
3590 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3596 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3598 return mono_marshal_get_runtime_invoke (method, virtual_);
3602 can_marshal_struct (MonoClass *klass)
3604 MonoClassField *field;
3605 gboolean can_marshal = TRUE;
3606 gpointer iter = NULL;
3607 MonoMarshalType *info;
3610 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3613 info = mono_marshal_load_type_info (klass);
3615 /* Only allow a few field types to avoid asserts in the marshalling code */
3616 while ((field = mono_class_get_fields (klass, &iter))) {
3617 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3620 switch (field->type->type) {
3625 case MONO_TYPE_BOOLEAN:
3628 case MONO_TYPE_CHAR:
3636 case MONO_TYPE_STRING:
3638 case MONO_TYPE_VALUETYPE:
3639 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3640 can_marshal = FALSE;
3642 case MONO_TYPE_SZARRAY: {
3643 gboolean has_mspec = FALSE;
3646 for (i = 0; i < info->num_fields; ++i) {
3647 if (info->fields [i].field == field && info->fields [i].mspec)
3652 can_marshal = FALSE;
3656 can_marshal = FALSE;
3662 /* Its hard to compute whenever these can be marshalled or not */
3663 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3670 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3672 /* Create a vtype instantiation */
3673 MonoGenericContext shared_context;
3675 MonoGenericInst *inst;
3676 MonoGenericContainer *container;
3677 MonoClass **constraints;
3680 memset (ctx, 0, sizeof (MonoGenericContext));
3682 if (method->klass->generic_container) {
3683 shared_context = method->klass->generic_container->context;
3684 inst = shared_context.class_inst;
3686 args = g_new0 (MonoType*, inst->type_argc);
3687 for (i = 0; i < inst->type_argc; ++i) {
3688 args [i] = &mono_defaults.int_class->byval_arg;
3690 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3692 if (method->is_generic) {
3693 container = mono_method_get_generic_container (method);
3694 shared_context = container->context;
3695 inst = shared_context.method_inst;
3697 args = g_new0 (MonoType*, inst->type_argc);
3698 for (i = 0; i < container->type_argc; ++i) {
3699 MonoGenericParamInfo *info = &container->type_params [i].info;
3700 gboolean ref_only = FALSE;
3702 if (info && info->constraints) {
3703 constraints = info->constraints;
3705 while (*constraints) {
3706 MonoClass *cklass = *constraints;
3707 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3708 /* Inflaring the method with our vtype would not be valid */
3715 args [i] = &mono_defaults.object_class->byval_arg;
3717 args [i] = &mono_defaults.int_class->byval_arg;
3719 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3724 add_wrappers (MonoAotCompile *acfg)
3726 MonoMethod *method, *m;
3728 MonoMethodSignature *sig, *csig;
3732 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3733 * so there is only one wrapper of a given type, or inlining their contents into their
3736 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3739 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3740 gboolean skip = FALSE;
3742 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3743 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3745 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3746 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3747 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3750 /* Skip methods which can not be handled by get_runtime_invoke () */
3751 sig = mono_method_signature (method);
3754 if ((sig->ret->type == MONO_TYPE_PTR) ||
3755 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3757 if (mono_class_is_open_constructed_type (sig->ret))
3760 for (j = 0; j < sig->param_count; j++) {
3761 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3763 if (mono_class_is_open_constructed_type (sig->params [j]))
3767 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3768 if (!mono_class_is_contextbound (method->klass)) {
3769 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3770 gboolean has_nullable = FALSE;
3772 for (j = 0; j < sig->param_count; j++) {
3773 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3774 has_nullable = TRUE;
3777 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3778 /* Supported by the dynamic runtime-invoke wrapper */
3782 mono_arch_dyn_call_free (info);
3786 if (acfg->aot_opts.llvm_only)
3787 /* Supported by the gsharedvt based runtime-invoke wrapper */
3791 //printf ("%s\n", mono_method_full_name (method, TRUE));
3792 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3796 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3799 /* Runtime invoke wrappers */
3801 /* void runtime-invoke () [.cctor] */
3802 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3803 csig->ret = &mono_defaults.void_class->byval_arg;
3804 add_method (acfg, get_runtime_invoke_sig (csig));
3806 /* void runtime-invoke () [Finalize] */
3807 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3809 csig->ret = &mono_defaults.void_class->byval_arg;
3810 add_method (acfg, get_runtime_invoke_sig (csig));
3812 /* void runtime-invoke (string) [exception ctor] */
3813 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3815 csig->ret = &mono_defaults.void_class->byval_arg;
3816 csig->params [0] = &mono_defaults.string_class->byval_arg;
3817 add_method (acfg, get_runtime_invoke_sig (csig));
3819 /* void runtime-invoke (string, string) [exception ctor] */
3820 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3822 csig->ret = &mono_defaults.void_class->byval_arg;
3823 csig->params [0] = &mono_defaults.string_class->byval_arg;
3824 csig->params [1] = &mono_defaults.string_class->byval_arg;
3825 add_method (acfg, get_runtime_invoke_sig (csig));
3827 /* string runtime-invoke () [Exception.ToString ()] */
3828 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3830 csig->ret = &mono_defaults.string_class->byval_arg;
3831 add_method (acfg, get_runtime_invoke_sig (csig));
3833 /* void runtime-invoke (string, Exception) [exception ctor] */
3834 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3836 csig->ret = &mono_defaults.void_class->byval_arg;
3837 csig->params [0] = &mono_defaults.string_class->byval_arg;
3838 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3839 add_method (acfg, get_runtime_invoke_sig (csig));
3841 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3842 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3844 csig->ret = &(mono_class_load_from_name (
3845 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3846 csig->params [0] = &mono_defaults.string_class->byval_arg;
3847 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3848 add_method (acfg, get_runtime_invoke_sig (csig));
3850 /* runtime-invoke used by finalizers */
3851 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3853 /* This is used by mono_runtime_capture_context () */
3854 method = mono_get_context_capture_method ();
3856 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3858 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3859 if (!acfg->aot_opts.llvm_only)
3860 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3863 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3864 if (acfg->aot_opts.llvm_only) {
3867 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3868 for (variants = 0; variants < 4; ++variants) {
3869 for (i = 0; i < 16; ++i) {
3870 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3871 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3879 add_method (acfg, mono_marshal_get_stelemref ());
3881 if (MONO_ARCH_HAVE_TLS_GET) {
3882 /* Managed Allocators */
3883 nallocators = mono_gc_get_managed_allocator_types ();
3884 for (i = 0; i < nallocators; ++i) {
3885 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3886 add_method (acfg, m);
3887 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3888 add_method (acfg, m);
3892 /* write barriers */
3893 if (mono_gc_is_moving ()) {
3894 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3895 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3898 /* Stelemref wrappers */
3900 MonoMethod **wrappers;
3903 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3904 for (i = 0; i < nwrappers; ++i)
3905 add_method (acfg, wrappers [i]);
3909 /* castclass_with_check wrapper */
3910 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3911 /* isinst_with_check wrapper */
3912 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3914 /* JIT icall wrappers */
3915 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3916 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3920 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3921 * we use the original method instead at runtime.
3922 * Since full-aot doesn't support remoting, this is not a problem.
3925 /* remoting-invoke wrappers */
3926 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3928 MonoMethodSignature *sig;
3930 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3931 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3932 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3934 sig = mono_method_signature (method);
3936 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3937 m = mono_marshal_get_remoting_invoke_with_check (method);
3939 add_method (acfg, m);
3944 /* delegate-invoke wrappers */
3945 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3948 MonoCustomAttrInfo *cattr;
3950 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3951 klass = mono_class_get_checked (acfg->image, token, &error);
3954 mono_error_cleanup (&error);
3958 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3961 if (!klass->generic_container) {
3962 method = mono_get_delegate_invoke (klass);
3964 m = mono_marshal_get_delegate_invoke (method, NULL);
3966 add_method (acfg, m);
3968 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3970 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3972 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3974 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3976 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3977 if (!is_ok (&error)) {
3978 mono_error_cleanup (&error);
3985 for (j = 0; j < cattr->num_attrs; ++j)
3986 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3988 if (j < cattr->num_attrs) {
3990 MonoMethod *wrapper;
3991 MonoMethod *del_invoke;
3993 /* Add wrappers needed by mono_ftnptr_to_delegate () */
3994 invoke = mono_get_delegate_invoke (klass);
3995 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
3996 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
3997 add_method (acfg, wrapper);
3998 add_method (acfg, del_invoke);
4001 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
4003 MonoGenericContext ctx;
4004 MonoMethod *inst, *gshared;
4007 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4010 method = mono_get_delegate_invoke (klass);
4011 create_gsharedvt_inst (acfg, method, &ctx);
4013 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4014 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4016 m = mono_marshal_get_delegate_invoke (inst, NULL);
4017 g_assert (m->is_inflated);
4019 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4020 add_extra_method (acfg, gshared);
4023 method = mono_get_delegate_begin_invoke (klass);
4024 create_gsharedvt_inst (acfg, method, &ctx);
4026 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4027 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4029 m = mono_marshal_get_delegate_begin_invoke (inst);
4030 g_assert (m->is_inflated);
4032 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4033 add_extra_method (acfg, gshared);
4036 method = mono_get_delegate_end_invoke (klass);
4037 create_gsharedvt_inst (acfg, method, &ctx);
4039 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4040 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4042 m = mono_marshal_get_delegate_end_invoke (inst);
4043 g_assert (m->is_inflated);
4045 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4046 add_extra_method (acfg, gshared);
4051 /* array access wrappers */
4052 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4056 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4057 klass = mono_class_get_checked (acfg->image, token, &error);
4060 mono_error_cleanup (&error);
4064 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4065 MonoMethod *m, *wrapper;
4067 /* Add runtime-invoke wrappers too */
4069 m = mono_class_get_method_from_name (klass, "Get", -1);
4071 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4072 add_extra_method (acfg, wrapper);
4073 if (!acfg->aot_opts.llvm_only)
4074 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4076 m = mono_class_get_method_from_name (klass, "Set", -1);
4078 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4079 add_extra_method (acfg, wrapper);
4080 if (!acfg->aot_opts.llvm_only)
4081 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4085 /* Synchronized wrappers */
4086 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4088 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4089 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4090 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4092 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4093 if (method->is_generic) {
4095 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
4097 MonoGenericContext ctx;
4098 MonoMethod *inst, *gshared, *m;
4101 * Create a generic wrapper for a generic instance, and AOT that.
4103 create_gsharedvt_inst (acfg, method, &ctx);
4104 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4105 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4106 m = mono_marshal_get_synchronized_wrapper (inst);
4107 g_assert (m->is_inflated);
4108 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4109 add_method (acfg, gshared);
4111 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4116 /* pinvoke wrappers */
4117 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4120 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4122 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4123 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4125 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4126 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4127 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4131 /* native-to-managed wrappers */
4132 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4135 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4136 MonoCustomAttrInfo *cattr;
4139 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4140 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4143 * Only generate native-to-managed wrappers for methods which have an
4144 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4145 * name to avoid defining a new assembly to contain it.
4147 cattr = mono_custom_attrs_from_method_checked (method, &error);
4148 if (!is_ok (&error)) {
4149 char *name = mono_method_get_full_name (method);
4150 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4155 for (j = 0; j < cattr->num_attrs; ++j)
4156 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4158 if (j < cattr->num_attrs) {
4159 MonoCustomAttrEntry *e = &cattr->attrs [j];
4160 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4161 const char *p = (const char*)e->data;
4163 int slen, num_named, named_type;
4167 char *export_name = NULL;
4168 MonoMethod *wrapper;
4170 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4171 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4172 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4173 mono_method_full_name (method, TRUE));
4177 g_assert (sig->param_count == 1);
4178 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4181 * Decode the cattr manually since we can't create objects
4182 * during aot compilation.
4188 /* From load_cattr_value () in reflection.c */
4189 slen = mono_metadata_decode_value (p, &p);
4190 n = (char *)g_memdup (p, slen + 1);
4192 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4194 mono_error_assert_ok (&error);
4197 klass = mono_class_from_mono_type (t);
4198 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4202 num_named = read16 (p);
4205 g_assert (num_named < 2);
4206 if (num_named == 1) {
4210 /* parse ExportSymbol attribute */
4212 named_type = *named;
4214 /* data_type = *named; */
4217 name_len = mono_metadata_decode_blob_size (named, &named);
4218 name = (char *)g_malloc (name_len + 1);
4219 memcpy (name, named, name_len);
4220 name [name_len] = 0;
4223 g_assert (named_type == 0x54);
4224 g_assert (!strcmp (name, "ExportSymbol"));
4226 /* load_cattr_value (), string case */
4227 g_assert (*named != (char)0xff);
4228 slen = mono_metadata_decode_value (named, &named);
4229 export_name = (char *)g_malloc (slen + 1);
4230 memcpy (export_name, named, slen);
4231 export_name [slen] = 0;
4235 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4236 add_method (acfg, wrapper);
4238 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4243 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4244 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4245 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4249 /* StructureToPtr/PtrToStructure wrappers */
4250 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4254 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4255 klass = mono_class_get_checked (acfg->image, token, &error);
4258 mono_error_cleanup (&error);
4262 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4263 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4264 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4265 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4271 has_type_vars (MonoClass *klass)
4273 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4276 return has_type_vars (klass->element_class);
4277 if (klass->generic_class) {
4278 MonoGenericContext *context = &klass->generic_class->context;
4279 if (context->class_inst) {
4282 for (i = 0; i < context->class_inst->type_argc; ++i)
4283 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4287 if (klass->generic_container)
4293 is_vt_inst (MonoGenericInst *inst)
4297 for (i = 0; i < inst->type_argc; ++i) {
4298 MonoType *t = inst->type_argv [i];
4299 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4306 method_has_type_vars (MonoMethod *method)
4308 if (has_type_vars (method->klass))
4311 if (method->is_inflated) {
4312 MonoGenericContext *context = mono_method_get_context (method);
4313 if (context->method_inst) {
4316 for (i = 0; i < context->method_inst->type_argc; ++i)
4317 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4325 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4327 return opts->mode == MONO_AOT_MODE_FULL;
4330 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4333 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4335 /* This might lead to a huge code blowup so only do it if neccesary */
4336 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !force)
4339 add_generic_class_with_depth (acfg, klass, 0, ref);
4343 check_type_depth (MonoType *t, int depth)
4351 case MONO_TYPE_GENERICINST: {
4352 MonoGenericClass *gklass = t->data.generic_class;
4353 MonoGenericInst *ginst = gklass->context.class_inst;
4356 for (i = 0; i < ginst->type_argc; ++i) {
4357 if (check_type_depth (ginst->type_argv [i], depth + 1))
4371 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4374 * add_generic_class:
4376 * Add all methods of a generic class.
4379 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4382 MonoClassField *field;
4384 gboolean use_gsharedvt = FALSE;
4386 if (!acfg->ginst_hash)
4387 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4389 mono_class_init (klass);
4391 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4394 if (has_type_vars (klass))
4397 if (!klass->generic_class && !klass->rank)
4400 if (mono_class_has_failure (klass))
4403 if (!acfg->ginst_hash)
4404 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4406 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4409 if (check_type_depth (&klass->byval_arg, 0))
4412 if (acfg->aot_opts.log_generics)
4413 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4415 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4418 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4419 * Enable this only for some classes since gsharedvt might not support all methods.
4421 if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->image == mono_defaults.corlib && klass->generic_class && klass->generic_class->context.class_inst && is_vt_inst (klass->generic_class->context.class_inst) &&
4422 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4423 use_gsharedvt = TRUE;
4426 while ((method = mono_class_get_methods (klass, &iter))) {
4427 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4429 * This is partial sharing, and we can't handle it yet
4434 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4436 add_types_from_method_header (acfg, method);
4440 if (method->is_generic)
4445 * FIXME: Instances which are referenced by these methods are not added,
4446 * for example Array.Resize<int> for List<int>.Add ().
4448 add_extra_method_with_depth (acfg, method, depth + 1);
4452 while ((field = mono_class_get_fields (klass, &iter))) {
4453 if (field->type->type == MONO_TYPE_GENERICINST)
4454 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4457 if (klass->delegate) {
4458 method = mono_get_delegate_invoke (klass);
4460 method = mono_marshal_get_delegate_invoke (method, NULL);
4462 if (acfg->aot_opts.log_generics)
4463 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4465 add_method (acfg, method);
4468 /* Add superclasses */
4470 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4473 * For ICollection<T>, add instances of the helper methods
4474 * in Array, since a T[] could be cast to ICollection<T>.
4476 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4477 (!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"))) {
4478 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4479 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4483 if (!strcmp (klass->name, "IEnumerator`1"))
4484 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4486 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4488 /* Add the T[]/InternalEnumerator class */
4489 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4494 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4495 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4499 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4500 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4501 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4505 while ((method = mono_class_get_methods (array_class, &iter))) {
4506 if (strstr (method->name, name_prefix)) {
4507 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4509 add_extra_method_with_depth (acfg, m, depth);
4513 g_free (name_prefix);
4516 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4517 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4519 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4520 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4521 MonoGenericContext ctx;
4522 MonoType *args [16];
4524 memset (&ctx, 0, sizeof (ctx));
4526 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4528 args [0] = &tclass->byval_arg;
4529 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4531 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4532 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4534 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4535 MonoClass *gcomparer_inst;
4536 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4537 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4538 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4540 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4544 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4545 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4547 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4548 MonoClass *iface, *gcomparer, *iface_inst;
4549 MonoGenericContext ctx;
4550 MonoType *args [16];
4552 memset (&ctx, 0, sizeof (ctx));
4554 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4556 args [0] = &tclass->byval_arg;
4557 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4559 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4560 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4562 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4563 MonoClass *gcomparer_inst;
4566 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4567 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4568 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4569 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4573 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4574 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4575 MonoClass *enum_comparer;
4576 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4577 MonoGenericContext ctx;
4578 MonoType *args [16];
4580 if (mono_class_is_enum (tclass)) {
4581 MonoClass *enum_comparer_inst;
4584 memset (&ctx, 0, sizeof (ctx));
4585 args [0] = &tclass->byval_arg;
4586 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4588 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4589 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4590 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4591 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4595 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4596 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4597 MonoClass *comparer;
4598 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4599 MonoGenericContext ctx;
4600 MonoType *args [16];
4602 if (mono_class_is_enum (tclass)) {
4603 MonoClass *comparer_inst;
4606 memset (&ctx, 0, sizeof (ctx));
4607 args [0] = &tclass->byval_arg;
4608 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4610 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4611 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4612 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4613 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4619 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4622 MonoGenericContext ctx;
4623 MonoType *args [16];
4625 if (acfg->aot_opts.no_instances)
4628 memset (&ctx, 0, sizeof (ctx));
4630 for (i = 0; i < ninsts; ++i) {
4632 MonoClass *generic_inst;
4633 args [0] = insts [i];
4634 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4635 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4636 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4637 add_generic_class (acfg, generic_inst, force, "");
4642 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4645 MonoMethodHeader *header;
4646 MonoMethodSignature *sig;
4649 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4651 sig = mono_method_signature (method);
4654 for (j = 0; j < sig->param_count; ++j)
4655 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4656 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4659 header = mono_method_get_header_checked (method, &error);
4662 for (j = 0; j < header->num_locals; ++j)
4663 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4664 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4665 mono_metadata_free_mh (header);
4667 mono_error_cleanup (&error); /* FIXME report the error */
4673 * add_generic_instances:
4675 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4678 add_generic_instances (MonoAotCompile *acfg)
4683 MonoGenericContext *context;
4685 if (acfg->aot_opts.no_instances)
4688 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4690 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4691 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4694 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4695 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4696 mono_error_cleanup (&error);
4700 if (method->klass->image != acfg->image)
4703 context = mono_method_get_context (method);
4705 if (context && ((context->class_inst && context->class_inst->is_open)))
4709 * For open methods, create an instantiation which can be passed to the JIT.
4710 * FIXME: Handle class_inst as well.
4712 if (context && context->method_inst && context->method_inst->is_open) {
4714 MonoGenericContext shared_context;
4715 MonoGenericInst *inst;
4716 MonoType **type_argv;
4718 MonoMethod *declaring_method;
4719 gboolean supported = TRUE;
4721 /* Check that the context doesn't contain open constructed types */
4722 if (context->class_inst) {
4723 inst = context->class_inst;
4724 for (i = 0; i < inst->type_argc; ++i) {
4725 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)
4727 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4731 if (context->method_inst) {
4732 inst = context->method_inst;
4733 for (i = 0; i < inst->type_argc; ++i) {
4734 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)
4736 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4744 memset (&shared_context, 0, sizeof (MonoGenericContext));
4746 inst = context->class_inst;
4748 type_argv = g_new0 (MonoType*, inst->type_argc);
4749 for (i = 0; i < inst->type_argc; ++i) {
4750 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)
4751 type_argv [i] = &mono_defaults.object_class->byval_arg;
4753 type_argv [i] = inst->type_argv [i];
4756 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4760 inst = context->method_inst;
4762 type_argv = g_new0 (MonoType*, inst->type_argc);
4763 for (i = 0; i < inst->type_argc; ++i) {
4764 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)
4765 type_argv [i] = &mono_defaults.object_class->byval_arg;
4767 type_argv [i] = inst->type_argv [i];
4770 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4774 if (method->is_generic || method->klass->generic_container)
4775 declaring_method = method;
4777 declaring_method = mono_method_get_declaring_generic_method (method);
4779 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4780 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4784 * If the method is fully sharable, it was already added in place of its
4785 * generic definition.
4787 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4791 * FIXME: Partially shared methods are not shared here, so we end up with
4792 * many identical methods.
4794 add_extra_method (acfg, method);
4797 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4801 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4803 klass = mono_class_get_checked (acfg->image, token, &error);
4804 if (!klass || klass->rank) {
4805 mono_error_cleanup (&error);
4809 add_generic_class (acfg, klass, FALSE, "typespec");
4812 /* Add types of args/locals */
4813 for (i = 0; i < acfg->methods->len; ++i) {
4814 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4815 add_types_from_method_header (acfg, method);
4818 if (acfg->image == mono_defaults.corlib) {
4820 MonoType *insts [256];
4823 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4824 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4825 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4826 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4827 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4828 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4829 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4830 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4831 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4832 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4833 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4834 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4836 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4837 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4839 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4840 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4842 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4844 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4846 MonoClass *enum_comparer;
4847 MonoType *insts [16];
4851 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4852 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4853 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4854 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4855 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4856 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4859 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4860 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4861 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4864 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4865 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4866 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4868 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4870 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4871 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4872 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4875 /* Add instances of the array generic interfaces for primitive types */
4876 /* This will add instances of the InternalArray_ helper methods in Array too */
4877 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4879 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4881 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4883 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4885 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4887 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4890 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4891 * used for all instances of GetGenericValueImpl by the AOT runtime.
4894 MonoGenericContext ctx;
4895 MonoType *args [16];
4896 MonoMethod *get_method;
4897 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4899 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4903 memset (&ctx, 0, sizeof (ctx));
4904 args [0] = &mono_defaults.object_class->byval_arg;
4905 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4906 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4907 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4911 /* Same for CompareExchange<T>/Exchange<T> */
4913 MonoGenericContext ctx;
4914 MonoType *args [16];
4916 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4917 gpointer iter = NULL;
4919 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4920 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4922 memset (&ctx, 0, sizeof (ctx));
4923 args [0] = &mono_defaults.object_class->byval_arg;
4924 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4925 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4926 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4931 /* Same for Volatile.Read/Write<T> */
4933 MonoGenericContext ctx;
4934 MonoType *args [16];
4936 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4937 gpointer iter = NULL;
4939 if (volatile_klass) {
4940 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4941 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4943 memset (&ctx, 0, sizeof (ctx));
4944 args [0] = &mono_defaults.object_class->byval_arg;
4945 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4946 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4947 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4953 /* object[] accessor wrappers. */
4954 for (i = 1; i < 4; ++i) {
4955 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
4958 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
4961 m = mono_marshal_get_array_accessor_wrapper (m);
4962 add_extra_method (acfg, m);
4964 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
4967 m = mono_marshal_get_array_accessor_wrapper (m);
4968 add_extra_method (acfg, m);
4970 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
4973 m = mono_marshal_get_array_accessor_wrapper (m);
4974 add_extra_method (acfg, m);
4980 * is_direct_callable:
4982 * Return whenever the method identified by JI is directly callable without
4983 * going through the PLT.
4986 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4988 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4989 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4991 gboolean direct_callable = TRUE;
4993 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4994 direct_callable = FALSE;
4995 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4996 // FIXME: Maybe call the wrapper directly ?
4997 direct_callable = FALSE;
4999 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5000 /* Disable this so all calls go through load_method (), see the
5001 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5002 * mono_debugger_agent_init ().
5004 direct_callable = FALSE;
5007 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5008 /* sgen does some initialization when the allocator method is created */
5009 direct_callable = FALSE;
5010 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5011 /* we don't know at compile time whether sgen is concurrent or not */
5012 direct_callable = FALSE;
5014 if (direct_callable)
5017 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5018 if (acfg->aot_opts.direct_pinvoke)
5020 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5021 if (acfg->aot_opts.direct_icalls)
5029 #ifdef MONO_ARCH_AOT_SUPPORTED
5031 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5033 MonoImage *image = method->klass->image;
5034 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5035 MonoTableInfo *tables = image->tables;
5036 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5037 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5038 guint32 im_cols [MONO_IMPLMAP_SIZE];
5041 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5045 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5048 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5050 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5053 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5055 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5061 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5068 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5070 if (a->native_offset == b->native_offset)
5071 return a->il_offset - b->il_offset;
5073 return a->native_offset - b->native_offset;
5077 * compute_line_numbers:
5079 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5082 static MonoDebugSourceLocation**
5083 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5085 MonoDebugMethodInfo *minfo;
5086 MonoDebugLineNumberEntry *ln_array;
5087 MonoDebugSourceLocation *loc;
5088 int i, prev_line, prev_il_offset;
5089 int *native_to_il_offset = NULL;
5090 MonoDebugSourceLocation **res;
5093 minfo = mono_debug_lookup_method (method);
5096 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5097 if (debug_info->code_size != code_size)
5100 g_assert (code_size);
5102 /* Compute the native->IL offset mapping */
5104 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5105 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5107 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5109 native_to_il_offset = g_new0 (int, code_size + 1);
5111 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5113 MonoDebugLineNumberEntry *lne = &ln_array [i];
5116 for (j = 0; j < lne->native_offset; ++j)
5117 native_to_il_offset [j] = -1;
5120 if (i < debug_info->num_line_numbers - 1) {
5121 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5123 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5124 native_to_il_offset [j] = lne->il_offset;
5126 for (j = lne->native_offset; j < code_size; ++j)
5127 native_to_il_offset [j] = lne->il_offset;
5132 /* Compute the native->line number mapping */
5133 res = g_new0 (MonoDebugSourceLocation*, code_size);
5134 prev_il_offset = -1;
5137 for (i = 0; i < code_size; ++i) {
5138 int il_offset = native_to_il_offset [i];
5140 if (il_offset == -1 || il_offset == prev_il_offset)
5142 prev_il_offset = il_offset;
5143 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5144 if (!(loc && loc->source_file))
5146 if (loc->row == prev_line) {
5147 mono_debug_symfile_free_location (loc);
5150 prev_line = loc->row;
5151 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5153 /* This will cover the prolog too */
5163 get_file_index (MonoAotCompile *acfg, const char *source_file)
5167 // FIXME: Free these
5168 if (!acfg->dwarf_ln_filenames)
5169 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5170 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5172 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5173 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5174 emit_unset_mode (acfg);
5175 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5187 * emit_and_reloc_code:
5189 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5190 * is true, calls are made through the GOT too. This is used for emitting trampolines
5191 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5192 * since trampolines are needed to make PTL work.
5195 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5197 int i, pindex, start_index;
5199 MonoJumpInfo *patch_info;
5200 MonoDebugSourceLocation **locs = NULL;
5201 gboolean skip, prologue_end = FALSE;
5202 #ifdef MONO_ARCH_AOT_SUPPORTED
5203 gboolean direct_call, external_call;
5205 const char *direct_call_target = 0;
5206 const char *direct_pinvoke;
5209 if (acfg->gas_line_numbers && method && debug_info) {
5210 locs = compute_line_numbers (method, code_len, debug_info);
5212 int findex = get_file_index (acfg, "<unknown>");
5213 emit_unset_mode (acfg);
5214 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5218 /* Collect and sort relocations */
5219 patches = g_ptr_array_new ();
5220 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5221 g_ptr_array_add (patches, patch_info);
5222 g_ptr_array_sort (patches, compare_patches);
5225 for (i = 0; i < code_len; i += INST_LEN) {
5227 for (pindex = start_index; pindex < patches->len; ++pindex) {
5228 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5229 if (patch_info->ip.i >= i)
5233 if (locs && locs [i]) {
5234 MonoDebugSourceLocation *loc = locs [i];
5236 const char *options;
5238 findex = get_file_index (acfg, loc->source_file);
5239 emit_unset_mode (acfg);
5241 options = " prologue_end";
5244 prologue_end = TRUE;
5245 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5246 mono_debug_symfile_free_location (loc);
5250 #ifdef MONO_ARCH_AOT_SUPPORTED
5251 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5252 start_index = pindex;
5254 switch (patch_info->type) {
5255 case MONO_PATCH_INFO_NONE:
5257 case MONO_PATCH_INFO_GOT_OFFSET: {
5260 arch_emit_got_offset (acfg, code + i, &code_size);
5261 i += code_size - INST_LEN;
5263 patch_info->type = MONO_PATCH_INFO_NONE;
5266 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5267 int code_size, index;
5268 char *selector = (char *)patch_info->data.target;
5270 if (!acfg->objc_selector_to_index)
5271 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5272 if (!acfg->objc_selectors)
5273 acfg->objc_selectors = g_ptr_array_new ();
5274 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5278 index = acfg->objc_selector_index;
5279 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5280 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5281 acfg->objc_selector_index ++;
5284 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5285 i += code_size - INST_LEN;
5287 patch_info->type = MONO_PATCH_INFO_NONE;
5292 * If this patch is a call, try emitting a direct call instead of
5293 * through a PLT entry. This is possible if the called method is in
5294 * the same assembly and requires no initialization.
5296 direct_call = FALSE;
5297 external_call = FALSE;
5298 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5299 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5300 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5301 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5303 direct_call_target = callee_cfg->asm_symbol;
5304 patch_info->type = MONO_PATCH_INFO_NONE;
5305 acfg->stats.direct_calls ++;
5308 acfg->stats.all_calls ++;
5309 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5310 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5311 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5312 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5314 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5315 if (direct_pinvoke) {
5317 g_assert (strlen (direct_pinvoke) < 1000);
5318 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5321 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5322 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5323 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5324 /* Call to a C function implementing a jit icall */
5326 external_call = TRUE;
5327 g_assert (strlen (sym) < 1000);
5328 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5330 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5331 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5332 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5333 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5334 /* Call to a jit icall without a wrapper */
5336 external_call = TRUE;
5337 g_assert (strlen (sym) < 1000);
5338 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5343 patch_info->type = MONO_PATCH_INFO_NONE;
5344 acfg->stats.direct_calls ++;
5347 if (!got_only && !direct_call) {
5348 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5350 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5352 direct_call_target = plt_entry->symbol;
5354 /* Nullify the patch */
5355 patch_info->type = MONO_PATCH_INFO_NONE;
5356 plt_entry->jit_used = TRUE;
5363 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5364 i += call_size - INST_LEN;
5368 got_slot = get_got_offset (acfg, FALSE, patch_info);
5370 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5371 i += code_size - INST_LEN;
5377 #endif /* MONO_ARCH_AOT_SUPPORTED */
5380 /* Find next patch */
5382 for (pindex = start_index; pindex < patches->len; ++pindex) {
5383 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5384 if (patch_info->ip.i >= i)
5388 /* Try to emit multiple bytes at once */
5389 if (pindex < patches->len && patch_info->ip.i > i) {
5392 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5393 if (locs && locs [limit])
5397 emit_code_bytes (acfg, code + i, limit - i);
5398 i = limit - INST_LEN;
5400 emit_code_bytes (acfg, code + i, INST_LEN);
5405 g_ptr_array_free (patches, TRUE);
5412 * Return a modified version of S which only includes characters permissible in symbols.
5415 sanitize_symbol (MonoAotCompile *acfg, char *s)
5417 gboolean process = FALSE;
5426 for (i = 0; i < len; ++i)
5427 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5432 gs = g_string_sized_new (len);
5433 for (i = 0; i < len; ++i) {
5435 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5436 g_string_append_c (gs, c);
5437 } else if (c > 0x7f) {
5438 /* multi-byte utf8 */
5439 g_string_append_printf (gs, "_0x%x", c);
5442 while (c >> 6 == 0x2) {
5443 g_string_append_printf (gs, "%x", c);
5447 g_string_append_printf (gs, "_");
5450 g_string_append_c (gs, '_');
5454 res = mono_mempool_strdup (acfg->mempool, gs->str);
5455 g_string_free (gs, TRUE);
5460 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5462 char *name1, *name2, *cached;
5463 int i, j, len, count;
5464 MonoMethod *cached_method;
5466 name1 = mono_method_full_name (method, TRUE);
5469 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5470 if ((!prefix || !*prefix) && name1 [0] == 'L')
5474 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5475 char adjustedPrefix [MAX_SYMBOL_SIZE];
5476 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5479 len = strlen (name1);
5480 name2 = (char *)malloc (strlen (prefix) + len + 16);
5481 memcpy (name2, prefix, strlen (prefix));
5482 j = strlen (prefix);
5483 for (i = 0; i < len; ++i) {
5484 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5486 } else if (isalnum (name1 [i])) {
5487 name2 [j ++] = name1 [i];
5488 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5490 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5493 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5503 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5504 if (!(cached_method && cached_method != method))
5506 sprintf (name2 + j, "_%d", count);
5510 cached = g_strdup (name2);
5511 g_hash_table_insert (cache, cached, method);
5517 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5522 char *debug_sym = NULL;
5523 char *symbol = NULL;
5524 int func_alignment = AOT_FUNC_ALIGNMENT;
5527 method = cfg->orig_method;
5528 code = cfg->native_code;
5530 method_index = get_method_index (acfg, method);
5531 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5533 /* Make the labels local */
5534 emit_section_change (acfg, ".text", 0);
5535 emit_alignment_code (acfg, func_alignment);
5537 if (acfg->global_symbols && acfg->need_no_dead_strip)
5538 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5540 emit_label (acfg, cfg->asm_symbol);
5542 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5544 * Write a C style symbol for every method, this has two uses:
5545 * - it works on platforms where the dwarf debugging info is not
5547 * - it allows the setting of breakpoints of aot-ed methods.
5549 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5550 cfg->asm_debug_symbol = g_strdup (debug_sym);
5552 if (acfg->need_no_dead_strip)
5553 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5554 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5555 emit_label (acfg, debug_sym);
5558 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5560 /* Emit a global symbol for the method */
5561 emit_global_inner (acfg, export_name, TRUE);
5562 emit_label (acfg, export_name);
5565 if (cfg->verbose_level > 0)
5566 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5568 acfg->stats.code_size += cfg->code_len;
5570 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5572 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 ()));
5576 if (acfg->aot_opts.write_symbols) {
5578 emit_symbol_size (acfg, debug_sym, ".");
5580 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5584 emit_label (acfg, symbol);
5591 * Encode PATCH_INFO into its disk representation.
5594 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5598 switch (patch_info->type) {
5599 case MONO_PATCH_INFO_NONE:
5601 case MONO_PATCH_INFO_IMAGE:
5602 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5604 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5605 case MONO_PATCH_INFO_JIT_TLS_ID:
5606 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5607 case MONO_PATCH_INFO_GC_NURSERY_START:
5608 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5610 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5611 encode_value (patch_info->data.index, p, &p);
5613 case MONO_PATCH_INFO_METHOD_REL:
5614 encode_value ((gint)patch_info->data.offset, p, &p);
5616 case MONO_PATCH_INFO_SWITCH: {
5617 gpointer *table = (gpointer *)patch_info->data.table->table;
5620 encode_value (patch_info->data.table->table_size, p, &p);
5621 for (k = 0; k < patch_info->data.table->table_size; k++)
5622 encode_value ((int)(gssize)table [k], p, &p);
5625 case MONO_PATCH_INFO_METHODCONST:
5626 case MONO_PATCH_INFO_METHOD:
5627 case MONO_PATCH_INFO_METHOD_JUMP:
5628 case MONO_PATCH_INFO_ICALL_ADDR:
5629 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5630 case MONO_PATCH_INFO_METHOD_RGCTX:
5631 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5632 encode_method_ref (acfg, patch_info->data.method, p, &p);
5634 case MONO_PATCH_INFO_AOT_JIT_INFO:
5635 encode_value (patch_info->data.index, p, &p);
5637 case MONO_PATCH_INFO_INTERNAL_METHOD:
5638 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5639 guint32 len = strlen (patch_info->data.name);
5641 encode_value (len, p, &p);
5643 memcpy (p, patch_info->data.name, len);
5648 case MONO_PATCH_INFO_LDSTR: {
5649 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5650 guint32 token = patch_info->data.token->token;
5651 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5652 encode_value (image_index, p, &p);
5653 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5656 case MONO_PATCH_INFO_RVA:
5657 case MONO_PATCH_INFO_DECLSEC:
5658 case MONO_PATCH_INFO_LDTOKEN:
5659 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5660 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5661 encode_value (patch_info->data.token->token, p, &p);
5662 encode_value (patch_info->data.token->has_context, p, &p);
5663 if (patch_info->data.token->has_context)
5664 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5666 case MONO_PATCH_INFO_EXC_NAME: {
5667 MonoClass *ex_class;
5670 mono_class_load_from_name (mono_defaults.exception_class->image,
5671 "System", (const char *)patch_info->data.target);
5672 encode_klass_ref (acfg, ex_class, p, &p);
5675 case MONO_PATCH_INFO_R4:
5676 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5678 case MONO_PATCH_INFO_R8:
5679 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5680 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5682 case MONO_PATCH_INFO_VTABLE:
5683 case MONO_PATCH_INFO_CLASS:
5684 case MONO_PATCH_INFO_IID:
5685 case MONO_PATCH_INFO_ADJUSTED_IID:
5686 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5688 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5689 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5690 if (patch_info->data.del_tramp->method) {
5691 encode_value (1, p, &p);
5692 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5694 encode_value (0, p, &p);
5696 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5698 case MONO_PATCH_INFO_FIELD:
5699 case MONO_PATCH_INFO_SFLDA:
5700 encode_field_info (acfg, patch_info->data.field, p, &p);
5702 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5704 case MONO_PATCH_INFO_RGCTX_FETCH:
5705 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5706 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5711 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5712 * reference the same method, so encode the method only once.
5714 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5716 buf2 = (guint8 *)g_malloc (1024);
5719 encode_method_ref (acfg, entry->method, p2, &p2);
5720 g_assert (p2 - buf2 < 1024);
5722 offset = add_to_blob (acfg, buf2, p2 - buf2);
5725 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5730 encode_value (offset, p, &p);
5731 g_assert ((int)entry->info_type < 256);
5732 g_assert (entry->data->type < 256);
5733 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5734 encode_patch (acfg, entry->data, p, &p);
5737 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5738 case MONO_PATCH_INFO_AOT_MODULE:
5740 case MONO_PATCH_INFO_SIGNATURE:
5741 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5742 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5744 case MONO_PATCH_INFO_TLS_OFFSET:
5745 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5747 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5748 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5749 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5751 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5752 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5755 encode_method_ref (acfg, info->method, p, &p);
5756 encode_value (info->num_entries, p, &p);
5757 for (i = 0; i < info->num_entries; ++i) {
5758 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5760 encode_value (template_->info_type, p, &p);
5761 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5762 case MONO_PATCH_INFO_CLASS:
5763 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5765 case MONO_PATCH_INFO_FIELD:
5766 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5769 g_assert_not_reached ();
5775 case MONO_PATCH_INFO_LDSTR_LIT: {
5776 const char *s = (const char *)patch_info->data.target;
5777 int len = strlen (s);
5779 encode_value (len, p, &p);
5780 memcpy (p, s, len + 1);
5784 case MONO_PATCH_INFO_VIRT_METHOD:
5785 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5786 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5788 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5791 g_warning ("unable to handle jump info %d", patch_info->type);
5792 g_assert_not_reached ();
5799 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5802 guint32 pindex, offset;
5803 MonoJumpInfo *patch_info;
5805 encode_value (n_patches, p, &p);
5807 for (pindex = 0; pindex < patches->len; ++pindex) {
5808 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5810 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5814 offset = get_got_offset (acfg, llvm, patch_info);
5815 encode_value (offset, p, &p);
5822 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5825 int pindex, buf_size, n_patches;
5827 MonoJumpInfo *patch_info;
5828 guint32 method_index;
5830 guint32 first_got_offset;
5832 method = cfg->orig_method;
5834 method_index = get_method_index (acfg, method);
5836 /* Sort relocations */
5837 patches = g_ptr_array_new ();
5838 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5839 g_ptr_array_add (patches, patch_info);
5840 g_ptr_array_sort (patches, compare_patches);
5842 first_got_offset = acfg->cfgs [method_index]->got_offset;
5844 /**********************/
5845 /* Encode method info */
5846 /**********************/
5848 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5849 p = buf = (guint8 *)g_malloc (buf_size);
5851 if (mono_class_get_cctor (method->klass)) {
5852 encode_value (1, p, &p);
5853 encode_klass_ref (acfg, method->klass, p, &p);
5855 /* Not needed when loading the method */
5856 encode_value (0, p, &p);
5859 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5862 for (pindex = 0; pindex < patches->len; ++pindex) {
5863 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5865 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5866 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5867 patch_info->type = MONO_PATCH_INFO_NONE;
5872 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5873 /* Stored in a GOT slot initialized at module load time */
5874 patch_info->type = MONO_PATCH_INFO_NONE;
5878 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5879 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5880 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5881 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5882 /* Stored in a GOT slot initialized at module load time */
5883 patch_info->type = MONO_PATCH_INFO_NONE;
5887 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5888 /* Calls are made through the PLT */
5889 patch_info->type = MONO_PATCH_INFO_NONE;
5897 g_assert (cfg->has_got_slots);
5899 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5901 g_ptr_array_free (patches, TRUE);
5903 acfg->stats.info_size += p - buf;
5905 g_assert (p - buf < buf_size);
5907 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5912 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5914 guint32 cache_index;
5917 /* Reuse the unwind module to canonize and store unwind info entries */
5918 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5920 /* Use +/- 1 to distinguish 0s from missing entries */
5921 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5929 * It would be easier to use assembler symbols, but the caller needs an
5932 offset = acfg->unwind_info_offset;
5933 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5934 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5937 encode_value (encoded_len, p, &p);
5939 acfg->unwind_info_offset += encoded_len + (p - buf);
5945 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5948 guint32 debug_info_size, seq_points_size;
5950 MonoMethodHeader *header;
5951 guint8 *p, *buf, *debug_info;
5952 MonoJitInfo *jinfo = cfg->jit_info;
5954 gboolean use_unwind_ops = FALSE;
5955 MonoSeqPointInfo *seq_points;
5957 code = cfg->native_code;
5958 header = cfg->header;
5960 if (!acfg->aot_opts.nodebug) {
5961 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5964 debug_info_size = 0;
5967 seq_points = cfg->seq_point_info;
5968 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5970 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5972 p = buf = (guint8 *)g_malloc (buf_size);
5974 use_unwind_ops = cfg->unwind_ops != NULL;
5976 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);
5978 encode_value (flags, p, &p);
5980 if (use_unwind_ops) {
5981 guint32 encoded_len;
5983 guint32 unwind_desc;
5985 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5987 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
5988 encode_value (unwind_desc, p, &p);
5992 encode_value (jinfo->unwind_info, p, &p);
5995 /*Encode the number of holes before the number of clauses to make decoding easier*/
5996 if (jinfo->has_try_block_holes) {
5997 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
5998 encode_value (table->num_holes, p, &p);
6001 if (jinfo->has_arch_eh_info) {
6003 * In AOT mode, the code length is calculated from the address of the previous method,
6004 * which could include alignment padding, so calculating the start of the epilog as
6005 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6007 encode_value (jinfo->code_size, p, &p);
6010 /* Exception table */
6011 if (cfg->compile_llvm) {
6013 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6014 * since the information is only available to llc. Instead, we let llc save the data
6015 * into the LSDA, and read it from there at runtime.
6017 /* The assembly might be CIL stripped so emit the data ourselves */
6018 if (header->num_clauses)
6019 encode_value (header->num_clauses, p, &p);
6021 for (k = 0; k < header->num_clauses; ++k) {
6022 MonoExceptionClause *clause;
6024 clause = &header->clauses [k];
6026 encode_value (clause->flags, p, &p);
6027 if (clause->data.catch_class) {
6028 encode_value (1, p, &p);
6029 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6031 encode_value (0, p, &p);
6034 /* Emit the IL ranges too, since they might not be available at runtime */
6035 encode_value (clause->try_offset, p, &p);
6036 encode_value (clause->try_len, p, &p);
6037 encode_value (clause->handler_offset, p, &p);
6038 encode_value (clause->handler_len, p, &p);
6040 /* Emit a list of nesting clauses */
6041 for (i = 0; i < header->num_clauses; ++i) {
6043 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6045 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6047 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6048 encode_value (i, p, &p);
6050 encode_value (-1, p, &p);
6053 if (jinfo->num_clauses)
6054 encode_value (jinfo->num_clauses, p, &p);
6056 for (k = 0; k < jinfo->num_clauses; ++k) {
6057 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6059 encode_value (ei->flags, p, &p);
6060 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6061 /* Not used for catch clauses */
6062 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6063 encode_value (ei->exvar_offset, p, &p);
6065 encode_value (ei->exvar_offset, p, &p);
6068 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6069 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6071 if (ei->data.catch_class) {
6075 buf2 = (guint8 *)g_malloc (4096);
6077 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6079 g_assert (len < 4096);
6080 encode_value (len, p, &p);
6081 memcpy (p, buf2, len);
6085 encode_value (0, p, &p);
6089 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6090 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6091 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6095 if (jinfo->has_try_block_holes) {
6096 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6097 for (i = 0; i < table->num_holes; ++i) {
6098 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6099 encode_value (hole->clause, p, &p);
6100 encode_value (hole->length, p, &p);
6101 encode_value (hole->offset, p, &p);
6105 if (jinfo->has_arch_eh_info) {
6106 MonoArchEHJitInfo *eh_info;
6108 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6109 encode_value (eh_info->stack_size, p, &p);
6110 encode_value (eh_info->epilog_size, p, &p);
6113 if (jinfo->has_generic_jit_info) {
6114 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6115 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6119 encode_value (gi->nlocs, p, &p);
6121 for (i = 0; i < gi->nlocs; ++i) {
6122 MonoDwarfLocListEntry *entry = &gi->locations [i];
6124 encode_value (entry->is_reg ? 1 : 0, p, &p);
6125 encode_value (entry->reg, p, &p);
6127 encode_value (entry->offset, p, &p);
6129 g_assert (entry->from == 0);
6131 encode_value (entry->from, p, &p);
6132 encode_value (entry->to, p, &p);
6135 if (!cfg->compile_llvm) {
6136 encode_value (gi->has_this ? 1 : 0, p, &p);
6137 encode_value (gi->this_reg, p, &p);
6138 encode_value (gi->this_offset, p, &p);
6143 * Need to encode jinfo->method too, since it is not equal to 'method'
6144 * when using generic sharing.
6146 buf2 = (guint8 *)g_malloc (4096);
6148 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6150 g_assert (len < 4096);
6151 encode_value (len, p, &p);
6152 memcpy (p, buf2, len);
6156 if (gsctx && gsctx->is_gsharedvt) {
6157 encode_value (1, p, &p);
6159 encode_value (0, p, &p);
6163 if (seq_points_size)
6164 p += mono_seq_point_info_write (seq_points, p);
6166 g_assert (debug_info_size < buf_size);
6168 encode_value (debug_info_size, p, &p);
6169 if (debug_info_size) {
6170 memcpy (p, debug_info, debug_info_size);
6171 p += debug_info_size;
6172 g_free (debug_info);
6177 encode_value (cfg->gc_map_size, p, &p);
6178 /* The GC map requires 4 bytes of alignment */
6179 while ((gsize)p % 4)
6181 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6182 p += cfg->gc_map_size;
6185 acfg->stats.ex_info_size += p - buf;
6187 g_assert (p - buf < buf_size);
6190 /* The GC Map requires 4 byte alignment */
6191 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6196 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6199 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6201 int i, buf_size, res;
6202 gboolean no_special_static, cant_encode;
6203 gpointer iter = NULL;
6206 mono_error_cleanup (&error);
6210 p = buf = (guint8 *)g_malloc (buf_size);
6212 /* Mark as unusable */
6213 encode_value (-1, p, &p);
6215 res = add_to_blob (acfg, buf, p - buf);
6221 buf_size = 10240 + (klass->vtable_size * 16);
6222 p = buf = (guint8 *)g_malloc (buf_size);
6226 mono_class_init (klass);
6228 mono_class_get_nested_types (klass, &iter);
6229 g_assert (klass->nested_classes_inited);
6231 mono_class_setup_vtable (klass);
6234 * Emit all the information which is required for creating vtables so
6235 * the runtime does not need to create the MonoMethod structures which
6236 * take up a lot of space.
6239 no_special_static = !mono_class_has_special_static_fields (klass);
6241 /* Check whenever we have enough info to encode the vtable */
6242 cant_encode = FALSE;
6243 for (i = 0; i < klass->vtable_size; ++i) {
6244 MonoMethod *cm = klass->vtable [i];
6246 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6250 mono_class_has_finalizer (klass);
6252 if (klass->generic_container || cant_encode) {
6253 encode_value (-1, p, &p);
6255 encode_value (klass->vtable_size, p, &p);
6256 encode_value ((klass->generic_container ? (1 << 8) : 0) | (no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
6257 if (klass->has_cctor)
6258 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6259 if (klass->has_finalize)
6260 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6262 encode_value (klass->instance_size, p, &p);
6263 encode_value (mono_class_data_size (klass), p, &p);
6264 encode_value (klass->packing_size, p, &p);
6265 encode_value (klass->min_align, p, &p);
6267 for (i = 0; i < klass->vtable_size; ++i) {
6268 MonoMethod *cm = klass->vtable [i];
6271 encode_method_ref (acfg, cm, p, &p);
6273 encode_value (0, p, &p);
6277 acfg->stats.class_info_size += p - buf;
6279 g_assert (p - buf < buf_size);
6280 res = add_to_blob (acfg, buf, p - buf);
6287 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6289 char *debug_sym = NULL;
6292 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6293 /* Need to add a prefix to create unique symbols */
6294 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6296 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6297 prefix = mangle_symbol_alloc ("plt_");
6299 prefix = g_strdup ("plt_");
6304 case MONO_PATCH_INFO_METHOD:
6305 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6307 case MONO_PATCH_INFO_INTERNAL_METHOD:
6308 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6310 case MONO_PATCH_INFO_RGCTX_FETCH:
6311 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6313 case MONO_PATCH_INFO_ICALL_ADDR:
6314 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6315 char *s = get_debug_sym (ji->data.method, "", cache);
6317 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6321 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6322 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6330 return sanitize_symbol (acfg, debug_sym);
6334 * Calls made from AOTed code are routed through a table of jumps similar to the
6335 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6336 * control to the AOT runtime through a trampoline.
6339 emit_plt (MonoAotCompile *acfg)
6343 if (acfg->aot_opts.llvm_only) {
6344 g_assert (acfg->plt_offset == 1);
6350 emit_section_change (acfg, ".text", 0);
6351 emit_alignment_code (acfg, 16);
6352 emit_info_symbol (acfg, "plt");
6353 emit_label (acfg, acfg->plt_symbol);
6355 for (i = 0; i < acfg->plt_offset; ++i) {
6356 char *debug_sym = NULL;
6357 MonoPltEntry *plt_entry = NULL;
6361 * The first plt entry is unused.
6365 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6367 debug_sym = plt_entry->debug_sym;
6369 if (acfg->thumb_mixed && !plt_entry->jit_used)
6370 /* Emit only a thumb version */
6373 /* Skip plt entries not actually called */
6374 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6377 if (acfg->llvm && !acfg->thumb_mixed) {
6378 emit_label (acfg, plt_entry->llvm_symbol);
6380 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6381 #if defined(TARGET_MACH)
6382 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6388 if (acfg->need_no_dead_strip) {
6389 emit_unset_mode (acfg);
6390 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6392 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6393 emit_label (acfg, debug_sym);
6396 emit_label (acfg, plt_entry->symbol);
6398 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6401 emit_symbol_size (acfg, debug_sym, ".");
6404 if (acfg->thumb_mixed) {
6405 /* Make sure the ARM symbols don't alias the thumb ones */
6406 emit_zero_bytes (acfg, 16);
6409 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6412 for (i = 0; i < acfg->plt_offset; ++i) {
6413 char *debug_sym = NULL;
6414 MonoPltEntry *plt_entry = NULL;
6419 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6421 /* Skip plt entries not actually called by LLVM code */
6422 if (!plt_entry->llvm_used)
6425 if (acfg->aot_opts.write_symbols) {
6426 if (plt_entry->debug_sym)
6427 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6431 #if defined(TARGET_MACH)
6432 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6433 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6435 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6436 emit_label (acfg, debug_sym);
6438 fprintf (acfg->fp, "\n.thumb_func\n");
6440 emit_label (acfg, plt_entry->llvm_symbol);
6443 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6445 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6448 emit_symbol_size (acfg, debug_sym, ".");
6454 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6456 emit_info_symbol (acfg, "plt_end");
6460 * emit_trampoline_full:
6462 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6463 * create_jit_info_for_trampoline ().
6465 static G_GNUC_UNUSED void
6466 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6468 char start_symbol [MAX_SYMBOL_SIZE];
6469 char end_symbol [MAX_SYMBOL_SIZE];
6470 char symbol [MAX_SYMBOL_SIZE];
6471 guint32 buf_size, info_offset;
6472 MonoJumpInfo *patch_info;
6485 code_size = info->code_size;
6487 unwind_ops = info->unwind_ops;
6491 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6493 emit_section_change (acfg, ".text", 0);
6494 emit_global (acfg, start_symbol, TRUE);
6495 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6496 emit_label (acfg, start_symbol);
6498 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6499 emit_label (acfg, symbol);
6502 * The code should access everything through the GOT, so we pass
6505 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6507 emit_symbol_size (acfg, start_symbol, ".");
6510 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6511 emit_label (acfg, end_symbol);
6516 /* Sort relocations */
6517 patches = g_ptr_array_new ();
6518 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6519 if (patch_info->type != MONO_PATCH_INFO_NONE)
6520 g_ptr_array_add (patches, patch_info);
6521 g_ptr_array_sort (patches, compare_patches);
6523 buf_size = patches->len * 128 + 128;
6524 buf = (guint8 *)g_malloc (buf_size);
6527 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6528 g_assert (p - buf < buf_size);
6529 g_ptr_array_free (patches, TRUE);
6531 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6533 info_offset = add_to_blob (acfg, buf, p - buf);
6535 emit_section_change (acfg, RODATA_SECT, 0);
6536 emit_global (acfg, symbol, FALSE);
6537 emit_label (acfg, symbol);
6539 emit_int32 (acfg, info_offset);
6543 guint32 encoded_len;
6547 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6549 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6550 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6553 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6554 emit_int32 (acfg, uw_offset);
6557 /* Emit debug info */
6559 char symbol2 [MAX_SYMBOL_SIZE];
6561 sprintf (symbol, "%s", name);
6562 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6565 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6571 static G_GNUC_UNUSED void
6572 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6574 emit_trampoline_full (acfg, got_offset, info, TRUE);
6578 emit_trampolines (MonoAotCompile *acfg)
6580 char symbol [MAX_SYMBOL_SIZE];
6581 char end_symbol [MAX_SYMBOL_SIZE];
6582 int i, tramp_got_offset;
6584 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6588 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6591 g_assert (acfg->image->assembly);
6593 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6594 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6595 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6596 MonoTrampInfo *info;
6599 * Emit the generic trampolines.
6601 * We could save some code by treating the generic trampolines as a wrapper
6602 * method, but that approach has its own complexities, so we choose the simpler
6605 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6606 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6607 #ifdef DISABLE_REMOTING
6608 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6611 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6612 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6615 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6616 emit_trampoline (acfg, acfg->got_offset, info);
6619 /* Emit the exception related code pieces */
6620 mono_arch_get_restore_context (&info, TRUE);
6621 emit_trampoline (acfg, acfg->got_offset, info);
6622 mono_arch_get_call_filter (&info, TRUE);
6623 emit_trampoline (acfg, acfg->got_offset, info);
6624 mono_arch_get_throw_exception (&info, TRUE);
6625 emit_trampoline (acfg, acfg->got_offset, info);
6626 mono_arch_get_rethrow_exception (&info, TRUE);
6627 emit_trampoline (acfg, acfg->got_offset, info);
6628 mono_arch_get_throw_corlib_exception (&info, TRUE);
6629 emit_trampoline (acfg, acfg->got_offset, info);
6631 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6632 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6633 emit_trampoline (acfg, acfg->got_offset, info);
6634 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6635 emit_trampoline (acfg, acfg->got_offset, info);
6638 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6639 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6641 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6643 /* Create a separate out trampoline for more information in stack traces */
6644 info->name = g_strdup ("gsharedvt_out_trampoline");
6645 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6649 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6651 GSList *l = mono_arch_get_trampolines (TRUE);
6654 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6656 emit_trampoline (acfg, acfg->got_offset, info);
6662 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6665 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6666 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6667 emit_trampoline (acfg, acfg->got_offset, info);
6670 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6671 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6672 emit_trampoline (acfg, acfg->got_offset, info);
6676 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6677 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6678 emit_trampoline (acfg, acfg->got_offset, info);
6684 /* delegate_invoke_impl trampolines */
6685 l = mono_arch_get_delegate_invoke_impls ();
6687 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6689 emit_trampoline (acfg, acfg->got_offset, info);
6694 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6695 mono_arch_create_handler_block_trampoline (&info, TRUE);
6696 emit_trampoline (acfg, acfg->got_offset, info);
6699 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6701 /* Emit trampolines which are numerous */
6704 * These include the following:
6705 * - specific trampolines
6706 * - static rgctx invoke trampolines
6708 * These trampolines have the same code, they are parameterized by GOT
6710 * They are defined in this file, in the arch_... routines instead of
6711 * in tramp-<ARCH>.c, since it is easier to do it this way.
6715 * When running in aot-only mode, we can't create specific trampolines at
6716 * runtime, so we create a few, and save them in the AOT file.
6717 * Normal trampolines embed their argument as a literal inside the
6718 * trampoline code, we can't do that here, so instead we embed an offset
6719 * which needs to be added to the trampoline address to get the address of
6720 * the GOT slot which contains the argument value.
6721 * The generated trampolines jump to the generic trampolines using another
6722 * GOT slot, which will be setup by the AOT loader to point to the
6723 * generic trampoline code of the given type.
6727 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6731 emit_section_change (acfg, ".text", 0);
6733 tramp_got_offset = acfg->got_offset;
6735 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6737 case MONO_AOT_TRAMP_SPECIFIC:
6738 sprintf (symbol, "specific_trampolines");
6740 case MONO_AOT_TRAMP_STATIC_RGCTX:
6741 sprintf (symbol, "static_rgctx_trampolines");
6743 case MONO_AOT_TRAMP_IMT_THUNK:
6744 sprintf (symbol, "imt_thunks");
6746 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6747 sprintf (symbol, "gsharedvt_arg_trampolines");
6750 g_assert_not_reached ();
6753 sprintf (end_symbol, "%s_e", symbol);
6755 if (acfg->aot_opts.write_symbols)
6756 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6758 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6759 emit_info_symbol (acfg, symbol);
6761 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6763 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6767 case MONO_AOT_TRAMP_SPECIFIC:
6768 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6769 tramp_got_offset += 2;
6771 case MONO_AOT_TRAMP_STATIC_RGCTX:
6772 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6773 tramp_got_offset += 2;
6775 case MONO_AOT_TRAMP_IMT_THUNK:
6776 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
6777 tramp_got_offset += 1;
6779 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6780 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6781 tramp_got_offset += 2;
6784 g_assert_not_reached ();
6786 if (!acfg->trampoline_size [ntype]) {
6787 g_assert (tramp_size);
6788 acfg->trampoline_size [ntype] = tramp_size;
6792 emit_label (acfg, end_symbol);
6793 emit_int32 (acfg, 0);
6796 arch_emit_specific_trampoline_pages (acfg);
6798 /* Reserve some entries at the end of the GOT for our use */
6799 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6802 acfg->got_offset += acfg->num_trampoline_got_entries;
6806 str_begins_with (const char *str1, const char *str2)
6808 int len = strlen (str2);
6809 return strncmp (str1, str2, len) == 0;
6813 mono_aot_readonly_field_override (MonoClassField *field)
6816 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6817 char *p = rdv->name;
6819 len = strlen (field->parent->name_space);
6820 if (strncmp (p, field->parent->name_space, len))
6825 len = strlen (field->parent->name);
6826 if (strncmp (p, field->parent->name, len))
6831 if (strcmp (p, field->name))
6833 switch (rdv->type) {
6835 return &rdv->value.i1;
6837 return &rdv->value.i2;
6839 return &rdv->value.i4;
6848 add_readonly_value (MonoAotOptions *opts, const char *val)
6853 /* the format of val is:
6854 * namespace.typename.fieldname=type/value
6855 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6857 fval = strrchr (val, '/');
6859 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6862 tval = strrchr (val, '=');
6864 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6867 rdv = g_new0 (ReadOnlyValue, 1);
6868 rdv->name = (char *)g_malloc0 (tval - val + 1);
6869 memcpy (rdv->name, val, tval - val);
6872 if (strncmp (tval, "i1", 2) == 0) {
6873 rdv->value.i1 = atoi (fval);
6874 rdv->type = MONO_TYPE_I1;
6875 } else if (strncmp (tval, "i2", 2) == 0) {
6876 rdv->value.i2 = atoi (fval);
6877 rdv->type = MONO_TYPE_I2;
6878 } else if (strncmp (tval, "i4", 2) == 0) {
6879 rdv->value.i4 = atoi (fval);
6880 rdv->type = MONO_TYPE_I4;
6882 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6885 rdv->next = readonly_values;
6886 readonly_values = rdv;
6890 clean_path (gchar * path)
6895 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6898 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6905 wrap_path (gchar * path)
6911 // If the string contains no spaces, just return the original string.
6912 if (strstr (path, " ") == NULL)
6915 // If the string is already wrapped in quotes, return it.
6916 len = strlen (path);
6917 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6920 // If the string contains spaces, then wrap it in quotes.
6921 gchar *clean = g_strdup_printf ("\"%s\"", path);
6926 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
6928 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
6930 ptrdiff_t len = end-start;
6932 g_ptr_array_add (args, g_strndup (start, len));
6936 mono_aot_split_options (const char *aot_options)
6938 enum MonoAotOptionState {
6939 MONO_AOT_OPTION_STATE_DEFAULT,
6940 MONO_AOT_OPTION_STATE_STRING,
6941 MONO_AOT_OPTION_STATE_ESCAPE,
6944 GPtrArray *args = g_ptr_array_new ();
6945 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6946 gchar const *opt_start = aot_options;
6947 gboolean end_of_string = FALSE;
6950 g_return_val_if_fail (aot_options != NULL, NULL);
6952 while ((cur = *aot_options) != '\0') {
6953 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6958 // If we find a quote, then if we're in the default case then
6959 // it means we've found the start of a string, if not then it
6960 // means we've found the end of the string and should switch
6961 // back to the default case.
6963 case MONO_AOT_OPTION_STATE_DEFAULT:
6964 state = MONO_AOT_OPTION_STATE_STRING;
6966 case MONO_AOT_OPTION_STATE_STRING:
6967 state = MONO_AOT_OPTION_STATE_DEFAULT;
6969 case MONO_AOT_OPTION_STATE_ESCAPE:
6970 g_assert_not_reached ();
6975 // If we've found an escaping operator, then this means we
6976 // should not process the next character if inside a string.
6977 if (state == MONO_AOT_OPTION_STATE_STRING)
6978 state = MONO_AOT_OPTION_STATE_ESCAPE;
6981 // If we're in the default state then this means we've found
6982 // an option, store it for later processing.
6983 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
6991 // If the next character is end of string, then process the last option.
6992 if (*(aot_options) == '\0') {
6993 end_of_string = TRUE;
6999 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7000 opt_start = ++aot_options;
7003 goto restart; // Check for null and continue loop
7010 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7014 args = mono_aot_split_options (aot_options ? aot_options : "");
7015 for (int i = 0; i < args->len; ++i) {
7016 const char *arg = (const char *)g_ptr_array_index (args, i);
7018 if (str_begins_with (arg, "outfile=")) {
7019 opts->outfile = g_strdup (arg + strlen ("outfile="));
7020 } else if (str_begins_with (arg, "llvm-outfile=")) {
7021 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7022 } else if (str_begins_with (arg, "temp-path=")) {
7023 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7024 } else if (str_begins_with (arg, "save-temps")) {
7025 opts->save_temps = TRUE;
7026 } else if (str_begins_with (arg, "keep-temps")) {
7027 opts->save_temps = TRUE;
7028 } else if (str_begins_with (arg, "write-symbols")) {
7029 opts->write_symbols = TRUE;
7030 } else if (str_begins_with (arg, "no-write-symbols")) {
7031 opts->write_symbols = FALSE;
7032 } else if (str_begins_with (arg, "metadata-only")) {
7033 opts->metadata_only = TRUE;
7034 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7035 opts->bind_to_runtime_version = TRUE;
7036 } else if (str_begins_with (arg, "full")) {
7037 opts->mode = MONO_AOT_MODE_FULL;
7038 } else if (str_begins_with (arg, "hybrid")) {
7039 opts->mode = MONO_AOT_MODE_HYBRID;
7040 } else if (str_begins_with (arg, "threads=")) {
7041 opts->nthreads = atoi (arg + strlen ("threads="));
7042 } else if (str_begins_with (arg, "static")) {
7043 opts->static_link = TRUE;
7044 opts->no_dlsym = TRUE;
7045 } else if (str_begins_with (arg, "asmonly")) {
7046 opts->asm_only = TRUE;
7047 } else if (str_begins_with (arg, "asmwriter")) {
7048 opts->asm_writer = TRUE;
7049 } else if (str_begins_with (arg, "nodebug")) {
7050 opts->nodebug = TRUE;
7051 } else if (str_begins_with (arg, "dwarfdebug")) {
7052 opts->dwarf_debug = TRUE;
7053 } else if (str_begins_with (arg, "nopagetrampolines")) {
7054 opts->use_trampolines_page = FALSE;
7055 } else if (str_begins_with (arg, "ntrampolines=")) {
7056 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7057 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7058 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7059 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7060 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7061 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7062 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7063 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7064 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7065 } else if (str_begins_with (arg, "tool-prefix=")) {
7066 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7067 } else if (str_begins_with (arg, "ld-flags=")) {
7068 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7069 } else if (str_begins_with (arg, "soft-debug")) {
7070 opts->soft_debug = TRUE;
7071 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7072 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7073 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7074 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7075 } else if (str_begins_with (arg, "msym-dir=")) {
7076 debug_options.no_seq_points_compact_data = FALSE;
7077 opts->gen_msym_dir = TRUE;
7078 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7079 } else if (str_begins_with (arg, "direct-pinvoke")) {
7080 opts->direct_pinvoke = TRUE;
7081 } else if (str_begins_with (arg, "direct-icalls")) {
7082 opts->direct_icalls = TRUE;
7083 } else if (str_begins_with (arg, "no-direct-calls")) {
7084 opts->no_direct_calls = TRUE;
7085 } else if (str_begins_with (arg, "print-skipped")) {
7086 opts->print_skipped_methods = TRUE;
7087 } else if (str_begins_with (arg, "stats")) {
7089 } else if (str_begins_with (arg, "no-instances")) {
7090 opts->no_instances = TRUE;
7091 } else if (str_begins_with (arg, "log-generics")) {
7092 opts->log_generics = TRUE;
7093 } else if (str_begins_with (arg, "log-instances=")) {
7094 opts->log_instances = TRUE;
7095 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7096 } else if (str_begins_with (arg, "log-instances")) {
7097 opts->log_instances = TRUE;
7098 } else if (str_begins_with (arg, "internal-logfile=")) {
7099 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7100 } else if (str_begins_with (arg, "mtriple=")) {
7101 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7102 } else if (str_begins_with (arg, "llvm-path=")) {
7103 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7104 } else if (!strcmp (arg, "llvm")) {
7106 } else if (str_begins_with (arg, "readonly-value=")) {
7107 add_readonly_value (opts, arg + strlen ("readonly-value="));
7108 } else if (str_begins_with (arg, "info")) {
7109 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7111 } else if (str_begins_with (arg, "gc-maps")) {
7112 mini_gc_enable_gc_maps_for_aot ();
7113 } else if (str_begins_with (arg, "dump")) {
7114 opts->dump_json = TRUE;
7115 } else if (str_begins_with (arg, "llvmonly")) {
7116 opts->mode = MONO_AOT_MODE_FULL;
7118 opts->llvm_only = TRUE;
7119 } else if (str_begins_with (arg, "data-outfile=")) {
7120 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7121 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7122 printf ("Supported options for --aot:\n");
7123 printf (" outfile=\n");
7124 printf (" llvm-outfile=\n");
7125 printf (" llvm-path=\n");
7126 printf (" temp-path=\n");
7127 printf (" save-temps\n");
7128 printf (" keep-temps\n");
7129 printf (" write-symbols\n");
7130 printf (" metadata-only\n");
7131 printf (" bind-to-runtime-version\n");
7133 printf (" threads=\n");
7134 printf (" static\n");
7135 printf (" asmonly\n");
7136 printf (" asmwriter\n");
7137 printf (" nodebug\n");
7138 printf (" dwarfdebug\n");
7139 printf (" ntrampolines=\n");
7140 printf (" nrgctx-trampolines=\n");
7141 printf (" nimt-trampolines=\n");
7142 printf (" ngsharedvt-trampolines=\n");
7143 printf (" tool-prefix=\n");
7144 printf (" readonly-value=\n");
7145 printf (" soft-debug\n");
7146 printf (" msym-dir=\n");
7147 printf (" gc-maps\n");
7148 printf (" print-skipped\n");
7149 printf (" no-instances\n");
7150 printf (" stats\n");
7153 printf (" help/?\n");
7156 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7160 g_free ((gpointer) arg);
7163 if (opts->use_trampolines_page) {
7164 opts->ntrampolines = 0;
7165 opts->nrgctx_trampolines = 0;
7166 opts->nimt_trampolines = 0;
7167 opts->ngsharedvt_arg_trampolines = 0;
7170 g_ptr_array_free (args, /*free_seg=*/TRUE);
7174 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7176 MonoMethod *method = (MonoMethod*)key;
7177 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7178 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7179 MonoJumpInfoToken *new_ji;
7181 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7182 new_ji->image = ji->image;
7183 new_ji->token = ji->token;
7184 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7188 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7190 if (klass->type_token)
7192 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7195 return can_encode_class (acfg, klass->element_class);
7200 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7202 if (method->wrapper_type) {
7203 switch (method->wrapper_type) {
7204 case MONO_WRAPPER_NONE:
7205 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7206 case MONO_WRAPPER_XDOMAIN_INVOKE:
7207 case MONO_WRAPPER_STFLD:
7208 case MONO_WRAPPER_LDFLD:
7209 case MONO_WRAPPER_LDFLDA:
7210 case MONO_WRAPPER_STELEMREF:
7211 case MONO_WRAPPER_ISINST:
7212 case MONO_WRAPPER_PROXY_ISINST:
7213 case MONO_WRAPPER_ALLOC:
7214 case MONO_WRAPPER_REMOTING_INVOKE:
7215 case MONO_WRAPPER_UNKNOWN:
7216 case MONO_WRAPPER_WRITE_BARRIER:
7217 case MONO_WRAPPER_DELEGATE_INVOKE:
7218 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7219 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7220 case MONO_WRAPPER_SYNCHRONIZED:
7222 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7223 case MONO_WRAPPER_CASTCLASS: {
7224 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7233 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7237 if (!method->token) {
7238 /* The method is part of a constructed type like Int[,].Set (). */
7239 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7240 if (method->klass->rank)
7250 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7252 switch (patch_info->type) {
7253 case MONO_PATCH_INFO_METHOD:
7254 case MONO_PATCH_INFO_METHODCONST:
7255 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7256 MonoMethod *method = patch_info->data.method;
7258 return can_encode_method (acfg, method);
7260 case MONO_PATCH_INFO_VTABLE:
7261 case MONO_PATCH_INFO_CLASS:
7262 case MONO_PATCH_INFO_IID:
7263 case MONO_PATCH_INFO_ADJUSTED_IID:
7264 if (!can_encode_class (acfg, patch_info->data.klass)) {
7265 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7269 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7270 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7271 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7276 case MONO_PATCH_INFO_RGCTX_FETCH:
7277 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7278 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7280 if (!can_encode_method (acfg, entry->method))
7282 if (!can_encode_patch (acfg, entry->data))
7294 is_concrete_type (MonoType *t)
7299 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7301 if (t->type == MONO_TYPE_GENERICINST) {
7302 MonoGenericContext *orig_ctx;
7303 MonoGenericInst *inst;
7306 if (!MONO_TYPE_ISSTRUCT (t))
7308 klass = mono_class_from_mono_type (t);
7309 orig_ctx = &klass->generic_class->context;
7311 inst = orig_ctx->class_inst;
7313 for (i = 0; i < inst->type_argc; ++i) {
7314 arg = mini_get_underlying_type (inst->type_argv [i]);
7315 if (!is_concrete_type (arg))
7319 inst = orig_ctx->method_inst;
7321 for (i = 0; i < inst->type_argc; ++i) {
7322 arg = mini_get_underlying_type (inst->type_argv [i]);
7323 if (!is_concrete_type (arg))
7331 /* LOCKING: Assumes the loader lock is held */
7333 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7335 MonoMethod *wrapper;
7336 gboolean concrete = TRUE;
7337 gboolean add_in = gsharedvt_in;
7338 gboolean add_out = gsharedvt_out;
7340 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7342 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7345 if (!add_in && !add_out)
7348 if (mini_is_gsharedvt_variable_signature (sig))
7352 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7354 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7356 if (!sig->has_type_parameters) {
7357 //printf ("%s\n", mono_signature_full_name (sig));
7360 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7361 add_extra_method (acfg, wrapper);
7363 if (gsharedvt_out) {
7364 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7365 add_extra_method (acfg, wrapper);
7368 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7369 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7372 //printf ("%s\n", mono_signature_full_name (sig));
7374 copy->ret = mini_get_underlying_type (sig->ret);
7375 if (!is_concrete_type (copy->ret))
7377 for (i = 0; i < sig->param_count; ++i) {
7378 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7379 if (!is_concrete_type (copy->params [i]))
7383 copy->has_type_parameters = 0;
7386 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7387 add_extra_method (acfg, wrapper);
7390 if (gsharedvt_out) {
7391 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7392 add_extra_method (acfg, wrapper);
7395 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7403 * AOT compile a given method.
7404 * This function might be called by multiple threads, so it must be thread-safe.
7407 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7410 MonoJumpInfo *patch_info;
7413 MonoMethod *wrapped;
7417 if (acfg->aot_opts.metadata_only)
7420 mono_acfg_lock (acfg);
7421 index = get_method_index (acfg, method);
7422 mono_acfg_unlock (acfg);
7424 /* fixme: maybe we can also precompile wrapper methods */
7425 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7426 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7427 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7428 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7432 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7435 wrapped = mono_marshal_method_from_wrapper (method);
7436 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7437 // FIXME: The wrapper should be generic too, but it is not
7440 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7443 InterlockedIncrement (&acfg->stats.mcount);
7446 if (method->is_generic || method->klass->generic_container) {
7447 InterlockedIncrement (&acfg->stats.genericcount);
7452 //acfg->aot_opts.print_skipped_methods = TRUE;
7455 * Since these methods are the only ones which are compiled with
7456 * AOT support, and they are not used by runtime startup/shutdown code,
7457 * the runtime will not see AOT methods during AOT compilation,so it
7458 * does not need to support them by creating a fake GOT etc.
7460 flags = JIT_FLAG_AOT;
7461 if (mono_aot_mode_is_full (&acfg->aot_opts))
7462 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7464 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7465 if (acfg->aot_opts.llvm_only)
7466 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7467 if (acfg->aot_opts.no_direct_calls)
7468 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7470 jit_timer = mono_time_track_start ();
7471 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7472 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7474 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7475 if (acfg->aot_opts.print_skipped_methods)
7476 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7477 InterlockedIncrement (&acfg->stats.genericcount);
7480 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7481 if (acfg->aot_opts.print_skipped_methods)
7482 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7483 /* Let the exception happen at runtime */
7487 if (cfg->disable_aot) {
7488 if (acfg->aot_opts.print_skipped_methods)
7489 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7490 InterlockedIncrement (&acfg->stats.ocount);
7493 cfg->method_index = index;
7495 /* Nullify patches which need no aot processing */
7496 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7497 switch (patch_info->type) {
7498 case MONO_PATCH_INFO_LABEL:
7499 case MONO_PATCH_INFO_BB:
7500 patch_info->type = MONO_PATCH_INFO_NONE;
7507 /* Collect method->token associations from the cfg */
7508 mono_acfg_lock (acfg);
7509 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7510 mono_acfg_unlock (acfg);
7511 g_hash_table_destroy (cfg->token_info_hash);
7512 cfg->token_info_hash = NULL;
7515 * Check for absolute addresses.
7518 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7519 switch (patch_info->type) {
7520 case MONO_PATCH_INFO_ABS:
7521 /* unable to handle this */
7530 if (acfg->aot_opts.print_skipped_methods)
7531 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7532 InterlockedIncrement (&acfg->stats.abscount);
7536 /* Lock for the rest of the code */
7537 mono_acfg_lock (acfg);
7540 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7541 else if (cfg->gshared)
7542 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7543 else if (cfg->method->wrapper_type)
7544 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7546 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7549 * Check for methods/klasses we can't encode.
7552 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7553 if (!can_encode_patch (acfg, patch_info))
7558 if (acfg->aot_opts.print_skipped_methods)
7559 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7560 acfg->stats.ocount++;
7561 mono_acfg_unlock (acfg);
7565 if (!cfg->compile_llvm)
7566 acfg->has_jitted_code = TRUE;
7568 if (method->is_inflated && acfg->aot_opts.log_instances) {
7569 if (acfg->instances_logfile)
7570 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7572 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7575 /* Adds generic instances referenced by this method */
7577 * The depth is used to avoid infinite loops when generic virtual recursion is
7580 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7581 if (!acfg->aot_opts.no_instances && depth < 32) {
7582 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7583 switch (patch_info->type) {
7584 case MONO_PATCH_INFO_RGCTX_FETCH:
7585 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7586 case MONO_PATCH_INFO_METHOD: {
7587 MonoMethod *m = NULL;
7589 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7590 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7592 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7593 m = e->data->data.method;
7595 m = patch_info->data.method;
7600 if (m->is_inflated) {
7601 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7602 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7603 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7604 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7605 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7606 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7608 add_extra_method_with_depth (acfg, m, depth + 1);
7609 add_types_from_method_header (acfg, m);
7612 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7614 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7615 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7617 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7618 add_extra_method_with_depth (acfg, m, depth + 1);
7622 case MONO_PATCH_INFO_VTABLE: {
7623 MonoClass *klass = patch_info->data.klass;
7625 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7626 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7629 case MONO_PATCH_INFO_SFLDA: {
7630 MonoClass *klass = patch_info->data.field->parent;
7632 /* The .cctor needs to run at runtime. */
7633 if (klass->generic_class && !mono_generic_context_is_sharable_full (&klass->generic_class->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7634 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7643 /* Determine whenever the method has GOT slots */
7644 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7645 switch (patch_info->type) {
7646 case MONO_PATCH_INFO_GOT_OFFSET:
7647 case MONO_PATCH_INFO_NONE:
7648 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7649 case MONO_PATCH_INFO_GC_NURSERY_START:
7650 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7652 case MONO_PATCH_INFO_IMAGE:
7653 /* The assembly is stored in GOT slot 0 */
7654 if (patch_info->data.image != acfg->image)
7655 cfg->has_got_slots = TRUE;
7658 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7659 cfg->has_got_slots = TRUE;
7664 if (!cfg->has_got_slots)
7665 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7667 /* Add gsharedvt wrappers for signatures used by the method */
7668 if (acfg->aot_opts.llvm_only) {
7671 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7672 /* These only need out wrappers */
7673 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7675 for (l = cfg->signatures; l; l = l->next) {
7676 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7678 /* These only need in wrappers */
7679 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7684 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7686 /* Make a copy of the patch info which is in the mempool */
7688 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7690 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7691 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7694 patches = new_patch_info;
7696 patches_end->next = new_patch_info;
7697 patches_end = new_patch_info;
7699 cfg->patch_info = patches;
7701 /* Make a copy of the unwind info */
7703 GSList *l, *unwind_ops;
7707 for (l = cfg->unwind_ops; l; l = l->next) {
7708 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7709 memcpy (op, l->data, sizeof (MonoUnwindOp));
7710 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7712 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7714 /* Make a copy of the argument/local info */
7717 MonoInst **args, **locals;
7718 MonoMethodSignature *sig;
7719 MonoMethodHeader *header;
7722 sig = mono_method_signature (method);
7723 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7724 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7725 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7726 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7730 header = mono_method_get_header_checked (method, &error);
7731 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7732 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7733 for (i = 0; i < header->num_locals; ++i) {
7734 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7735 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7737 mono_metadata_free_mh (header);
7738 cfg->locals = locals;
7741 /* Free some fields used by cfg to conserve memory */
7742 mono_empty_compile (cfg);
7744 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7746 while (index >= acfg->cfgs_size) {
7747 MonoCompile **new_cfgs;
7750 new_size = acfg->cfgs_size * 2;
7751 new_cfgs = g_new0 (MonoCompile*, new_size);
7752 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7753 g_free (acfg->cfgs);
7754 acfg->cfgs = new_cfgs;
7755 acfg->cfgs_size = new_size;
7757 acfg->cfgs [index] = cfg;
7759 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7761 mono_update_jit_stats (cfg);
7764 if (cfg->orig_method->wrapper_type)
7765 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7768 mono_acfg_unlock (acfg);
7770 InterlockedIncrement (&acfg->stats.ccount);
7774 compile_thread_main (gpointer *user_data)
7776 MonoDomain *domain = (MonoDomain *)user_data [0];
7777 MonoAotCompile *acfg = (MonoAotCompile *)user_data [1];
7778 GPtrArray *methods = (GPtrArray *)user_data [2];
7782 MonoThread *thread = mono_thread_attach (domain);
7783 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7784 mono_error_assert_ok (&error);
7786 for (i = 0; i < methods->len; ++i)
7787 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7791 load_profile_files (MonoAotCompile *acfg)
7795 int file_index, res, method_index, i;
7798 GList *unordered, *l;
7803 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7805 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7810 infile = fopen (tmp, "r");
7813 printf ("Using profile data file '%s'\n", tmp);
7818 res = fscanf (infile, "%32s\n", ver);
7819 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7820 printf ("Profile file has wrong version or invalid.\n");
7827 MonoMethodDesc *desc;
7830 if (fgets (name, 1023, infile) == NULL)
7833 /* Kill the newline */
7834 if (strlen (name) > 0)
7835 name [strlen (name) - 1] = '\0';
7837 desc = mono_method_desc_new (name, TRUE);
7839 method = mono_method_desc_search_in_image (desc, acfg->image);
7841 if (method && mono_method_get_token (method)) {
7842 token = mono_method_get_token (method);
7843 method_index = mono_metadata_token_index (token) - 1;
7846 for (i = 0; i < acfg->method_order->len; ++i) {
7847 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7853 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7855 //printf ("No method found matching '%s'.\n", name);
7861 /* Add missing methods */
7863 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7865 for (i = 0; i < acfg->method_order->len; ++i) {
7866 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7872 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7874 unordered = g_list_reverse (unordered);
7875 for (l = unordered; l; l = l->next)
7876 g_ptr_array_add (acfg->method_order, l->data);
7879 /* Used by the LLVM backend */
7881 mono_aot_get_got_offset (MonoJumpInfo *ji)
7883 return get_got_offset (llvm_acfg, TRUE, ji);
7887 * mono_aot_is_shared_got_offset:
7889 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7890 * when the AOT image is loaded.
7893 mono_aot_is_shared_got_offset (int offset)
7895 return offset < llvm_acfg->nshared_got_entries;
7899 mono_aot_get_method_name (MonoCompile *cfg)
7901 if (llvm_acfg->aot_opts.static_link)
7902 /* Include the assembly name too to avoid duplicate symbol errors */
7903 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7905 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7909 * mono_aot_is_linkonce_method:
7911 * Return whenever METHOD should be emitted with linkonce linkage,
7912 * eliminating duplicate copies when compiling in static mode.
7915 mono_aot_is_linkonce_method (MonoMethod *method)
7921 // FIXME: Add more cases
7922 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7924 info = mono_marshal_get_wrapper_info (method);
7925 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7932 append_mangled_type (GString *s, MonoType *t)
7935 g_string_append_printf (s, "b");
7937 case MONO_TYPE_VOID:
7938 g_string_append_printf (s, "void_");
7941 g_string_append_printf (s, "i1");
7944 g_string_append_printf (s, "u1");
7947 g_string_append_printf (s, "i2");
7950 g_string_append_printf (s, "u2");
7953 g_string_append_printf (s, "i4");
7956 g_string_append_printf (s, "u4");
7959 g_string_append_printf (s, "i8");
7962 g_string_append_printf (s, "u8");
7965 g_string_append_printf (s, "ii");
7968 g_string_append_printf (s, "ui");
7971 g_string_append_printf (s, "fl");
7974 g_string_append_printf (s, "do");
7977 char *fullname = mono_type_full_name (t);
7983 * Have to create a mangled name which is:
7987 temp = g_string_new ("");
7988 len = strlen (fullname);
7989 for (i = 0; i < len; ++i) {
7990 char c = fullname [i];
7992 g_string_append_c (temp, c);
7993 } else if (c == '_') {
7994 g_string_append_c (temp, '_');
7995 g_string_append_c (temp, '_');
7997 g_string_append_c (temp, '_');
7998 g_string_append_printf (temp, "%x", (int)c);
8001 temps = g_string_free (temp, FALSE);
8002 /* Include the length to avoid different length type names aliasing each other */
8003 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8012 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8017 supported = append_mangled_type (s, sig->ret);
8021 g_string_append_printf (s, "this_");
8022 for (i = 0; i < sig->param_count; ++i) {
8023 supported = append_mangled_type (s, sig->params [i]);
8032 * mono_aot_get_mangled_method_name:
8034 * Return a unique mangled name for METHOD, or NULL.
8037 mono_aot_get_mangled_method_name (MonoMethod *method)
8043 // FIXME: Add more cases
8044 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8046 info = mono_marshal_get_wrapper_info (method);
8047 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8050 s = g_string_new ("");
8052 g_string_append_printf (s, "aot_method_w_");
8054 switch (info->subtype) {
8055 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8056 g_string_append_printf (s, "gsharedvt_in_");
8058 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8059 g_string_append_printf (s, "gsharedvt_out_");
8062 g_assert_not_reached ();
8066 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8068 g_string_free (s, TRUE);
8072 return g_string_free (s, FALSE);
8076 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8078 return is_direct_callable (llvm_acfg, NULL, patch_info);
8082 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8084 MonoPltEntry *plt_entry;
8086 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8087 plt_entry->llvm_used = FALSE;
8091 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8093 const char *sym = NULL;
8095 if (llvm_acfg->aot_opts.direct_icalls) {
8096 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8097 /* Call to a C function implementing a jit icall */
8098 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8099 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8100 MonoMethod *method = (MonoMethod *)data;
8101 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8102 sym = mono_lookup_icall_symbol (method);
8103 else if (llvm_acfg->aot_opts.direct_pinvoke)
8104 sym = get_pinvoke_import (llvm_acfg, method);
8107 return g_strdup (sym);
8113 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8115 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8116 MonoPltEntry *plt_entry;
8117 const char *sym = NULL;
8120 ji->data.target = data;
8122 if (!can_encode_patch (llvm_acfg, ji))
8125 if (llvm_acfg->aot_opts.direct_icalls) {
8126 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8127 /* Call to a C function implementing a jit icall */
8128 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8129 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8130 MonoMethod *method = (MonoMethod *)data;
8131 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8132 sym = mono_lookup_icall_symbol (method);
8135 return g_strdup (sym);
8138 plt_entry = get_plt_entry (llvm_acfg, ji);
8139 plt_entry->llvm_used = TRUE;
8141 #if defined(TARGET_MACH)
8142 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8144 return g_strdup_printf (plt_entry->llvm_symbol);
8149 mono_aot_get_method_index (MonoMethod *method)
8151 g_assert (llvm_acfg);
8152 return get_method_index (llvm_acfg, method);
8156 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8160 mono_acfg_lock (llvm_acfg);
8161 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8162 mono_acfg_unlock (llvm_acfg);
8168 execute_system (const char * command)
8173 // We need an extra set of quotes around the whole command to properly handle commands
8174 // with spaces since internally the command is called through "cmd /c.
8175 command = g_strdup_printf ("\"%s\"", command);
8177 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8178 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8179 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8180 status = _wsystem (wstr);
8184 #elif defined (HAVE_SYSTEM)
8185 status = system (command);
8187 g_assert_not_reached ();
8198 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8202 emit_llvm_file (MonoAotCompile *acfg)
8204 char *command, *opts, *tempbc, *optbc, *output_fname;
8206 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8207 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8208 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8210 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8211 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8214 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8217 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8218 * a lot of time, and doesn't seem to save much space.
8219 * The following optimizations cannot be enabled:
8221 * - 'jump-threading' changes our blockaddress references to int constants.
8222 * - 'basiccg' fails because it contains:
8223 * if (CS && !isa<IntrinsicInst>(II)) {
8224 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8225 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8226 * The opt list below was produced by taking the output of:
8227 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8228 * then removing tailcallelim + the global opts.
8229 * strip-dead-prototypes deletes unused intrinsics definitions.
8231 /* The dse pass is disabled because of #13734 and #17616 */
8233 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8234 * // If we have no DataLayout information around, then the size of the store
8235 * // is inferrable from the pointee type. If they are the same type, then
8236 * // we know that the store is safe.
8237 * if (AA.getDataLayout() == 0 &&
8238 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8239 * return OverwriteComplete;
8240 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8242 if (acfg->aot_opts.llvm_only)
8243 // FIXME: This doesn't work yet
8244 opts = g_strdup ("");
8246 #if LLVM_API_VERSION > 100
8247 opts = g_strdup ("-O2 -disable-tail-calls");
8249 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");
8251 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8252 aot_printf (acfg, "Executing opt: %s\n", command);
8253 if (execute_system (command) != 0)
8257 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8258 /* Nothing else to do */
8261 if (acfg->aot_opts.llvm_only) {
8262 /* Use the stock clang from xcode */
8264 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);
8266 aot_printf (acfg, "Executing clang: %s\n", command);
8267 if (execute_system (command) != 0)
8272 if (!acfg->llc_args)
8273 acfg->llc_args = g_string_new ("");
8275 /* Verbose asm slows down llc greatly */
8276 g_string_append (acfg->llc_args, " -asm-verbose=false");
8278 if (acfg->aot_opts.mtriple)
8279 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8281 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8283 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8285 #if LLVM_API_VERSION > 100
8286 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8289 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8290 /* ios requires PIC code now */
8291 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8293 if (llvm_acfg->aot_opts.static_link)
8294 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8296 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8299 if (acfg->llvm_owriter) {
8300 /* Emit an object file directly */
8301 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8302 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8304 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8306 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8307 g_free (output_fname);
8309 aot_printf (acfg, "Executing llc: %s\n", command);
8311 if (execute_system (command) != 0)
8318 emit_code (MonoAotCompile *acfg)
8320 int oindex, i, prev_index;
8321 gboolean saved_unbox_info = FALSE;
8322 char symbol [MAX_SYMBOL_SIZE];
8324 if (acfg->aot_opts.llvm_only)
8327 #if defined(TARGET_POWERPC64)
8328 sprintf (symbol, ".Lgot_addr");
8329 emit_section_change (acfg, ".text", 0);
8330 emit_alignment (acfg, 8);
8331 emit_label (acfg, symbol);
8332 emit_pointer (acfg, acfg->got_symbol);
8336 * This global symbol is used to compute the address of each method using the
8337 * code_offsets array. It is also used to compute the memory ranges occupied by
8338 * AOT code, so it must be equal to the address of the first emitted method.
8340 emit_section_change (acfg, ".text", 0);
8341 emit_alignment_code (acfg, 8);
8342 emit_info_symbol (acfg, "jit_code_start");
8345 * Emit some padding so the local symbol for the first method doesn't have the
8346 * same address as 'methods'.
8348 emit_padding (acfg, 16);
8350 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8354 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8356 cfg = acfg->cfgs [i];
8361 method = cfg->orig_method;
8363 /* Emit unbox trampoline */
8364 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8365 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8367 emit_section_change (acfg, ".text", 0);
8369 if (acfg->thumb_mixed && cfg->compile_llvm) {
8370 emit_set_thumb_mode (acfg);
8371 fprintf (acfg->fp, "\n.thumb_func\n");
8374 emit_label (acfg, symbol);
8376 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8378 if (acfg->thumb_mixed && cfg->compile_llvm)
8379 emit_set_arm_mode (acfg);
8381 if (!saved_unbox_info) {
8382 char user_symbol [128];
8384 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8386 emit_label (acfg, "ut_end");
8388 unwind_ops = mono_unwind_get_cie_program ();
8389 save_unwind_info (acfg, user_symbol, unwind_ops);
8390 mono_free_unwind_info (unwind_ops);
8392 /* Save the unbox trampoline size */
8393 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8395 saved_unbox_info = TRUE;
8399 if (cfg->compile_llvm)
8400 acfg->stats.llvm_count ++;
8402 emit_method_code (acfg, cfg);
8405 emit_section_change (acfg, ".text", 0);
8406 emit_alignment_code (acfg, 8);
8407 emit_info_symbol (acfg, "jit_code_end");
8409 /* To distinguish it from the next symbol */
8410 emit_padding (acfg, 4);
8413 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8414 * from optimizing them away, since it doesn't see that code_offsets references them.
8415 * JITted methods don't need this since they are referenced using assembler local
8417 * FIXME: This is why write-symbols doesn't work on OSX ?
8419 if (acfg->llvm && acfg->need_no_dead_strip) {
8420 fprintf (acfg->fp, "\n");
8421 for (i = 0; i < acfg->nmethods; ++i) {
8422 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8423 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8428 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8429 * This is PIE code, and the linker can update it if needed.
8432 sprintf (symbol, "method_addresses");
8433 emit_section_change (acfg, ".text", 1);
8434 emit_alignment_code (acfg, 8);
8435 emit_info_symbol (acfg, symbol);
8436 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8437 emit_unset_mode (acfg);
8438 if (acfg->need_no_dead_strip)
8439 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8441 for (i = 0; i < acfg->nmethods; ++i) {
8442 #ifdef MONO_ARCH_AOT_SUPPORTED
8445 if (acfg->cfgs [i]) {
8446 if (acfg->aot_opts.llvm_only && acfg->cfgs [i]->compile_llvm)
8447 /* Obtained by calling a generated function in the LLVM image */
8448 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8450 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8452 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8457 sprintf (symbol, "method_addresses_end");
8458 emit_label (acfg, symbol);
8461 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8462 sprintf (symbol, "unbox_trampolines");
8463 emit_section_change (acfg, RODATA_SECT, 0);
8464 emit_alignment (acfg, 8);
8465 emit_info_symbol (acfg, symbol);
8468 for (i = 0; i < acfg->nmethods; ++i) {
8473 cfg = acfg->cfgs [i];
8477 method = cfg->orig_method;
8479 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8480 index = get_method_index (acfg, method);
8482 emit_int32 (acfg, index);
8483 /* Make sure the table is sorted by index */
8484 g_assert (index > prev_index);
8488 sprintf (symbol, "unbox_trampolines_end");
8489 emit_info_symbol (acfg, symbol);
8490 emit_int32 (acfg, 0);
8492 /* Emit a separate table with the trampoline addresses/offsets */
8493 sprintf (symbol, "unbox_trampoline_addresses");
8494 emit_section_change (acfg, ".text", 0);
8495 emit_alignment_code (acfg, 8);
8496 emit_info_symbol (acfg, symbol);
8498 for (i = 0; i < acfg->nmethods; ++i) {
8503 cfg = acfg->cfgs [i];
8507 method = cfg->orig_method;
8509 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype && !(acfg->aot_opts.llvm_only && cfg->compile_llvm)) {
8510 #ifdef MONO_ARCH_AOT_SUPPORTED
8513 index = get_method_index (acfg, method);
8514 sprintf (symbol, "ut_%d", index);
8516 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8520 emit_int32 (acfg, 0);
8524 emit_info (MonoAotCompile *acfg)
8529 offsets = g_new0 (gint32, acfg->nmethods);
8531 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8532 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8534 if (acfg->cfgs [i]) {
8535 emit_method_info (acfg, acfg->cfgs [i]);
8536 offsets [i] = acfg->cfgs [i]->method_info_offset;
8542 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8547 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8549 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8550 #define mix(a,b,c) { \
8551 a -= c; a ^= rot(c, 4); c += b; \
8552 b -= a; b ^= rot(a, 6); a += c; \
8553 c -= b; c ^= rot(b, 8); b += a; \
8554 a -= c; a ^= rot(c,16); c += b; \
8555 b -= a; b ^= rot(a,19); a += c; \
8556 c -= b; c ^= rot(b, 4); b += a; \
8558 #define final(a,b,c) { \
8559 c ^= b; c -= rot(b,14); \
8560 a ^= c; a -= rot(c,11); \
8561 b ^= a; b -= rot(a,25); \
8562 c ^= b; c -= rot(b,16); \
8563 a ^= c; a -= rot(c,4); \
8564 b ^= a; b -= rot(a,14); \
8565 c ^= b; c -= rot(b,24); \
8569 mono_aot_type_hash (MonoType *t1)
8571 guint hash = t1->type;
8573 hash |= t1->byref << 6; /* do not collide with t1->type values */
8575 case MONO_TYPE_VALUETYPE:
8576 case MONO_TYPE_CLASS:
8577 case MONO_TYPE_SZARRAY:
8578 /* check if the distribution is good enough */
8579 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8581 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8582 case MONO_TYPE_ARRAY:
8583 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8584 case MONO_TYPE_GENERICINST:
8585 return ((hash << 5) - hash) ^ 0;
8592 * mono_aot_method_hash:
8594 * Return a hash code for methods which only depends on metadata.
8597 mono_aot_method_hash (MonoMethod *method)
8599 MonoMethodSignature *sig;
8603 guint32 *hashes_start, *hashes;
8605 MonoGenericInst *class_ginst = NULL;
8606 MonoGenericInst *ginst = NULL;
8608 /* Similar to the hash in mono_method_get_imt_slot () */
8610 sig = mono_method_signature (method);
8612 if (method->klass->generic_class)
8613 class_ginst = method->klass->generic_class->context.class_inst;
8614 if (method->is_inflated)
8615 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8617 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8618 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8619 hashes = hashes_start;
8621 /* Some wrappers are assigned to random classes */
8622 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8623 klass = method->klass;
8625 klass = mono_defaults.object_class;
8627 if (!method->wrapper_type) {
8630 if (klass->generic_class)
8631 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8633 full_name = mono_type_full_name (&klass->byval_arg);
8635 hashes [0] = mono_metadata_str_hash (full_name);
8639 hashes [0] = mono_metadata_str_hash (klass->name);
8640 hashes [1] = mono_metadata_str_hash (klass->name_space);
8642 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8643 /* The method name includes a stringified pointer */
8646 hashes [2] = mono_metadata_str_hash (method->name);
8647 hashes [3] = method->wrapper_type;
8648 hashes [4] = mono_aot_type_hash (sig->ret);
8650 for (i = 0; i < sig->param_count; i++) {
8651 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8654 for (i = 0; i < class_ginst->type_argc; ++i)
8655 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8658 for (i = 0; i < ginst->type_argc; ++i)
8659 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8661 g_assert (hindex == hashes_count);
8663 /* Setup internal state */
8664 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8666 /* Handle most of the hashes */
8667 while (hashes_count > 3) {
8676 /* Handle the last 3 hashes (all the case statements fall through) */
8677 switch (hashes_count) {
8678 case 3 : c += hashes [2];
8679 case 2 : b += hashes [1];
8680 case 1 : a += hashes [0];
8682 case 0: /* nothing left to add */
8686 free (hashes_start);
8695 * mono_aot_get_array_helper_from_wrapper;
8697 * Get the helper method in Array called by an array wrapper method.
8700 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8704 MonoGenericContext ctx;
8705 MonoType *args [16];
8706 char *mname, *iname, *s, *s2, *helper_name = NULL;
8708 prefix = "System.Collections.Generic";
8709 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8710 s2 = strstr (s, "`1.");
8716 //printf ("X: %s %s\n", iname, mname);
8718 if (!strcmp (iname, "IList"))
8719 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8721 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8722 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8724 g_free (helper_name);
8727 if (m->is_generic) {
8729 memset (&ctx, 0, sizeof (ctx));
8730 args [0] = &method->klass->element_class->byval_arg;
8731 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8732 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8733 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8739 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8741 typedef struct HashEntry {
8742 guint32 key, value, index;
8743 struct HashEntry *next;
8747 * emit_extra_methods:
8749 * Emit methods which are not in the METHOD table, like wrappers.
8752 emit_extra_methods (MonoAotCompile *acfg)
8754 int i, table_size, buf_size;
8756 guint32 *info_offsets;
8759 HashEntry *entry, *new_entry;
8760 int nmethods, max_chain_length;
8763 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8765 /* Emit method info */
8767 for (i = 0; i < acfg->extra_methods->len; ++i) {
8768 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8769 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8775 p = buf = (guint8 *)g_malloc (buf_size);
8779 method = cfg->method_to_register;
8781 encode_method_ref (acfg, method, p, &p);
8783 g_assert ((p - buf) < buf_size);
8785 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8790 * Construct a chained hash table for mapping indexes in extra_method_info to
8793 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8794 table = g_ptr_array_sized_new (table_size);
8795 for (i = 0; i < table_size; ++i)
8796 g_ptr_array_add (table, NULL);
8797 chain_lengths = g_new0 (int, table_size);
8798 max_chain_length = 0;
8799 for (i = 0; i < acfg->extra_methods->len; ++i) {
8800 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8801 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8807 key = info_offsets [i];
8808 value = get_method_index (acfg, method);
8810 hash = mono_aot_method_hash (method) % table_size;
8811 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8813 chain_lengths [hash] ++;
8814 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8816 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8817 new_entry->key = key;
8818 new_entry->value = value;
8820 entry = (HashEntry *)g_ptr_array_index (table, hash);
8821 if (entry == NULL) {
8822 new_entry->index = hash;
8823 g_ptr_array_index (table, hash) = new_entry;
8826 entry = entry->next;
8828 entry->next = new_entry;
8829 new_entry->index = table->len;
8830 g_ptr_array_add (table, new_entry);
8833 g_free (chain_lengths);
8835 //printf ("MAX: %d\n", max_chain_length);
8837 buf_size = table->len * 12 + 4;
8838 p = buf = (guint8 *)g_malloc (buf_size);
8839 encode_int (table_size, p, &p);
8841 for (i = 0; i < table->len; ++i) {
8842 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8844 if (entry == NULL) {
8845 encode_int (0, p, &p);
8846 encode_int (0, p, &p);
8847 encode_int (0, p, &p);
8849 //g_assert (entry->key > 0);
8850 encode_int (entry->key, p, &p);
8851 encode_int (entry->value, p, &p);
8853 encode_int (entry->next->index, p, &p);
8855 encode_int (0, p, &p);
8858 g_assert (p - buf <= buf_size);
8860 /* Emit the table */
8861 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8866 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8867 * This is used by mono_aot_find_jit_info ().
8869 buf_size = acfg->extra_methods->len * 8 + 4;
8870 p = buf = (guint8 *)g_malloc (buf_size);
8871 encode_int (acfg->extra_methods->len, p, &p);
8872 for (i = 0; i < acfg->extra_methods->len; ++i) {
8873 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8875 encode_int (get_method_index (acfg, method), p, &p);
8876 encode_int (info_offsets [i], p, &p);
8878 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8881 g_free (info_offsets);
8882 g_ptr_array_free (table, TRUE);
8886 generate_aotid (guint8* aotid)
8888 gpointer *rand_handle;
8892 rand_handle = mono_rand_init (NULL, 0);
8894 mono_rand_try_get_bytes (rand_handle, aotid, 16, &error);
8895 mono_error_assert_ok (&error);
8897 mono_rand_close (rand_handle);
8901 emit_exception_info (MonoAotCompile *acfg)
8905 SeqPointData sp_data;
8906 gboolean seq_points_to_file = FALSE;
8908 offsets = g_new0 (gint32, acfg->nmethods);
8909 for (i = 0; i < acfg->nmethods; ++i) {
8910 if (acfg->cfgs [i]) {
8911 MonoCompile *cfg = acfg->cfgs [i];
8913 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8914 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8915 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8916 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8917 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8919 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8920 offsets [i] = cfg->ex_info_offset;
8922 if (method_seq_points_to_file) {
8923 if (!seq_points_to_file) {
8924 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8925 seq_points_to_file = TRUE;
8927 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8934 if (seq_points_to_file) {
8935 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8936 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8937 char *image_basename = g_path_get_basename (acfg->image->name);
8938 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8939 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8941 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8942 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8946 mono_seq_point_data_write (&sp_data, aot_file_path);
8947 mono_seq_point_data_free (&sp_data);
8951 g_free (image_basename);
8953 g_free (aot_file_path);
8956 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8961 emit_unwind_info (MonoAotCompile *acfg)
8966 if (acfg->aot_opts.llvm_only) {
8967 g_assert (acfg->unwind_ops->len == 0);
8972 * The unwind info contains a lot of duplicates so we emit each unique
8973 * entry once, and only store the offset from the start of the table in the
8977 sprintf (symbol, "unwind_info");
8978 emit_section_change (acfg, RODATA_SECT, 1);
8979 emit_alignment (acfg, 8);
8980 emit_info_symbol (acfg, symbol);
8982 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8983 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8984 guint8 *unwind_info;
8985 guint32 unwind_info_len;
8989 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
8992 encode_value (unwind_info_len, p, &p);
8993 emit_bytes (acfg, buf, p - buf);
8994 emit_bytes (acfg, unwind_info, unwind_info_len);
8996 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9001 emit_class_info (MonoAotCompile *acfg)
9006 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9007 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9008 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9010 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);
9014 typedef struct ClassNameTableEntry {
9015 guint32 token, index;
9016 struct ClassNameTableEntry *next;
9017 } ClassNameTableEntry;
9020 emit_class_name_table (MonoAotCompile *acfg)
9022 int i, table_size, buf_size;
9023 guint32 token, hash;
9028 ClassNameTableEntry *entry, *new_entry;
9031 * Construct a chained hash table for mapping class names to typedef tokens.
9033 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9034 table = g_ptr_array_sized_new (table_size);
9035 for (i = 0; i < table_size; ++i)
9036 g_ptr_array_add (table, NULL);
9037 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9039 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9040 klass = mono_class_get_checked (acfg->image, token, &error);
9042 mono_error_cleanup (&error);
9045 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9046 hash = mono_metadata_str_hash (full_name) % table_size;
9049 /* FIXME: Allocate from the mempool */
9050 new_entry = g_new0 (ClassNameTableEntry, 1);
9051 new_entry->token = token;
9053 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9054 if (entry == NULL) {
9055 new_entry->index = hash;
9056 g_ptr_array_index (table, hash) = new_entry;
9059 entry = entry->next;
9061 entry->next = new_entry;
9062 new_entry->index = table->len;
9063 g_ptr_array_add (table, new_entry);
9067 /* Emit the table */
9068 buf_size = table->len * 4 + 4;
9069 p = buf = (guint8 *)g_malloc0 (buf_size);
9071 /* FIXME: Optimize memory usage */
9072 g_assert (table_size < 65000);
9073 encode_int16 (table_size, p, &p);
9074 g_assert (table->len < 65000);
9075 for (i = 0; i < table->len; ++i) {
9076 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9078 if (entry == NULL) {
9079 encode_int16 (0, p, &p);
9080 encode_int16 (0, p, &p);
9082 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9084 encode_int16 (entry->next->index, p, &p);
9086 encode_int16 (0, p, &p);
9090 g_assert (p - buf <= buf_size);
9091 g_ptr_array_free (table, TRUE);
9093 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9099 emit_image_table (MonoAotCompile *acfg)
9105 * The image table is small but referenced in a lot of places.
9106 * So we emit it at once, and reference its elements by an index.
9108 buf_size = acfg->image_table->len * 28 + 4;
9109 for (i = 0; i < acfg->image_table->len; i++) {
9110 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9111 MonoAssemblyName *aname = &image->assembly->aname;
9113 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9116 buf = p = (guint8 *)g_malloc0 (buf_size);
9117 encode_int (acfg->image_table->len, p, &p);
9118 for (i = 0; i < acfg->image_table->len; i++) {
9119 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9120 MonoAssemblyName *aname = &image->assembly->aname;
9122 /* FIXME: Support multi-module assemblies */
9123 g_assert (image->assembly->image == image);
9125 encode_string (image->assembly_name, p, &p);
9126 encode_string (image->guid, p, &p);
9127 encode_string (aname->culture ? aname->culture : "", p, &p);
9128 encode_string ((const char*)aname->public_key_token, p, &p);
9130 while (GPOINTER_TO_UINT (p) % 8 != 0)
9133 encode_int (aname->flags, p, &p);
9134 encode_int (aname->major, p, &p);
9135 encode_int (aname->minor, p, &p);
9136 encode_int (aname->build, p, &p);
9137 encode_int (aname->revision, p, &p);
9139 g_assert (p - buf <= buf_size);
9141 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9147 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9149 int i, first_plt_got_patch = 0, buf_size;
9151 guint32 *got_info_offsets;
9152 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9154 /* Add the patches needed by the PLT to the GOT */
9156 acfg->plt_got_offset_base = acfg->got_offset;
9157 first_plt_got_patch = info->got_patches->len;
9158 for (i = 1; i < acfg->plt_offset; ++i) {
9159 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9161 g_ptr_array_add (info->got_patches, plt_entry->ji);
9163 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9166 acfg->got_offset += acfg->plt_offset;
9171 * - optimize offsets table.
9172 * - reduce number of exported symbols.
9173 * - emit info for a klass only once.
9174 * - determine when a method uses a GOT slot which is guaranteed to be already
9176 * - clean up and document the code.
9177 * - use String.Empty in class libs.
9180 /* Encode info required to decode shared GOT entries */
9181 buf_size = info->got_patches->len * 128;
9182 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9183 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9185 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9187 if (acfg->plt_offset)
9188 acfg->plt_got_info_offsets [0] = 0;
9190 for (i = 0; i < info->got_patches->len; ++i) {
9191 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9196 encode_value (ji->type, p, &p);
9198 encode_patch (acfg, ji, p, &p);
9199 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9200 g_assert (p - buf <= buf_size);
9201 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9203 if (!llvm && i >= first_plt_got_patch)
9204 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9205 acfg->stats.got_info_size += p - buf;
9208 /* Emit got_info_offsets table */
9210 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9211 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);
9215 emit_got (MonoAotCompile *acfg)
9217 char symbol [MAX_SYMBOL_SIZE];
9219 if (acfg->aot_opts.llvm_only)
9222 /* Don't make GOT global so accesses to it don't need relocations */
9223 sprintf (symbol, "%s", acfg->got_symbol);
9226 emit_unset_mode (acfg);
9227 fprintf (acfg->fp, ".section __DATA, __bss\n");
9228 emit_alignment (acfg, 8);
9230 emit_info_symbol (acfg, "jit_got");
9231 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9233 emit_section_change (acfg, ".bss", 0);
9234 emit_alignment (acfg, 8);
9235 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9236 emit_label (acfg, symbol);
9238 emit_info_symbol (acfg, "jit_got");
9239 if (acfg->got_offset > 0)
9240 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9243 sprintf (symbol, "got_end");
9244 emit_label (acfg, symbol);
9247 typedef struct GlobalsTableEntry {
9248 guint32 value, index;
9249 struct GlobalsTableEntry *next;
9250 } GlobalsTableEntry;
9253 emit_globals (MonoAotCompile *acfg)
9259 GlobalsTableEntry *entry, *new_entry;
9261 if (!acfg->aot_opts.static_link)
9263 if (acfg->aot_opts.llvm_only) {
9264 g_assert (acfg->globals->len == 0);
9269 * When static linking, we emit a table containing our globals.
9273 * Construct a chained hash table for mapping global names to their index in
9274 * the globals table.
9276 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9277 table = g_ptr_array_sized_new (table_size);
9278 for (i = 0; i < table_size; ++i)
9279 g_ptr_array_add (table, NULL);
9280 for (i = 0; i < acfg->globals->len; ++i) {
9281 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9283 hash = mono_metadata_str_hash (name) % table_size;
9285 /* FIXME: Allocate from the mempool */
9286 new_entry = g_new0 (GlobalsTableEntry, 1);
9287 new_entry->value = i;
9289 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9290 if (entry == NULL) {
9291 new_entry->index = hash;
9292 g_ptr_array_index (table, hash) = new_entry;
9295 entry = entry->next;
9297 entry->next = new_entry;
9298 new_entry->index = table->len;
9299 g_ptr_array_add (table, new_entry);
9303 /* Emit the table */
9304 sprintf (symbol, ".Lglobals_hash");
9305 emit_section_change (acfg, RODATA_SECT, 0);
9306 emit_alignment (acfg, 8);
9307 emit_label (acfg, symbol);
9309 /* FIXME: Optimize memory usage */
9310 g_assert (table_size < 65000);
9311 emit_int16 (acfg, table_size);
9312 for (i = 0; i < table->len; ++i) {
9313 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9315 if (entry == NULL) {
9316 emit_int16 (acfg, 0);
9317 emit_int16 (acfg, 0);
9319 emit_int16 (acfg, entry->value + 1);
9321 emit_int16 (acfg, entry->next->index);
9323 emit_int16 (acfg, 0);
9327 /* Emit the names */
9328 for (i = 0; i < acfg->globals->len; ++i) {
9329 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9331 sprintf (symbol, "name_%d", i);
9332 emit_section_change (acfg, RODATA_SECT, 1);
9334 emit_alignment (acfg, 4);
9336 emit_label (acfg, symbol);
9337 emit_string (acfg, name);
9340 /* Emit the globals table */
9341 sprintf (symbol, "globals");
9342 emit_section_change (acfg, ".data", 0);
9343 /* This is not a global, since it is accessed by the init function */
9344 emit_alignment (acfg, 8);
9345 emit_info_symbol (acfg, symbol);
9347 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9348 emit_pointer (acfg, symbol);
9350 for (i = 0; i < acfg->globals->len; ++i) {
9351 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9353 sprintf (symbol, "name_%d", i);
9354 emit_pointer (acfg, symbol);
9356 g_assert (strlen (name) < sizeof (symbol));
9357 sprintf (symbol, "%s", name);
9358 emit_pointer (acfg, symbol);
9360 /* Null terminate the table */
9361 emit_int32 (acfg, 0);
9362 emit_int32 (acfg, 0);
9366 emit_mem_end (MonoAotCompile *acfg)
9370 if (acfg->aot_opts.llvm_only)
9373 sprintf (symbol, "mem_end");
9374 emit_section_change (acfg, ".text", 1);
9375 emit_alignment_code (acfg, 8);
9376 emit_label (acfg, symbol);
9380 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9384 info->version = MONO_AOT_FILE_VERSION;
9385 info->plt_got_offset_base = acfg->plt_got_offset_base;
9386 info->got_size = acfg->got_offset * sizeof (gpointer);
9387 info->plt_size = acfg->plt_offset;
9388 info->nmethods = acfg->nmethods;
9389 info->flags = acfg->flags;
9390 info->opts = acfg->opts;
9391 info->simd_opts = acfg->simd_opts;
9392 info->gc_name_index = acfg->gc_name_offset;
9393 info->datafile_size = acfg->datafile_offset;
9394 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9395 info->table_offsets [i] = acfg->table_offsets [i];
9396 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9397 info->num_trampolines [i] = acfg->num_trampolines [i];
9398 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9399 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9400 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9401 info->trampoline_size [i] = acfg->trampoline_size [i];
9402 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9404 info->double_align = MONO_ABI_ALIGNOF (double);
9405 info->long_align = MONO_ABI_ALIGNOF (gint64);
9406 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9407 info->tramp_page_size = acfg->tramp_page_size;
9408 info->nshared_got_entries = acfg->nshared_got_entries;
9409 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9410 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9412 memcpy(&info->aotid, acfg->image->aotid, 16);
9416 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9418 char symbol [MAX_SYMBOL_SIZE];
9420 const char **symbols;
9422 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9424 symbols [sindex ++] = acfg->got_symbol;
9426 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9427 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9429 symbols [sindex ++] = NULL;
9430 symbols [sindex ++] = NULL;
9432 /* llvm_get_method */
9433 symbols [sindex ++] = NULL;
9434 /* llvm_get_unbox_tramp */
9435 symbols [sindex ++] = NULL;
9436 if (!acfg->aot_opts.llvm_only) {
9437 symbols [sindex ++] = "jit_code_start";
9438 symbols [sindex ++] = "jit_code_end";
9439 symbols [sindex ++] = "method_addresses";
9441 symbols [sindex ++] = NULL;
9442 symbols [sindex ++] = NULL;
9443 symbols [sindex ++] = NULL;
9445 if (acfg->data_outfile) {
9446 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9447 symbols [sindex ++] = NULL;
9449 symbols [sindex ++] = "blob";
9450 symbols [sindex ++] = "class_name_table";
9451 symbols [sindex ++] = "class_info_offsets";
9452 symbols [sindex ++] = "method_info_offsets";
9453 symbols [sindex ++] = "ex_info_offsets";
9454 symbols [sindex ++] = "extra_method_info_offsets";
9455 symbols [sindex ++] = "extra_method_table";
9456 symbols [sindex ++] = "got_info_offsets";
9458 symbols [sindex ++] = "llvm_got_info_offsets";
9460 symbols [sindex ++] = NULL;
9461 symbols [sindex ++] = "image_table";
9463 symbols [sindex ++] = "mem_end";
9464 symbols [sindex ++] = "assembly_guid";
9465 symbols [sindex ++] = "runtime_version";
9466 if (acfg->num_trampoline_got_entries) {
9467 symbols [sindex ++] = "specific_trampolines";
9468 symbols [sindex ++] = "static_rgctx_trampolines";
9469 symbols [sindex ++] = "imt_thunks";
9470 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9472 symbols [sindex ++] = NULL;
9473 symbols [sindex ++] = NULL;
9474 symbols [sindex ++] = NULL;
9475 symbols [sindex ++] = NULL;
9477 if (acfg->aot_opts.static_link) {
9478 symbols [sindex ++] = "globals";
9480 symbols [sindex ++] = NULL;
9482 symbols [sindex ++] = "assembly_name";
9483 symbols [sindex ++] = "plt";
9484 symbols [sindex ++] = "plt_end";
9485 symbols [sindex ++] = "unwind_info";
9486 if (!acfg->aot_opts.llvm_only) {
9487 symbols [sindex ++] = "unbox_trampolines";
9488 symbols [sindex ++] = "unbox_trampolines_end";
9489 symbols [sindex ++] = "unbox_trampoline_addresses";
9491 symbols [sindex ++] = NULL;
9492 symbols [sindex ++] = NULL;
9493 symbols [sindex ++] = NULL;
9496 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9498 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9499 emit_section_change (acfg, ".data", 0);
9500 emit_alignment (acfg, 8);
9501 emit_label (acfg, symbol);
9502 if (!acfg->aot_opts.static_link)
9503 emit_global (acfg, symbol, FALSE);
9505 /* The data emitted here must match MonoAotFileInfo. */
9507 emit_int32 (acfg, info->version);
9508 emit_int32 (acfg, info->dummy);
9511 * We emit pointers to our data structures instead of emitting global symbols which
9512 * point to them, to reduce the number of globals, and because using globals leads to
9513 * various problems (i.e. arm/thumb).
9515 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9516 emit_pointer (acfg, symbols [i]);
9518 emit_int32 (acfg, info->plt_got_offset_base);
9519 emit_int32 (acfg, info->got_size);
9520 emit_int32 (acfg, info->plt_size);
9521 emit_int32 (acfg, info->nmethods);
9522 emit_int32 (acfg, info->flags);
9523 emit_int32 (acfg, info->opts);
9524 emit_int32 (acfg, info->simd_opts);
9525 emit_int32 (acfg, info->gc_name_index);
9526 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9527 emit_int32 (acfg, info->double_align);
9528 emit_int32 (acfg, info->long_align);
9529 emit_int32 (acfg, info->generic_tramp_num);
9530 emit_int32 (acfg, info->tramp_page_size);
9531 emit_int32 (acfg, info->nshared_got_entries);
9532 emit_int32 (acfg, info->datafile_size);
9534 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9535 emit_int32 (acfg, info->table_offsets [i]);
9536 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9537 emit_int32 (acfg, info->num_trampolines [i]);
9538 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9539 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9540 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9541 emit_int32 (acfg, info->trampoline_size [i]);
9542 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9543 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9545 emit_bytes (acfg, info->aotid, 16);
9547 if (acfg->aot_opts.static_link) {
9548 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9549 emit_alignment (acfg, sizeof (gpointer));
9550 emit_label (acfg, acfg->static_linking_symbol);
9551 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9556 * Emit a structure containing all the information not stored elsewhere.
9559 emit_file_info (MonoAotCompile *acfg)
9562 MonoAotFileInfo *info;
9564 if (acfg->aot_opts.bind_to_runtime_version) {
9565 build_info = mono_get_runtime_build_info ();
9566 emit_string_symbol (acfg, "runtime_version", build_info);
9567 g_free (build_info);
9569 emit_string_symbol (acfg, "runtime_version", "");
9572 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9574 /* Emit a string holding the assembly name */
9575 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9577 info = g_new0 (MonoAotFileInfo, 1);
9578 init_aot_file_info (acfg, info);
9580 if (acfg->aot_opts.static_link) {
9581 char symbol [MAX_SYMBOL_SIZE];
9585 * Emit a global symbol which can be passed by an embedding app to
9586 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9589 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9591 /* Get rid of characters which cannot occur in symbols */
9593 for (p = symbol; *p; ++p) {
9594 if (!(isalnum (*p) || *p == '_'))
9597 acfg->static_linking_symbol = g_strdup (symbol);
9601 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9603 emit_aot_file_info (acfg, info);
9607 emit_blob (MonoAotCompile *acfg)
9609 acfg->blob_closed = TRUE;
9611 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9615 emit_objc_selectors (MonoAotCompile *acfg)
9620 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9625 * cat > foo.m << EOF
9628 * return @selector(print:);
9633 mono_img_writer_emit_unset_mode (acfg->w);
9634 g_assert (acfg->fp);
9635 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9636 fprintf (acfg->fp, ".align 3\n");
9637 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9638 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9639 emit_label (acfg, symbol);
9640 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9641 emit_pointer (acfg, symbol);
9644 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9645 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9646 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9647 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9650 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9651 fprintf (acfg->fp, ".align 3\n");
9652 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9653 fprintf (acfg->fp, ".long 0\n");
9654 fprintf (acfg->fp, ".long 16\n");
9658 emit_dwarf_info (MonoAotCompile *acfg)
9660 #ifdef EMIT_DWARF_INFO
9664 /* DIEs for methods */
9665 for (i = 0; i < acfg->nmethods; ++i) {
9666 MonoCompile *cfg = acfg->cfgs [i];
9671 // FIXME: LLVM doesn't define .Lme_...
9672 if (cfg->compile_llvm)
9675 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9677 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 ()));
9683 collect_methods (MonoAotCompile *acfg)
9686 MonoImage *image = acfg->image;
9688 /* Collect methods */
9689 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9692 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9694 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9697 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9698 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9699 mono_error_cleanup (&error);
9703 /* Load all methods eagerly to skip the slower lazy loading code */
9704 mono_class_setup_methods (method->klass);
9706 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9707 /* Compile the wrapper instead */
9708 /* We do this here instead of add_wrappers () because it is easy to do it here */
9709 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9713 /* FIXME: Some mscorlib methods don't have debug info */
9715 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9716 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9717 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9718 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9719 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9720 if (!mono_debug_lookup_method (method)) {
9721 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9728 if (method->is_generic || method->klass->generic_container)
9729 /* Compile the ref shared version instead */
9730 method = mini_get_shared_method (method);
9732 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9733 add_method_with_index (acfg, method, i, FALSE);
9734 acfg->method_index ++;
9737 /* gsharedvt methods */
9738 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9741 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9743 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9746 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9747 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9749 if (method->is_generic || method->klass->generic_container) {
9750 MonoMethod *gshared;
9752 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9753 add_extra_method (acfg, gshared);
9757 add_generic_instances (acfg);
9759 if (mono_aot_mode_is_full (&acfg->aot_opts))
9760 add_wrappers (acfg);
9765 compile_methods (MonoAotCompile *acfg)
9769 if (acfg->aot_opts.nthreads > 0) {
9774 gpointer *user_data;
9775 MonoMethod **methods;
9778 methods_len = acfg->methods->len;
9780 len = acfg->methods->len / acfg->aot_opts.nthreads;
9783 * Partition the list of methods into fragments, and hand it to threads to
9786 threads = g_ptr_array_new ();
9787 /* Make a copy since acfg->methods is modified by compile_method () */
9788 methods = g_new0 (MonoMethod*, methods_len);
9789 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9790 for (i = 0; i < methods_len; ++i)
9791 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9793 while (i < methods_len) {
9794 frag = g_ptr_array_new ();
9795 for (j = 0; j < len; ++j) {
9796 if (i < methods_len) {
9797 g_ptr_array_add (frag, methods [i]);
9802 user_data = g_new0 (gpointer, 3);
9803 user_data [0] = mono_domain_get ();
9804 user_data [1] = acfg;
9805 user_data [2] = frag;
9809 tp.creation_flags = 0;
9810 handle = mono_threads_create_thread ((LPTHREAD_START_ROUTINE)compile_thread_main, user_data, &tp, NULL);
9811 g_ptr_array_add (threads, handle);
9815 for (i = 0; i < threads->len; ++i) {
9816 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9822 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9823 for (i = methods_len; i < acfg->methods->len; ++i) {
9824 /* This can new methods to acfg->methods */
9825 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9830 compile_asm (MonoAotCompile *acfg)
9832 char *command, *objfile;
9833 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9834 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9835 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9837 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9838 #define AS_OPTIONS "--64"
9839 #elif defined(TARGET_POWERPC64)
9840 #define AS_OPTIONS "-a64 -mppc64"
9841 #elif defined(sparc) && SIZEOF_VOID_P == 8
9842 #define AS_OPTIONS "-xarch=v9"
9843 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9844 #define AS_OPTIONS "-arch i386"
9846 #define AS_OPTIONS ""
9849 #ifdef __native_client_codegen__
9850 #if defined(TARGET_AMD64)
9851 #define AS_NAME "nacl64-as"
9853 #define AS_NAME "nacl-as"
9855 #elif defined(TARGET_OSX)
9856 #define AS_NAME "clang"
9858 #define AS_NAME "as"
9862 #define LD_NAME "ld"
9863 #define LD_OPTIONS "-shared -G"
9864 #elif defined(__ppc__) && defined(TARGET_MACH)
9865 #define LD_NAME "gcc"
9866 #define LD_OPTIONS "-dynamiclib"
9867 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9868 #define LD_NAME "clang"
9869 #define LD_OPTIONS "--shared"
9870 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9871 #define LD_NAME "gcc"
9872 #define LD_OPTIONS "-shared"
9873 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9874 #define LD_NAME "clang"
9875 #define LD_OPTIONS "-m32 -dynamiclib"
9876 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9877 #define LD_NAME "gcc"
9878 #define LD_OPTIONS "--shared"
9879 #elif defined(TARGET_POWERPC64)
9880 #define LD_OPTIONS "-m elf64ppc"
9884 #define LD_OPTIONS ""
9887 if (acfg->aot_opts.asm_only) {
9888 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9889 if (acfg->aot_opts.static_link)
9890 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9892 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9896 if (acfg->aot_opts.static_link) {
9897 if (acfg->aot_opts.outfile)
9898 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9900 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9902 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9906 g_string_append (acfg->as_args, "-c -x assembler");
9909 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9910 acfg->as_args ? acfg->as_args->str : "",
9911 wrap_path (objfile), wrap_path (acfg->tmpfname));
9912 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9913 if (execute_system (command) != 0) {
9919 if (acfg->llvm && !acfg->llvm_owriter) {
9920 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9921 acfg->as_args ? acfg->as_args->str : "",
9922 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9923 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9924 if (execute_system (command) != 0) {
9933 if (acfg->aot_opts.static_link) {
9934 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9935 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9940 if (acfg->aot_opts.outfile)
9941 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9943 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9945 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9948 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9950 llvm_ofile = g_strdup ("");
9953 /* replace the ; flags separators with spaces */
9954 g_strdelimit (ld_flags, ";", ' ');
9956 if (acfg->aot_opts.llvm_only)
9957 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9960 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
9961 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9962 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9965 char *args = g_strdup_printf ("%s %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9966 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9967 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9970 command = g_strdup_printf ("clang++ %s", args);
9972 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
9977 aot_printf (acfg, "Executing the native linker: %s\n", command);
9978 if (execute_system (command) != 0) {
9979 g_free (tmp_outfile_name);
9980 g_free (outfile_name);
9989 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
9990 printf ("Stripping the binary: %s\n", com);
9991 execute_system (com);
9994 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
9996 * gas generates 'mapping symbols' each time code and data is mixed, which
9997 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
9999 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10000 aot_printf (acfg, "Stripping the binary: %s\n", command);
10001 if (execute_system (command) != 0) {
10002 g_free (tmp_outfile_name);
10003 g_free (outfile_name);
10010 if (0 != rename (tmp_outfile_name, outfile_name)) {
10011 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10012 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10013 unlink (outfile_name);
10014 rename (tmp_outfile_name, outfile_name);
10018 #if defined(TARGET_MACH)
10019 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10020 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10021 if (execute_system (command) != 0) {
10026 if (!acfg->aot_opts.save_temps)
10029 g_free (tmp_outfile_name);
10030 g_free (outfile_name);
10033 if (acfg->aot_opts.save_temps)
10034 aot_printf (acfg, "Retained input file.\n");
10036 unlink (acfg->tmpfname);
10041 static void init_got_info (GotInfo *info)
10045 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10046 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10047 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10048 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10049 info->got_patches = g_ptr_array_new ();
10052 static MonoAotCompile*
10053 acfg_create (MonoAssembly *ass, guint32 opts)
10055 MonoImage *image = ass->image;
10056 MonoAotCompile *acfg;
10058 acfg = g_new0 (MonoAotCompile, 1);
10059 acfg->methods = g_ptr_array_new ();
10060 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10061 acfg->method_depth = g_hash_table_new (NULL, NULL);
10062 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10063 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10064 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10065 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10066 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10067 acfg->image_hash = g_hash_table_new (NULL, NULL);
10068 acfg->image_table = g_ptr_array_new ();
10069 acfg->globals = g_ptr_array_new ();
10070 acfg->image = image;
10072 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10073 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10074 acfg->mempool = mono_mempool_new ();
10075 acfg->extra_methods = g_ptr_array_new ();
10076 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10077 acfg->unwind_ops = g_ptr_array_new ();
10078 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10079 acfg->method_order = g_ptr_array_new ();
10080 acfg->export_names = g_hash_table_new (NULL, NULL);
10081 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10082 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10083 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10084 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10085 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10086 mono_os_mutex_init_recursive (&acfg->mutex);
10088 init_got_info (&acfg->got_info);
10089 init_got_info (&acfg->llvm_got_info);
10095 got_info_free (GotInfo *info)
10099 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10100 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10101 g_free (info->patch_to_got_offset_by_type);
10102 g_hash_table_destroy (info->patch_to_got_offset);
10103 g_ptr_array_free (info->got_patches, TRUE);
10107 acfg_free (MonoAotCompile *acfg)
10111 mono_img_writer_destroy (acfg->w);
10112 for (i = 0; i < acfg->nmethods; ++i)
10113 if (acfg->cfgs [i])
10114 mono_destroy_compile (acfg->cfgs [i]);
10116 g_free (acfg->cfgs);
10118 g_free (acfg->static_linking_symbol);
10119 g_free (acfg->got_symbol);
10120 g_free (acfg->plt_symbol);
10121 g_ptr_array_free (acfg->methods, TRUE);
10122 g_ptr_array_free (acfg->image_table, TRUE);
10123 g_ptr_array_free (acfg->globals, TRUE);
10124 g_ptr_array_free (acfg->unwind_ops, TRUE);
10125 g_hash_table_destroy (acfg->method_indexes);
10126 g_hash_table_destroy (acfg->method_depth);
10127 g_hash_table_destroy (acfg->plt_offset_to_entry);
10128 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10129 if (acfg->patch_to_plt_entry [i])
10130 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10132 g_free (acfg->patch_to_plt_entry);
10133 g_hash_table_destroy (acfg->method_to_cfg);
10134 g_hash_table_destroy (acfg->token_info_hash);
10135 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10136 g_hash_table_destroy (acfg->image_hash);
10137 g_hash_table_destroy (acfg->unwind_info_offsets);
10138 g_hash_table_destroy (acfg->method_label_hash);
10139 if (acfg->typespec_classes)
10140 g_hash_table_destroy (acfg->typespec_classes);
10141 g_hash_table_destroy (acfg->export_names);
10142 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10143 g_hash_table_destroy (acfg->klass_blob_hash);
10144 g_hash_table_destroy (acfg->method_blob_hash);
10145 got_info_free (&acfg->got_info);
10146 got_info_free (&acfg->llvm_got_info);
10147 mono_mempool_destroy (acfg->mempool);
10151 #define WRAPPER(e,n) n,
10152 static const char* const
10153 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10154 #include "mono/metadata/wrapper-types.h"
10158 static G_GNUC_UNUSED const char*
10159 get_wrapper_type_name (int type)
10161 return wrapper_type_names [type];
10167 static void aot_dump (MonoAotCompile *acfg)
10173 mono_json_writer_init (&writer);
10175 mono_json_writer_object_begin(&writer);
10178 mono_json_writer_indent (&writer);
10179 mono_json_writer_object_key(&writer, "methods");
10180 mono_json_writer_array_begin (&writer);
10183 for (i = 0; i < acfg->nmethods; ++i) {
10185 MonoMethod *method;
10188 cfg = acfg->cfgs [i];
10192 method = cfg->orig_method;
10194 mono_json_writer_indent (&writer);
10195 mono_json_writer_object_begin(&writer);
10197 mono_json_writer_indent (&writer);
10198 mono_json_writer_object_key(&writer, "name");
10199 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10201 mono_json_writer_indent (&writer);
10202 mono_json_writer_object_key(&writer, "signature");
10203 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10205 mono_json_writer_indent (&writer);
10206 mono_json_writer_object_key(&writer, "code_size");
10207 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10209 klass = method->klass;
10211 mono_json_writer_indent (&writer);
10212 mono_json_writer_object_key(&writer, "class");
10213 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10215 mono_json_writer_indent (&writer);
10216 mono_json_writer_object_key(&writer, "namespace");
10217 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10219 mono_json_writer_indent (&writer);
10220 mono_json_writer_object_key(&writer, "wrapper_type");
10221 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10223 mono_json_writer_indent_pop (&writer);
10224 mono_json_writer_indent (&writer);
10225 mono_json_writer_object_end (&writer);
10226 mono_json_writer_printf (&writer, ",\n");
10229 mono_json_writer_indent_pop (&writer);
10230 mono_json_writer_indent (&writer);
10231 mono_json_writer_array_end (&writer);
10232 mono_json_writer_printf (&writer, ",\n");
10236 mono_json_writer_indent_push (&writer);
10237 mono_json_writer_indent (&writer);
10238 mono_json_writer_object_key(&writer, "plt");
10239 mono_json_writer_array_begin (&writer);
10241 for (i = 0; i < acfg->plt_offset; ++i) {
10242 MonoPltEntry *plt_entry = NULL;
10247 * The first plt entry is unused.
10251 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10252 ji = plt_entry->ji;
10254 mono_json_writer_indent (&writer);
10255 mono_json_writer_printf (&writer, "{ ");
10256 mono_json_writer_object_key(&writer, "symbol");
10257 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10260 mono_json_writer_indent_pop (&writer);
10261 mono_json_writer_indent (&writer);
10262 mono_json_writer_array_end (&writer);
10263 mono_json_writer_printf (&writer, ",\n");
10268 mono_json_writer_indent_push (&writer);
10269 mono_json_writer_indent (&writer);
10270 mono_json_writer_object_key(&writer, "got");
10271 mono_json_writer_array_begin (&writer);
10273 mono_json_writer_indent_push (&writer);
10274 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10275 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10277 mono_json_writer_indent (&writer);
10278 mono_json_writer_printf (&writer, "{ ");
10279 mono_json_writer_object_key(&writer, "patch_name");
10280 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10283 mono_json_writer_indent_pop (&writer);
10284 mono_json_writer_indent (&writer);
10285 mono_json_writer_array_end (&writer);
10286 mono_json_writer_printf (&writer, ",\n");
10289 mono_json_writer_indent_pop (&writer);
10290 mono_json_writer_indent (&writer);
10291 mono_json_writer_object_end (&writer);
10293 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10294 dumpfile = fopen (dumpname, "w+");
10297 fprintf (dumpfile, "%s", writer.text->str);
10300 mono_json_writer_destroy (&writer);
10303 static const char *preinited_jit_icalls[] = {
10304 "mono_aot_init_llvm_method",
10305 "mono_aot_init_gshared_method_this",
10306 "mono_aot_init_gshared_method_mrgctx",
10307 "mono_aot_init_gshared_method_vtable",
10308 "mono_llvm_throw_corlib_exception",
10309 "mono_init_vtable_slot",
10310 "mono_helper_ldstr_mscorlib"
10314 add_preinit_got_slots (MonoAotCompile *acfg)
10320 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10321 * during method initialization etc.
10324 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10325 ji->type = MONO_PATCH_INFO_IMAGE;
10326 ji->data.image = acfg->image;
10327 get_got_offset (acfg, FALSE, ji);
10328 get_got_offset (acfg, TRUE, ji);
10330 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10331 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10332 get_got_offset (acfg, FALSE, ji);
10333 get_got_offset (acfg, TRUE, ji);
10335 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10336 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10337 get_got_offset (acfg, FALSE, ji);
10338 get_got_offset (acfg, TRUE, ji);
10340 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10341 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10342 get_got_offset (acfg, FALSE, ji);
10343 get_got_offset (acfg, TRUE, ji);
10345 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10346 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10347 get_got_offset (acfg, FALSE, ji);
10348 get_got_offset (acfg, TRUE, ji);
10350 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10351 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10352 get_got_offset (acfg, FALSE, ji);
10353 get_got_offset (acfg, TRUE, ji);
10355 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10356 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10357 get_got_offset (acfg, FALSE, ji);
10358 get_got_offset (acfg, TRUE, ji);
10360 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10361 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10362 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10363 ji->data.name = preinited_jit_icalls [i];
10364 get_got_offset (acfg, FALSE, ji);
10365 get_got_offset (acfg, TRUE, ji);
10368 acfg->nshared_got_entries = acfg->got_offset;
10372 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10374 MonoImage *image = ass->image;
10377 MonoAotCompile *acfg;
10378 char *outfile_name, *tmp_outfile_name, *p;
10379 char llvm_stats_msg [256];
10383 acfg = acfg_create (ass, opts);
10385 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10386 acfg->aot_opts.write_symbols = TRUE;
10387 acfg->aot_opts.ntrampolines = 4096;
10388 acfg->aot_opts.nrgctx_trampolines = 4096;
10389 acfg->aot_opts.nimt_trampolines = 512;
10390 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10391 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10392 acfg->aot_opts.llvm_path = g_strdup ("");
10393 acfg->aot_opts.temp_path = g_strdup ("");
10395 acfg->aot_opts.use_trampolines_page = TRUE;
10398 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10400 if (acfg->aot_opts.logfile) {
10401 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10404 if (acfg->aot_opts.data_outfile) {
10405 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10406 if (!acfg->data_outfile) {
10407 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10410 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10413 //acfg->aot_opts.print_skipped_methods = TRUE;
10415 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10416 if (opts & MONO_OPT_GSHAREDVT) {
10417 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10422 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10423 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10424 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10429 if (acfg->aot_opts.llvm_only) {
10430 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
10431 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10436 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10437 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts)) {
10438 acfg->opts |= MONO_OPT_GSHAREDVT;
10439 opts |= MONO_OPT_GSHAREDVT;
10443 if (opts & MONO_OPT_GSHAREDVT)
10444 mono_set_generic_sharing_vt_supported (TRUE);
10446 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10448 generate_aotid ((guint8*) &acfg->image->aotid);
10450 char *aotid = mono_guid_to_string (acfg->image->aotid);
10451 aot_printf (acfg, "AOTID %s\n", aotid);
10454 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10455 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10456 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10461 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10462 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10466 if (acfg->aot_opts.static_link)
10467 acfg->aot_opts.asm_writer = TRUE;
10469 if (acfg->aot_opts.soft_debug) {
10470 MonoDebugOptions *opt = mini_get_debug_options ();
10472 opt->mdb_optimizations = TRUE;
10473 opt->gen_sdb_seq_points = TRUE;
10475 if (!mono_debug_enabled ()) {
10476 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10479 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10482 if (mono_use_llvm || acfg->aot_opts.llvm) {
10484 acfg->aot_opts.asm_writer = TRUE;
10485 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10487 if (acfg->aot_opts.soft_debug) {
10488 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10494 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10495 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10500 * Emit all LLVM code into a separate assembly/object file and link with it
10503 if (!acfg->aot_opts.asm_only) {
10504 acfg->llvm_owriter = TRUE;
10505 } else if (acfg->aot_opts.llvm_outfile) {
10506 int len = strlen (acfg->aot_opts.llvm_outfile);
10508 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10509 acfg->llvm_owriter = TRUE;
10513 if (mono_aot_mode_is_full (&acfg->aot_opts))
10514 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10516 if (mono_threads_is_coop_enabled ())
10517 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10519 if (acfg->aot_opts.instances_logfile_path) {
10520 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10521 if (!acfg->instances_logfile) {
10522 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10527 load_profile_files (acfg);
10529 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10530 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10531 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10533 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10534 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10535 if (acfg->opts & MONO_OPT_GSHAREDVT)
10536 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10539 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10543 if (acfg->llvm && acfg->thumb_mixed)
10544 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10545 if (acfg->aot_opts.llvm_only)
10546 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10548 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10549 /* Get rid of characters which cannot occur in symbols */
10550 for (p = acfg->assembly_name_sym; *p; ++p) {
10551 if (!(isalnum (*p) || *p == '_'))
10555 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10556 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10557 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10559 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10560 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10563 acfg->method_index = 1;
10565 if (mono_aot_mode_is_full (&acfg->aot_opts))
10566 mono_set_partial_sharing_supported (TRUE);
10568 res = collect_methods (acfg);
10572 acfg->cfgs_size = acfg->methods->len + 32;
10573 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10575 /* PLT offset 0 is reserved for the PLT trampoline */
10576 acfg->plt_offset = 1;
10577 add_preinit_got_slots (acfg);
10582 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10588 compile_methods (acfg);
10592 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10598 if (acfg->aot_opts.asm_only) {
10599 if (acfg->aot_opts.outfile) {
10600 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10601 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10603 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10604 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10606 g_assert (acfg->aot_opts.llvm_outfile);
10607 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10608 if (acfg->llvm_owriter)
10609 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10611 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10613 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10614 g_strdup_printf ("%s", "temp") :
10615 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10617 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10618 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10619 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10624 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10625 if (acfg->aot_opts.outfile)
10626 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10628 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10629 acfg->fp = fopen (acfg->tmpfname, "w+");
10631 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10632 acfg->fp = fdopen (i, "w+");
10634 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10635 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10639 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10641 tmp_outfile_name = NULL;
10642 outfile_name = NULL;
10644 /* Compute symbols for methods */
10645 for (i = 0; i < acfg->nmethods; ++i) {
10646 if (acfg->cfgs [i]) {
10647 MonoCompile *cfg = acfg->cfgs [i];
10648 int method_index = get_method_index (acfg, cfg->orig_method);
10650 if (COMPILE_LLVM (cfg))
10651 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10652 else if (acfg->global_symbols || acfg->llvm)
10653 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10655 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10656 cfg->asm_debug_symbol = cfg->asm_symbol;
10660 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10662 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10664 acfg->gas_line_numbers = TRUE;
10667 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10668 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10669 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10672 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10676 mono_img_writer_emit_start (acfg->w);
10679 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10685 emit_extra_methods (acfg);
10687 emit_trampolines (acfg);
10689 emit_class_name_table (acfg);
10691 emit_got_info (acfg, FALSE);
10693 emit_got_info (acfg, TRUE);
10695 emit_exception_info (acfg);
10697 emit_unwind_info (acfg);
10699 emit_class_info (acfg);
10703 emit_image_table (acfg);
10709 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10712 const char *gc_name = mono_gc_get_gc_name ();
10713 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10718 emit_objc_selectors (acfg);
10720 emit_globals (acfg);
10722 emit_file_info (acfg);
10725 emit_dwarf_info (acfg);
10726 mono_dwarf_writer_close (acfg->dwarf);
10729 emit_mem_end (acfg);
10731 if (acfg->need_pt_gnu_stack) {
10732 /* This is required so the .so doesn't have an executable stack */
10733 /* The bin writer already emits this */
10734 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10737 if (acfg->aot_opts.data_outfile)
10738 fclose (acfg->data_outfile);
10744 res = emit_llvm_file (acfg);
10752 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10755 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10757 strcpy (llvm_stats_msg, "");
10759 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;
10761 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",
10762 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10763 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10764 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10765 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10766 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10767 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,
10768 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10769 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10770 (int)(acfg->got_offset * sizeof (gpointer)));
10771 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10772 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10774 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10775 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10776 if (acfg->stats.genericcount)
10777 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10778 if (acfg->stats.abscount)
10779 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10780 if (acfg->stats.lmfcount)
10781 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10782 if (acfg->stats.ocount)
10783 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10787 res = mono_img_writer_emit_writeout (acfg->w);
10792 res = compile_asm (acfg);
10799 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10801 if (acfg->aot_opts.stats) {
10804 aot_printf (acfg, "GOT slot distribution:\n");
10805 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10806 if (acfg->stats.got_slot_types [i])
10807 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]);
10808 aot_printf (acfg, "\nMethod stats:\n");
10809 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10810 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10811 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10812 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10815 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);
10817 if (acfg->aot_opts.dump_json)
10830 mono_aot_readonly_field_override (MonoClassField *field)
10836 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10842 mono_aot_is_shared_got_offset (int offset)