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;
222 gboolean llvm_owriter_supported;
224 MonoDwarfWriter *dwarf;
231 GHashTable *unwind_info_offsets;
232 GPtrArray *unwind_ops;
233 guint32 unwind_info_offset;
236 char *llvm_got_symbol;
238 char *llvm_eh_frame_symbol;
239 GHashTable *method_label_hash;
240 const char *temp_prefix;
241 const char *user_symbol_prefix;
242 const char *llvm_label_prefix;
243 const char *inst_directive;
245 guint32 label_generator;
247 gboolean has_jitted_code;
248 MonoAotFileFlags flags;
249 MonoDynamicStream blob;
250 gboolean blob_closed;
251 GHashTable *typespec_classes;
254 char *assembly_name_sym;
255 GHashTable *plt_entry_debug_sym_cache;
256 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
257 GHashTable *ginst_hash;
258 GHashTable *dwarf_ln_filenames;
259 gboolean global_symbols;
260 int objc_selector_index, objc_selector_index_2;
261 GPtrArray *objc_selectors;
262 GHashTable *objc_selector_to_index;
264 FILE *instances_logfile;
272 char *symbol, *llvm_symbol, *debug_sym;
274 gboolean jit_used, llvm_used;
277 #define mono_acfg_lock(acfg) mono_os_mutex_lock (&((acfg)->mutex))
278 #define mono_acfg_unlock(acfg) mono_os_mutex_unlock (&((acfg)->mutex))
280 /* This points to the current acfg in LLVM mode */
281 static MonoAotCompile *llvm_acfg;
283 #ifdef HAVE_ARRAY_ELEM_INIT
284 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
285 #define MSGSTRFIELD1(line) str##line
286 static const struct msgstr_t {
287 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
288 #include "patch-info.h"
291 #define PATCH_INFO(a,b) b,
292 #include "patch-info.h"
295 static const gint16 opidx [] = {
296 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
297 #include "patch-info.h"
301 static G_GNUC_UNUSED const char*
302 get_patch_name (int info)
304 return (const char*)&opstr + opidx [info];
308 #define PATCH_INFO(a,b) b,
309 static const char* const
310 patch_types [MONO_PATCH_INFO_NUM + 1] = {
311 #include "patch-info.h"
315 static G_GNUC_UNUSED const char*
316 get_patch_name (int info)
318 return patch_types [info];
324 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len);
327 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
330 aot_printf (MonoAotCompile *acfg, const gchar *format, ...)
336 output = acfg->logfile;
340 va_start (args, format);
341 vfprintf (output, format, args);
346 aot_printerrf (MonoAotCompile *acfg, const gchar *format, ...)
352 output = acfg->logfile;
356 va_start (args, format);
357 vfprintf (output, format, args);
362 report_loader_error (MonoAotCompile *acfg, MonoError *error, const char *format, ...)
367 if (mono_error_ok (error))
371 output = acfg->logfile;
375 va_start (args, format);
376 vfprintf (output, format, args);
378 mono_error_cleanup (error);
380 g_error ("FullAOT cannot continue if there are loader errors");
383 /* Wrappers around the image writer functions */
385 #define MAX_SYMBOL_SIZE 256
387 static inline const char *
388 mangle_symbol (const char * symbol, char * mangled_symbol, gsize length)
390 gsize needed_size = length;
392 g_assert (NULL != symbol);
393 g_assert (NULL != mangled_symbol);
394 g_assert (0 != length);
396 #if defined(TARGET_WIN32) && defined(TARGET_X86)
397 if (symbol && '_' != symbol [0]) {
398 needed_size = g_snprintf (mangled_symbol, length, "_%s", symbol);
400 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
403 needed_size = g_snprintf (mangled_symbol, length, "%s", symbol);
406 g_assert (0 <= needed_size && needed_size < length);
407 return mangled_symbol;
411 mangle_symbol_alloc (const char * symbol)
413 g_assert (NULL != symbol);
415 #if defined(TARGET_WIN32) && defined(TARGET_X86)
416 if (symbol && '_' != symbol [0]) {
417 return g_strdup_printf ("_%s", symbol);
420 return g_strdup_printf ("%s", symbol);
423 return g_strdup_printf ("%s", symbol);
428 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
430 mono_img_writer_emit_section_change (acfg->w, section_name, subsection_index);
433 #if defined(TARGET_WIN32) && defined(TARGET_X86)
436 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
438 const char * mangled_symbol_name = name;
439 char * mangled_symbol_name_alloc = NULL;
442 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
443 mangled_symbol_name = mangled_symbol_name_alloc;
446 if (name != mangled_symbol_name && 0 != g_strcasecmp (name, mangled_symbol_name)) {
447 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
449 mono_img_writer_emit_local_symbol (acfg->w, mangled_symbol_name, end_label, func);
451 if (NULL != mangled_symbol_name_alloc) {
452 g_free (mangled_symbol_name_alloc);
459 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
461 mono_img_writer_emit_local_symbol (acfg->w, name, end_label, func);
467 emit_label (MonoAotCompile *acfg, const char *name)
469 mono_img_writer_emit_label (acfg->w, name);
473 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
475 mono_img_writer_emit_bytes (acfg->w, buf, size);
479 emit_string (MonoAotCompile *acfg, const char *value)
481 mono_img_writer_emit_string (acfg->w, value);
485 emit_line (MonoAotCompile *acfg)
487 mono_img_writer_emit_line (acfg->w);
491 emit_alignment (MonoAotCompile *acfg, int size)
493 mono_img_writer_emit_alignment (acfg->w, size);
497 emit_alignment_code (MonoAotCompile *acfg, int size)
499 if (acfg->align_pad_value)
500 mono_img_writer_emit_alignment_fill (acfg->w, size, acfg->align_pad_value);
502 mono_img_writer_emit_alignment (acfg->w, size);
506 emit_padding (MonoAotCompile *acfg, int size)
511 if (acfg->align_pad_value) {
512 for (i = 0; i < 16; ++i)
513 buf [i] = acfg->align_pad_value;
515 memset (buf, 0, sizeof (buf));
518 for (i = 0; i < size; i += 16) {
520 emit_bytes (acfg, buf, size - i);
522 emit_bytes (acfg, buf, 16);
527 emit_pointer (MonoAotCompile *acfg, const char *target)
529 mono_img_writer_emit_pointer (acfg->w, target);
533 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
535 if (prefix [0] != '\0') {
536 char *s = g_strdup_printf ("%s%s", prefix, target);
537 mono_img_writer_emit_pointer (acfg->w, s);
540 mono_img_writer_emit_pointer (acfg->w, target);
545 emit_int16 (MonoAotCompile *acfg, int value)
547 mono_img_writer_emit_int16 (acfg->w, value);
551 emit_int32 (MonoAotCompile *acfg, int value)
553 mono_img_writer_emit_int32 (acfg->w, value);
557 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
559 mono_img_writer_emit_symbol_diff (acfg->w, end, start, offset);
563 emit_zero_bytes (MonoAotCompile *acfg, int num)
565 mono_img_writer_emit_zero_bytes (acfg->w, num);
569 emit_byte (MonoAotCompile *acfg, guint8 val)
571 mono_img_writer_emit_byte (acfg->w, val);
574 #if defined(TARGET_WIN32) && defined(TARGET_X86)
576 static G_GNUC_UNUSED void
577 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
579 const char * mangled_symbol_name = name;
580 char * mangled_symbol_name_alloc = NULL;
582 mangled_symbol_name_alloc = mangle_symbol_alloc (name);
583 mangled_symbol_name = mangled_symbol_name_alloc;
585 if (0 != g_strcasecmp (name, mangled_symbol_name)) {
586 mono_img_writer_emit_label (acfg->w, mangled_symbol_name);
588 mono_img_writer_emit_global (acfg->w, mangled_symbol_name, func);
590 if (NULL != mangled_symbol_name_alloc) {
591 g_free (mangled_symbol_name_alloc);
597 static G_GNUC_UNUSED void
598 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
600 mono_img_writer_emit_global (acfg->w, name, func);
606 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
608 if (acfg->aot_opts.no_dlsym) {
609 g_ptr_array_add (acfg->globals, g_strdup (name));
610 mono_img_writer_emit_local_symbol (acfg->w, name, NULL, func);
612 emit_global_inner (acfg, name, func);
617 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
619 mono_img_writer_emit_symbol_size (acfg->w, name, end_label);
622 /* Emit a symbol which is referenced by the MonoAotFileInfo structure */
624 emit_info_symbol (MonoAotCompile *acfg, const char *name)
626 char symbol [MAX_SYMBOL_SIZE];
629 emit_label (acfg, name);
630 /* LLVM generated code references this */
631 sprintf (symbol, "%s%s%s", acfg->user_symbol_prefix, acfg->global_prefix, name);
632 emit_label (acfg, symbol);
633 emit_global_inner (acfg, symbol, FALSE);
635 emit_label (acfg, name);
640 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
643 mono_llvm_emit_aot_data (name, (guint8*)value, strlen (value) + 1);
647 mono_img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
649 /* On apple, all symbols need to be aligned to avoid warnings from ld */
650 emit_alignment (acfg, 4);
652 mono_img_writer_emit_label (acfg->w, name);
653 mono_img_writer_emit_string (acfg->w, value);
656 static G_GNUC_UNUSED void
657 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
660 guint8 b = value & 0x7f;
662 if (value != 0) /* more bytes to come */
668 static G_GNUC_UNUSED void
669 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
672 gboolean negative = (value < 0);
679 /* the following is unnecessary if the
680 * implementation of >>= uses an arithmetic rather
681 * than logical shift for a signed left operand
685 value |= - ((gint64)1 <<(size - 7));
686 /* sign bit of byte is second high order bit (0x40) */
687 if ((value == 0 && !(byte & 0x40)) ||
688 (value == -1 && (byte & 0x40)))
692 emit_byte (acfg, byte);
696 static G_GNUC_UNUSED void
697 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
702 guint8 b = value & 0x7f;
704 if (value != 0) /* more bytes to come */
712 static G_GNUC_UNUSED void
713 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
716 gboolean negative = (value < 0);
724 /* the following is unnecessary if the
725 * implementation of >>= uses an arithmetic rather
726 * than logical shift for a signed left operand
730 value |= - (1 <<(size - 7));
731 /* sign bit of byte is second high order bit (0x40) */
732 if ((value == 0 && !(byte & 0x40)) ||
733 (value == -1 && (byte & 0x40)))
744 encode_int (gint32 val, guint8 *buf, guint8 **endbuf)
747 buf [0] = (val >> 0) & 0xff;
748 buf [1] = (val >> 8) & 0xff;
749 buf [2] = (val >> 16) & 0xff;
750 buf [3] = (val >> 24) & 0xff;
756 encode_int16 (guint16 val, guint8 *buf, guint8 **endbuf)
758 buf [0] = (val >> 0) & 0xff;
759 buf [1] = (val >> 8) & 0xff;
765 encode_string (const char *s, guint8 *buf, guint8 **endbuf)
767 int len = strlen (s);
769 memcpy (buf, s, len + 1);
770 *endbuf = buf + len + 1;
774 emit_unset_mode (MonoAotCompile *acfg)
776 mono_img_writer_emit_unset_mode (acfg->w);
779 static G_GNUC_UNUSED void
780 emit_set_thumb_mode (MonoAotCompile *acfg)
782 emit_unset_mode (acfg);
783 fprintf (acfg->fp, ".code 16\n");
786 static G_GNUC_UNUSED void
787 emit_set_arm_mode (MonoAotCompile *acfg)
789 emit_unset_mode (acfg);
790 fprintf (acfg->fp, ".code 32\n");
794 emit_code_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
799 g_assert (size % 4 == 0);
800 emit_unset_mode (acfg);
801 for (i = 0; i < size; i += 4)
802 fprintf (acfg->fp, "%s 0x%x\n", acfg->inst_directive, *(guint32*)(buf + i));
804 emit_bytes (acfg, buf, size);
808 /* ARCHITECTURE SPECIFIC CODE */
810 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC) || defined(TARGET_ARM64)
811 #define EMIT_DWARF_INFO 1
814 #if defined(TARGET_ARM)
815 #define AOT_FUNC_ALIGNMENT 4
817 #define AOT_FUNC_ALIGNMENT 16
820 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
821 #define PPC_LD_OP "ld"
822 #define PPC_LDX_OP "ldx"
824 #define PPC_LD_OP "lwz"
825 #define PPC_LDX_OP "lwzx"
829 #define AOT_TARGET_STR "AMD64"
834 #define AOT_TARGET_STR "ARM (MACH)"
836 #define AOT_TARGET_STR "ARM (!MACH)"
842 #define AOT_TARGET_STR "ARM64 (MACH)"
844 #define AOT_TARGET_STR "ARM64 (!MACH)"
848 #ifdef TARGET_POWERPC64
849 #ifdef __mono_ilp32__
850 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
852 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
855 #ifdef TARGET_POWERPC
856 #ifdef __mono_ilp32__
857 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
859 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
866 #define AOT_TARGET_STR "X86 (WIN32)"
867 #elif defined(__native_client_codegen__)
868 #define AOT_TARGET_STR "X86 (native client codegen)"
870 #define AOT_TARGET_STR "X86 (!native client codegen)"
874 #ifndef AOT_TARGET_STR
875 #define AOT_TARGET_STR ""
879 arch_init (MonoAotCompile *acfg)
881 acfg->llc_args = g_string_new ("");
882 acfg->as_args = g_string_new ("");
883 acfg->llvm_owriter_supported = TRUE;
886 * The prefix LLVM likes to put in front of symbol names on darwin.
887 * The mach-os specs require this for globals, but LLVM puts them in front of all
888 * symbols. We need to handle this, since we need to refer to LLVM generated
891 acfg->llvm_label_prefix = "";
892 acfg->user_symbol_prefix = "";
894 #if defined(TARGET_X86)
895 g_string_append (acfg->llc_args, " -march=x86 -mattr=sse4.1");
898 #if defined(TARGET_AMD64)
899 g_string_append (acfg->llc_args, " -march=x86-64 -mattr=sse4.1");
901 acfg->align_pad_value = 0x90;
905 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
906 g_string_append (acfg->llc_args, "-mattr=+v6");
908 #if defined(ARM_FPU_VFP_HARD)
909 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16 -float-abi=hard");
910 g_string_append (acfg->as_args, " -mfpu=vfp3");
911 #elif defined(ARM_FPU_VFP)
912 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
913 g_string_append (acfg->as_args, " -mfpu=vfp3");
915 g_string_append (acfg->llc_args, " -soft-float");
918 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
919 acfg->thumb_mixed = TRUE;
921 if (acfg->aot_opts.mtriple)
922 mono_arch_set_target (acfg->aot_opts.mtriple);
926 acfg->inst_directive = ".inst";
927 if (acfg->aot_opts.mtriple)
928 mono_arch_set_target (acfg->aot_opts.mtriple);
932 acfg->user_symbol_prefix = "_";
933 acfg->llvm_label_prefix = "_";
934 acfg->inst_directive = ".word";
935 acfg->need_no_dead_strip = TRUE;
936 acfg->aot_opts.gnu_asm = TRUE;
939 #if defined(__linux__) && !defined(TARGET_ARM)
940 acfg->need_pt_gnu_stack = TRUE;
944 acfg->global_symbols = TRUE;
947 #ifdef TARGET_ANDROID
948 acfg->llvm_owriter_supported = FALSE;
955 /* Load the contents of GOT_SLOT into dreg, clobbering ip0 */
957 arm64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
962 emit_unset_mode (acfg);
964 offset = (int)(got_slot * sizeof (gpointer));
966 /* clang's integrated assembler */
967 fprintf (acfg->fp, "adrp x16, %s@PAGE+%d\n", acfg->got_symbol, offset & 0xfffff000);
968 fprintf (acfg->fp, "add x16, x16, %s@PAGEOFF\n", acfg->got_symbol);
969 fprintf (acfg->fp, "ldr x%d, [x16, #%d]\n", dreg, offset & 0xfff);
972 fprintf (acfg->fp, "adrp x16, %s+%d\n", acfg->got_symbol, offset & 0xfffff000);
973 fprintf (acfg->fp, "add x16, x16, :lo12:%s\n", acfg->got_symbol);
974 fprintf (acfg->fp, "ldr x%d, [x16, %d]\n", dreg, offset & 0xfff);
979 arm64_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
984 emit_unset_mode (acfg);
987 reg = arm_get_ldr_lit_reg (code);
989 fprintf (acfg->fp, "adrp x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGE\n", reg, index);
990 fprintf (acfg->fp, "add x%d, x%d, L_OBJC_SELECTOR_REFERENCES_%d@PAGEOFF\n", reg, reg, index);
991 fprintf (acfg->fp, "ldr x%d, [x%d]\n", reg, reg);
997 arm64_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1000 emit_unset_mode (acfg);
1001 if (ji && ji->relocation == MONO_R_ARM64_B) {
1002 fprintf (acfg->fp, "b %s\n", target);
1005 g_assert (ji->relocation == MONO_R_ARM64_BL);
1006 fprintf (acfg->fp, "bl %s\n", target);
1012 arm64_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
1016 /* ldr rt, target */
1017 reg = arm_get_ldr_lit_reg (code);
1018 arm64_emit_load_got_slot (acfg, reg, got_slot);
1023 arm64_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1025 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset / sizeof (gpointer));
1026 fprintf (acfg->fp, "br x16\n");
1027 /* Used by mono_aot_get_plt_info_offset () */
1028 fprintf (acfg->fp, "%s %d\n", acfg->inst_directive, info_offset);
1032 arm64_emit_tramp_page_common_code (MonoAotCompile *acfg, int pagesize, int arg_reg, int *size)
1038 /* The common code */
1041 /* The trampoline address is in IP0 */
1042 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1043 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1044 /* Compute the data slot address */
1045 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1046 /* Trampoline argument */
1047 arm_ldrx (code, arg_reg, ARMREG_IP0, 0);
1049 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 8);
1050 arm_brx (code, ARMREG_IP0);
1053 emit_code_bytes (acfg, buf, code - buf);
1059 arm64_emit_tramp_page_specific_code (MonoAotCompile *acfg, int pagesize, int common_tramp_size, int specific_tramp_size)
1065 count = (pagesize - common_tramp_size) / specific_tramp_size;
1066 for (i = 0; i < count; ++i) {
1068 arm_adrx (code, ARMREG_IP0, code);
1069 /* Branch to the generic code */
1070 arm_b (code, code - 4 - (i * specific_tramp_size) - common_tramp_size);
1071 /* This has to be 2 pointers long */
1074 g_assert (code - buf == specific_tramp_size);
1075 emit_code_bytes (acfg, buf, code - buf);
1080 arm64_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1084 guint8 *labels [16];
1085 int common_tramp_size;
1086 int specific_tramp_size = 2 * 8;
1090 if (!acfg->aot_opts.use_trampolines_page)
1094 /* Have to match the target pagesize */
1097 pagesize = mono_pagesize ();
1099 acfg->tramp_page_size = pagesize;
1101 /* The specific trampolines */
1102 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1103 emit_alignment (acfg, pagesize);
1104 emit_global (acfg, symbol, TRUE);
1105 emit_label (acfg, symbol);
1107 /* The common code */
1108 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1109 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = common_tramp_size;
1111 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1113 /* The rgctx trampolines */
1114 /* These are the same as the specific trampolines, but they load the argument into MONO_ARCH_RGCTX_REG */
1115 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1116 emit_alignment (acfg, pagesize);
1117 emit_global (acfg, symbol, TRUE);
1118 emit_label (acfg, symbol);
1120 /* The common code */
1121 arm64_emit_tramp_page_common_code (acfg, pagesize, MONO_ARCH_RGCTX_REG, &common_tramp_size);
1122 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = common_tramp_size;
1124 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1126 /* The gsharedvt arg trampolines */
1127 /* These are the same as the specific trampolines */
1128 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1129 emit_alignment (acfg, pagesize);
1130 emit_global (acfg, symbol, TRUE);
1131 emit_label (acfg, symbol);
1133 arm64_emit_tramp_page_common_code (acfg, pagesize, ARMREG_IP1, &common_tramp_size);
1134 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = common_tramp_size;
1136 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1138 /* The IMT trampolines */
1139 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1140 emit_alignment (acfg, pagesize);
1141 emit_global (acfg, symbol, TRUE);
1142 emit_label (acfg, symbol);
1146 /* The trampoline address is in IP0 */
1147 arm_movzx (code, ARMREG_IP1, imm & 0xffff, 0);
1148 arm_movkx (code, ARMREG_IP1, (imm >> 16) & 0xffff, 16);
1149 /* Compute the data slot address */
1150 arm_subx (code, ARMREG_IP0, ARMREG_IP0, ARMREG_IP1);
1151 /* Trampoline argument */
1152 arm_ldrx (code, ARMREG_IP1, ARMREG_IP0, 0);
1154 /* Same as arch_emit_imt_trampoline () */
1156 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1157 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1159 arm_bcc (code, ARMCOND_EQ, 0);
1161 /* End-of-loop check */
1163 arm_cbzx (code, ARMREG_IP0, 0);
1166 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1167 arm_b (code, labels [0]);
1170 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1171 /* Load vtable slot addr */
1172 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1173 /* Load vtable slot */
1174 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1175 arm_brx (code, ARMREG_IP0);
1178 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1179 /* Load fail addr */
1180 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1181 arm_brx (code, ARMREG_IP0);
1183 emit_code_bytes (acfg, buf, code - buf);
1185 common_tramp_size = code - buf;
1186 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = common_tramp_size;
1188 arm64_emit_tramp_page_specific_code (acfg, pagesize, common_tramp_size, specific_tramp_size);
1192 arm64_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1194 /* Load argument from second GOT slot */
1195 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset + 1);
1196 /* Load generic trampoline address from first GOT slot */
1197 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset);
1198 fprintf (acfg->fp, "br x16\n");
1199 *tramp_size = 7 * 4;
1203 arm64_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1205 emit_unset_mode (acfg);
1206 fprintf (acfg->fp, "add x0, x0, %d\n", (int)(sizeof (MonoObject)));
1207 fprintf (acfg->fp, "b %s\n", call_target);
1211 arm64_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1213 /* Similar to the specific trampolines, but use the rgctx reg instead of ip1 */
1215 /* Load argument from first GOT slot */
1216 arm64_emit_load_got_slot (acfg, MONO_ARCH_RGCTX_REG, offset);
1217 /* Load generic trampoline address from second GOT slot */
1218 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1219 fprintf (acfg->fp, "br x16\n");
1220 *tramp_size = 7 * 4;
1224 arm64_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1227 guint8 *code, *labels [16];
1229 /* Load parameter from GOT slot into ip1 */
1230 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1234 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 0);
1235 arm_cmpx (code, ARMREG_IP0, MONO_ARCH_RGCTX_REG);
1237 arm_bcc (code, ARMCOND_EQ, 0);
1239 /* End-of-loop check */
1241 arm_cbzx (code, ARMREG_IP0, 0);
1244 arm_addx_imm (code, ARMREG_IP1, ARMREG_IP1, 2 * 8);
1245 arm_b (code, labels [0]);
1248 mono_arm_patch (labels [1], code, MONO_R_ARM64_BCC);
1249 /* Load vtable slot addr */
1250 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1251 /* Load vtable slot */
1252 arm_ldrx (code, ARMREG_IP0, ARMREG_IP0, 0);
1253 arm_brx (code, ARMREG_IP0);
1256 mono_arm_patch (labels [2], code, MONO_R_ARM64_CBZ);
1257 /* Load fail addr */
1258 arm_ldrx (code, ARMREG_IP0, ARMREG_IP1, 8);
1259 arm_brx (code, ARMREG_IP0);
1261 emit_code_bytes (acfg, buf, code - buf);
1263 *tramp_size = code - buf + (3 * 4);
1267 arm64_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1269 /* Similar to the specific trampolines, but the address is in the second slot */
1270 /* Load argument from first GOT slot */
1271 arm64_emit_load_got_slot (acfg, ARMREG_R17, offset);
1272 /* Load generic trampoline address from second GOT slot */
1273 arm64_emit_load_got_slot (acfg, ARMREG_R16, offset + 1);
1274 fprintf (acfg->fp, "br x16\n");
1275 *tramp_size = 7 * 4;
1281 #ifdef MONO_ARCH_AOT_SUPPORTED
1283 * arch_emit_direct_call:
1285 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
1289 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, gboolean thumb, MonoJumpInfo *ji, int *call_size)
1291 #if defined(TARGET_X86) || defined(TARGET_AMD64)
1292 /* Need to make sure this is exactly 5 bytes long */
1293 emit_unset_mode (acfg);
1294 fprintf (acfg->fp, "call %s\n", target);
1296 #elif defined(TARGET_ARM)
1297 emit_unset_mode (acfg);
1299 fprintf (acfg->fp, "blx %s\n", target);
1301 fprintf (acfg->fp, "bl %s\n", target);
1303 #elif defined(TARGET_ARM64)
1304 arm64_emit_direct_call (acfg, target, external, thumb, ji, call_size);
1305 #elif defined(TARGET_POWERPC)
1306 emit_unset_mode (acfg);
1307 fprintf (acfg->fp, "bl %s\n", target);
1310 g_assert_not_reached ();
1317 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
1319 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
1320 * in in the 2. slot of every GOT, and require every method to place the GOT
1321 * address in r30, even when it doesn't access the GOT otherwise. This way,
1322 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
1327 * PPC64 uses function descriptors which greatly complicate all code, since
1328 * these are used very inconsistently in the runtime. Some functions like
1329 * mono_compile_method () return ftn descriptors, while others like the
1330 * trampoline creation functions do not.
1331 * We assume that all GOT slots contain function descriptors, and create
1332 * descriptors in aot-runtime.c when needed.
1333 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
1334 * from function descriptors, we could do the same, but it would require
1335 * rewriting all the ppc/aot code to handle function descriptors properly.
1336 * So instead, we use the same approach as on PPC32.
1337 * This is a horrible mess, but fixing it would probably lead to an even bigger
1343 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
1346 #ifdef MONO_ARCH_AOT_SUPPORTED
1348 * arch_emit_got_offset:
1350 * The memory pointed to by CODE should hold native code for computing the GOT
1351 * address (OP_LOAD_GOTADDR). Emit this code while patching it with the offset
1352 * between code and the GOT. CODE_SIZE is set to the number of bytes emitted.
1355 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
1357 #if defined(TARGET_POWERPC64)
1358 emit_unset_mode (acfg);
1360 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
1361 * unsupported relocations. So we store the got address into the .Lgot_addr
1362 * symbol which is in the text segment, compute its address, and load it.
1364 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1365 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
1366 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
1367 fprintf (acfg->fp, "add 30, 30, 0\n");
1368 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
1369 acfg->label_generator ++;
1371 #elif defined(TARGET_POWERPC)
1372 emit_unset_mode (acfg);
1373 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
1374 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
1375 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
1376 acfg->label_generator ++;
1379 guint32 offset = mono_arch_get_patch_offset (code);
1380 emit_bytes (acfg, code, offset);
1381 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
1383 *code_size = offset + 4;
1388 * arch_emit_got_access:
1390 * The memory pointed to by CODE should hold native code for loading a GOT
1391 * slot (OP_AOTCONST/OP_GOT_ENTRY). Emit this code while patching it so it accesses the
1392 * GOT slot GOT_SLOT. CODE_SIZE is set to the number of bytes emitted.
1395 arch_emit_got_access (MonoAotCompile *acfg, const char *got_symbol, guint8 *code, int got_slot, int *code_size)
1398 /* mov reg, got+offset(%rip) */
1400 /* The GOT symbol is in the LLVM module, the clang assembler has problems emitting symbol diffs for it */
1404 /* Decode reg, see amd64_mov_reg_membase () */
1405 rex_r = code [0] & AMD64_REX_R;
1406 g_assert (code [0] == 0x49 + rex_r);
1407 g_assert (code [1] == 0x8b);
1408 dreg = ((code [2] >> 3) & 0x7) + (rex_r ? 8 : 0);
1410 emit_unset_mode (acfg);
1411 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
1414 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1415 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
1416 *code_size = mono_arch_get_patch_offset (code) + 4;
1418 #elif defined(TARGET_X86)
1419 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1420 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
1421 *code_size = mono_arch_get_patch_offset (code) + 4;
1422 #elif defined(TARGET_ARM)
1423 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1424 emit_symbol_diff (acfg, got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
1425 *code_size = mono_arch_get_patch_offset (code) + 4;
1426 #elif defined(TARGET_ARM64)
1427 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1428 arm64_emit_got_access (acfg, code, got_slot, code_size);
1429 #elif defined(TARGET_POWERPC)
1434 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
1436 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
1437 g_assert (code - buf == 8);
1438 emit_bytes (acfg, buf, code - buf);
1439 *code_size = code - buf;
1442 g_assert_not_reached ();
1448 #ifdef MONO_ARCH_AOT_SUPPORTED
1450 * arch_emit_objc_selector_ref:
1452 * Emit the implementation of OP_OBJC_GET_SELECTOR, which itself implements @selector(foo:) in objective-c.
1455 arch_emit_objc_selector_ref (MonoAotCompile *acfg, guint8 *code, int index, int *code_size)
1457 #if defined(TARGET_ARM)
1458 char symbol1 [MAX_SYMBOL_SIZE];
1459 char symbol2 [MAX_SYMBOL_SIZE];
1460 int lindex = acfg->objc_selector_index_2 ++;
1462 /* Emit ldr.imm/b */
1463 emit_bytes (acfg, code, 8);
1465 sprintf (symbol1, "L_OBJC_SELECTOR_%d", lindex);
1466 sprintf (symbol2, "L_OBJC_SELECTOR_REFERENCES_%d", index);
1468 emit_label (acfg, symbol1);
1469 mono_img_writer_emit_unset_mode (acfg->w);
1470 fprintf (acfg->fp, ".long %s-(%s+12)", symbol2, symbol1);
1473 #elif defined(TARGET_ARM64)
1474 arm64_emit_objc_selector_ref (acfg, code, index, code_size);
1476 g_assert_not_reached ();
1482 * arch_emit_plt_entry:
1484 * Emit code for the PLT entry.
1485 * The plt entry should look like this:
1486 * <indirect jump to GOT_SYMBOL + OFFSET>
1487 * <INFO_OFFSET embedded into the instruction stream>
1490 arch_emit_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1492 #if defined(TARGET_X86)
1493 /* jmp *<offset>(%ebx) */
1494 emit_byte (acfg, 0xff);
1495 emit_byte (acfg, 0xa3);
1496 emit_int32 (acfg, offset);
1497 /* Used by mono_aot_get_plt_info_offset */
1498 emit_int32 (acfg, info_offset);
1499 #elif defined(TARGET_AMD64)
1500 emit_unset_mode (acfg);
1501 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", got_symbol, offset);
1502 /* Used by mono_aot_get_plt_info_offset */
1503 emit_int32 (acfg, info_offset);
1504 acfg->stats.plt_size += 10;
1505 #elif defined(TARGET_ARM)
1510 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
1511 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1512 emit_bytes (acfg, buf, code - buf);
1513 emit_symbol_diff (acfg, got_symbol, ".", offset - 4);
1514 /* Used by mono_aot_get_plt_info_offset */
1515 emit_int32 (acfg, info_offset);
1516 #elif defined(TARGET_ARM64)
1517 arm64_emit_plt_entry (acfg, got_symbol, offset, info_offset);
1518 #elif defined(TARGET_POWERPC)
1519 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
1520 emit_unset_mode (acfg);
1521 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
1522 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
1523 fprintf (acfg->fp, "add 11, 11, 30\n");
1524 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1525 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1526 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1527 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1529 fprintf (acfg->fp, "mtctr 11\n");
1530 fprintf (acfg->fp, "bctr\n");
1531 emit_int32 (acfg, info_offset);
1533 g_assert_not_reached ();
1538 * arch_emit_llvm_plt_entry:
1540 * Same as arch_emit_plt_entry, but handles calls from LLVM generated code.
1541 * This is only needed on arm to handle thumb interop.
1544 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, const char *got_symbol, int offset, int info_offset)
1546 #if defined(TARGET_ARM)
1547 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
1548 /* The caller already transitioned to thumb */
1549 /* The code below should be 12 bytes long */
1550 /* clang has trouble encoding these instructions, so emit the binary */
1552 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
1553 /* thumb can't encode ld pc, [pc, ip] */
1554 fprintf (acfg->fp, "add ip, pc, ip\n");
1555 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
1556 fprintf (acfg->fp, "bx ip\n");
1558 emit_set_thumb_mode (acfg);
1559 fprintf (acfg->fp, ".4byte 0xc008f8df\n");
1560 fprintf (acfg->fp, ".2byte 0x44fc\n");
1561 fprintf (acfg->fp, ".4byte 0xc000f8dc\n");
1562 fprintf (acfg->fp, ".2byte 0x4760\n");
1563 emit_symbol_diff (acfg, got_symbol, ".", offset + 4);
1564 emit_int32 (acfg, info_offset);
1565 emit_unset_mode (acfg);
1566 emit_set_arm_mode (acfg);
1568 g_assert_not_reached ();
1572 /* Save unwind_info in the module and emit the offset to the information at symbol */
1573 static void save_unwind_info (MonoAotCompile *acfg, char *symbol, GSList *unwind_ops)
1575 guint32 uw_offset, encoded_len;
1578 emit_section_change (acfg, RODATA_SECT, 0);
1579 emit_global (acfg, symbol, FALSE);
1580 emit_label (acfg, symbol);
1582 encoded = mono_unwind_ops_encode (unwind_ops, &encoded_len);
1583 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
1585 emit_int32 (acfg, uw_offset);
1589 * arch_emit_specific_trampoline_pages:
1591 * Emits a page full of trampolines: each trampoline uses its own address to
1592 * lookup both the generic trampoline code and the data argument.
1593 * This page can be remapped in process multiple times so we can get an
1594 * unlimited number of trampolines.
1595 * Specifically this implementation uses the following trick: two memory pages
1596 * are allocated, with the first containing the data and the second containing the trampolines.
1597 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
1598 * implementation does all the lifting.
1599 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
1600 * on the arm 32 bit system.
1603 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
1605 #if defined(TARGET_ARM)
1608 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
1610 int pagesize = MONO_AOT_TRAMP_PAGE_SIZE;
1611 GSList *unwind_ops = NULL;
1612 #define COMMON_TRAMP_SIZE 16
1613 int count = (pagesize - COMMON_TRAMP_SIZE) / 8;
1614 int imm8, rot_amount;
1617 if (!acfg->aot_opts.use_trampolines_page)
1620 acfg->tramp_page_size = pagesize;
1622 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
1623 emit_alignment (acfg, pagesize);
1624 emit_global (acfg, symbol, TRUE);
1625 emit_label (acfg, symbol);
1627 /* emit the generic code first, the trampoline address + 8 is in the lr register */
1629 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1630 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
1631 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
1632 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
1634 g_assert (code - buf == COMMON_TRAMP_SIZE);
1637 emit_bytes (acfg, buf, code - buf);
1639 for (i = 0; i < count; ++i) {
1641 ARM_PUSH (code, 0x5fff);
1643 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1644 g_assert (code - buf == 8);
1645 emit_bytes (acfg, buf, code - buf);
1648 /* now the rgctx trampolines: each specific trampolines puts in the ip register
1649 * the instruction pointer address, so the generic trampoline at the start of the page
1650 * subtracts 4096 to get to the data page and loads the values
1651 * We again fit the generic trampiline in 16 bytes.
1653 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
1654 emit_global (acfg, symbol, TRUE);
1655 emit_label (acfg, symbol);
1657 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1658 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1659 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
1660 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1662 g_assert (code - buf == COMMON_TRAMP_SIZE);
1665 emit_bytes (acfg, buf, code - buf);
1667 for (i = 0; i < count; ++i) {
1669 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1671 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1672 g_assert (code - buf == 8);
1673 emit_bytes (acfg, buf, code - buf);
1677 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1679 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1680 emit_global (acfg, symbol, TRUE);
1681 emit_label (acfg, symbol);
1683 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1684 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1685 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1686 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1687 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1688 g_assert (code - buf == COMMON_TRAMP_SIZE);
1690 emit_bytes (acfg, buf, code - buf);
1692 for (i = 0; i < count; ++i) {
1694 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1696 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1697 g_assert (code - buf == 8);
1698 emit_bytes (acfg, buf, code - buf);
1701 /* now the imt trampolines: each specific trampolines puts in the ip register
1702 * the instruction pointer address, so the generic trampoline at the start of the page
1703 * subtracts 4096 to get to the data page and loads the values
1705 #define IMT_TRAMP_SIZE 72
1706 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1707 emit_global (acfg, symbol, TRUE);
1708 emit_label (acfg, symbol);
1710 /* Need at least two free registers, plus a slot for storing the pc */
1711 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1713 imm8 = mono_arm_is_rotated_imm8 (pagesize, &rot_amount);
1714 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1715 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1717 /* The IMT method is in v5, r0 has the imt array address */
1720 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1721 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1722 imt_found_check = code;
1723 ARM_B_COND (code, ARMCOND_EQ, 0);
1725 /* End-of-loop check */
1726 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1727 loop_end_check = code;
1728 ARM_B_COND (code, ARMCOND_EQ, 0);
1731 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1732 loop_branch_back = code;
1734 arm_patch (loop_branch_back, loop_start);
1737 arm_patch (imt_found_check, code);
1738 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1739 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1740 /* Save it to the third stack slot */
1741 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1742 /* Restore the registers and branch */
1743 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1746 arm_patch (loop_end_check, code);
1747 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1748 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1749 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1753 g_assert (code - buf == IMT_TRAMP_SIZE);
1754 emit_bytes (acfg, buf, code - buf);
1756 for (i = 0; i < count; ++i) {
1758 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1760 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1761 g_assert (code - buf == 8);
1762 emit_bytes (acfg, buf, code - buf);
1765 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_SPECIFIC] = 16;
1766 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_STATIC_RGCTX] = 16;
1767 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_IMT] = 72;
1768 acfg->tramp_page_code_offsets [MONO_AOT_TRAMP_GSHAREDVT_ARG] = 16;
1770 /* Unwind info for specifc trampolines */
1771 sprintf (symbol, "%sspecific_trampolines_page_gen_p", acfg->user_symbol_prefix);
1772 /* We unwind to the original caller, from the stack, since lr is clobbered */
1773 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 14 * sizeof (mgreg_t));
1774 mono_add_unwind_op_offset (unwind_ops, 0, 0, ARMREG_LR, -4);
1775 save_unwind_info (acfg, symbol, unwind_ops);
1776 mono_free_unwind_info (unwind_ops);
1778 sprintf (symbol, "%sspecific_trampolines_page_sp_p", acfg->user_symbol_prefix);
1779 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1780 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 14 * sizeof (mgreg_t));
1781 save_unwind_info (acfg, symbol, unwind_ops);
1782 mono_free_unwind_info (unwind_ops);
1784 /* Unwind info for rgctx trampolines */
1785 sprintf (symbol, "%srgctx_trampolines_page_gen_p", acfg->user_symbol_prefix);
1786 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1787 save_unwind_info (acfg, symbol, unwind_ops);
1789 sprintf (symbol, "%srgctx_trampolines_page_sp_p", acfg->user_symbol_prefix);
1790 save_unwind_info (acfg, symbol, unwind_ops);
1791 mono_free_unwind_info (unwind_ops);
1793 /* Unwind info for gsharedvt trampolines */
1794 sprintf (symbol, "%sgsharedvt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1795 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1796 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 4 * sizeof (mgreg_t));
1797 save_unwind_info (acfg, symbol, unwind_ops);
1798 mono_free_unwind_info (unwind_ops);
1800 sprintf (symbol, "%sgsharedvt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1801 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1802 save_unwind_info (acfg, symbol, unwind_ops);
1803 mono_free_unwind_info (unwind_ops);
1805 /* Unwind info for imt trampolines */
1806 sprintf (symbol, "%simt_trampolines_page_gen_p", acfg->user_symbol_prefix);
1807 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1808 mono_add_unwind_op_def_cfa_offset (unwind_ops, 4, 0, 3 * sizeof (mgreg_t));
1809 save_unwind_info (acfg, symbol, unwind_ops);
1810 mono_free_unwind_info (unwind_ops);
1812 sprintf (symbol, "%simt_trampolines_page_sp_p", acfg->user_symbol_prefix);
1813 mono_add_unwind_op_def_cfa (unwind_ops, 0, 0, ARMREG_SP, 0);
1814 save_unwind_info (acfg, symbol, unwind_ops);
1815 mono_free_unwind_info (unwind_ops);
1816 #elif defined(TARGET_ARM64)
1817 arm64_emit_specific_trampoline_pages (acfg);
1822 * arch_emit_specific_trampoline:
1824 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1825 * two GOT slots which contain the generic trampoline address and the trampoline
1826 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1829 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1832 * The trampolines created here are variations of the specific
1833 * trampolines created in mono_arch_create_specific_trampoline (). The
1835 * - the generic trampoline address is taken from a got slot.
1836 * - the offset of the got slot where the trampoline argument is stored
1837 * is embedded in the instruction stream, and the generic trampoline
1838 * can load the argument by loading the offset, adding it to the
1839 * address of the trampoline to get the address of the got slot, and
1840 * loading the argument from there.
1841 * - all the trampolines should be of the same length.
1843 #if defined(TARGET_AMD64)
1844 /* This should be exactly 8 bytes long */
1846 /* call *<offset>(%rip) */
1848 emit_unset_mode (acfg);
1849 fprintf (acfg->fp, "call *%s+%d(%%rip)\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
1850 emit_zero_bytes (acfg, 2);
1852 emit_byte (acfg, '\x41');
1853 emit_byte (acfg, '\xff');
1854 emit_byte (acfg, '\x15');
1855 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1856 emit_zero_bytes (acfg, 1);
1858 #elif defined(TARGET_ARM)
1862 /* This should be exactly 20 bytes long */
1865 ARM_PUSH (code, 0x5fff);
1866 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1867 /* Load the value from the GOT */
1868 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1870 ARM_BLX_REG (code, ARMREG_R1);
1872 g_assert (code - buf == 16);
1875 emit_bytes (acfg, buf, code - buf);
1877 * Only one offset is needed, since the second one would be equal to the
1880 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1881 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1882 #elif defined(TARGET_ARM64)
1883 arm64_emit_specific_trampoline (acfg, offset, tramp_size);
1884 #elif defined(TARGET_POWERPC)
1892 * PPC has no ip relative addressing, so we need to compute the address
1893 * of the mscorlib got. That is slow and complex, so instead, we store it
1894 * in the second got slot of every aot image. The caller already computed
1895 * the address of its got and placed it into r30.
1897 emit_unset_mode (acfg);
1898 /* Load mscorlib got address */
1899 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1900 /* Load generic trampoline address */
1901 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1902 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1903 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1904 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1905 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1907 fprintf (acfg->fp, "mtctr 11\n");
1908 /* Load trampoline argument */
1909 /* On ppc, we pass it normally to the generic trampoline */
1910 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1911 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1912 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1913 /* Branch to generic trampoline */
1914 fprintf (acfg->fp, "bctr\n");
1916 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1917 *tramp_size = 10 * 4;
1919 *tramp_size = 9 * 4;
1921 #elif defined(TARGET_X86)
1925 /* Similar to the PPC code above */
1927 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1930 /* Load mscorlib got address */
1931 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1932 /* Push trampoline argument */
1933 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1934 /* Load generic trampoline address */
1935 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1936 /* Branch to generic trampoline */
1937 x86_jump_reg (code, X86_ECX);
1939 emit_bytes (acfg, buf, code - buf);
1942 g_assert (code - buf == *tramp_size);
1944 g_assert_not_reached ();
1949 * arch_emit_unbox_trampoline:
1951 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1952 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1955 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1957 #if defined(TARGET_AMD64)
1962 this_reg = mono_arch_get_this_arg_reg (NULL);
1964 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1966 emit_bytes (acfg, buf, code - buf);
1969 emit_unset_mode (acfg);
1970 fprintf (acfg->fp, "jmp %s\n", call_target);
1972 emit_byte (acfg, '\xe9');
1973 emit_symbol_diff (acfg, call_target, ".", -4);
1975 #elif defined(TARGET_X86)
1982 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1984 emit_bytes (acfg, buf, code - buf);
1987 emit_byte (acfg, '\xe9');
1988 emit_symbol_diff (acfg, call_target, ".", -4);
1989 #elif defined(TARGET_ARM)
1993 if (acfg->thumb_mixed && cfg->compile_llvm) {
1994 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1995 fprintf (acfg->fp, "b %s\n", call_target);
1996 fprintf (acfg->fp, ".arm\n");
1997 fprintf (acfg->fp, ".align 2\n");
2003 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
2005 emit_bytes (acfg, buf, code - buf);
2006 /* jump to method */
2007 if (acfg->thumb_mixed && cfg->compile_llvm)
2008 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
2010 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2011 #elif defined(TARGET_ARM64)
2012 arm64_emit_unbox_trampoline (acfg, cfg, method, call_target);
2013 #elif defined(TARGET_POWERPC)
2016 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
2017 fprintf (acfg->fp, "\n\tb %s\n", call_target);
2019 g_assert_not_reached ();
2024 * arch_emit_static_rgctx_trampoline:
2026 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
2027 * two GOT slots which contain the rgctx argument, and the method to jump to.
2028 * TRAMP_SIZE is set to the size of the emitted trampoline.
2029 * These kinds of trampolines cannot be enumerated statically, since there could
2030 * be one trampoline per method instantiation, so we emit the same code for all
2031 * trampolines, and parameterize them using two GOT slots.
2034 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2036 #if defined(TARGET_AMD64)
2037 /* This should be exactly 13 bytes long */
2041 emit_unset_mode (acfg);
2042 fprintf (acfg->fp, "mov %s+%d(%%rip), %%r10\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)));
2043 fprintf (acfg->fp, "jmp *%s+%d(%%rip)\n", acfg->got_symbol, (int)((offset + 1) * sizeof (gpointer)));
2045 /* mov <OFFSET>(%rip), %r10 */
2046 emit_byte (acfg, '\x4d');
2047 emit_byte (acfg, '\x8b');
2048 emit_byte (acfg, '\x15');
2049 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2051 /* jmp *<offset>(%rip) */
2052 emit_byte (acfg, '\xff');
2053 emit_byte (acfg, '\x25');
2054 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
2056 #elif defined(TARGET_ARM)
2060 /* This should be exactly 24 bytes long */
2063 /* Load rgctx value */
2064 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
2065 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
2066 /* Load branch addr + branch */
2067 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
2068 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
2070 g_assert (code - buf == 16);
2073 emit_bytes (acfg, buf, code - buf);
2074 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
2075 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
2076 #elif defined(TARGET_ARM64)
2077 arm64_emit_static_rgctx_trampoline (acfg, offset, tramp_size);
2078 #elif defined(TARGET_POWERPC)
2086 * PPC has no ip relative addressing, so we need to compute the address
2087 * of the mscorlib got. That is slow and complex, so instead, we store it
2088 * in the second got slot of every aot image. The caller already computed
2089 * the address of its got and placed it into r30.
2091 emit_unset_mode (acfg);
2092 /* Load mscorlib got address */
2093 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
2095 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
2096 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
2097 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
2098 /* Load target address */
2099 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
2100 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
2101 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
2102 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2103 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
2104 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
2106 fprintf (acfg->fp, "mtctr 11\n");
2107 /* Branch to the target address */
2108 fprintf (acfg->fp, "bctr\n");
2110 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
2111 *tramp_size = 11 * 4;
2113 *tramp_size = 9 * 4;
2116 #elif defined(TARGET_X86)
2120 /* Similar to the PPC code above */
2122 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2125 /* Load mscorlib got address */
2126 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2128 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
2129 /* Branch to the target address */
2130 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2132 emit_bytes (acfg, buf, code - buf);
2135 g_assert (code - buf == *tramp_size);
2137 g_assert_not_reached ();
2142 * arch_emit_imt_trampoline:
2144 * Emit an IMT trampoline usable in full-aot mode. The trampoline uses 1 got slot which
2145 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
2146 * key is the IMT key, and ptr holds the address of a memory location holding
2147 * the address to branch to if the IMT arg matches the key. The array is
2148 * terminated by a pair whose key is NULL, and whose ptr is the address of the
2150 * TRAMP_SIZE is set to the size of the emitted trampoline.
2153 arch_emit_imt_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2155 #if defined(TARGET_AMD64)
2157 guint8 *labels [16];
2159 guint8 *mov_buf_ptr = mov_buf;
2161 const int kSizeOfMove = 7;
2163 code = buf = (guint8 *)g_malloc (256);
2165 /* FIXME: Optimize this, i.e. use binary search etc. */
2166 /* Maybe move the body into a separate function (slower, but much smaller) */
2168 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
2171 emit_unset_mode (acfg);
2172 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (int)(offset * sizeof (gpointer)), mono_arch_regname (MONO_ARCH_IMT_SCRATCH_REG));
2176 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2178 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2181 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
2183 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2186 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
2187 amd64_jump_code (code, labels [0]);
2190 mono_amd64_patch (labels [2], code);
2191 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
2192 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2195 mono_amd64_patch (labels [1], code);
2196 /* Load fail tramp */
2197 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
2198 /* Check if there is a fail tramp */
2199 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
2201 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
2202 /* Jump to fail tramp */
2203 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
2206 mono_amd64_patch (labels [3], code);
2207 x86_breakpoint (code);
2210 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
2211 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
2212 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
2213 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
2214 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
2215 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
2217 emit_bytes (acfg, buf, code - buf);
2219 *tramp_size = code - buf + kSizeOfMove;
2223 #elif defined(TARGET_X86)
2225 guint8 *labels [16];
2227 code = buf = g_malloc (256);
2229 /* Allocate a temporary stack slot */
2230 x86_push_reg (code, X86_EAX);
2232 x86_push_reg (code, X86_EAX);
2234 /* Load mscorlib got address */
2235 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2237 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
2240 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2242 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2245 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
2247 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2250 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
2251 x86_jump_code (code, labels [0]);
2254 mono_x86_patch (labels [2], code);
2255 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2256 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
2257 /* Save the target address to the temporary stack location */
2258 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2260 x86_pop_reg (code, X86_EAX);
2261 /* Jump to the target address */
2265 mono_x86_patch (labels [1], code);
2266 /* Load fail tramp */
2267 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
2268 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
2270 x86_branch8 (code, X86_CC_Z, FALSE, 0);
2271 /* Jump to fail tramp */
2272 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
2273 x86_pop_reg (code, X86_EAX);
2277 mono_x86_patch (labels [3], code);
2278 x86_breakpoint (code);
2280 emit_bytes (acfg, buf, code - buf);
2282 *tramp_size = code - buf;
2286 #elif defined(TARGET_ARM)
2288 guint8 *code, *code2, *labels [16];
2292 /* The IMT method is in v5 */
2294 /* Need at least two free registers, plus a slot for storing the pc */
2295 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
2297 /* Load the parameter from the GOT */
2298 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
2299 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
2302 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
2303 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
2305 ARM_B_COND (code, ARMCOND_EQ, 0);
2307 /* End-of-loop check */
2308 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
2310 ARM_B_COND (code, ARMCOND_EQ, 0);
2313 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
2316 arm_patch (labels [4], labels [1]);
2319 arm_patch (labels [2], code);
2320 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2321 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
2322 /* Save it to the third stack slot */
2323 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2324 /* Restore the registers and branch */
2325 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2328 arm_patch (labels [3], code);
2329 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
2330 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
2331 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
2335 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
2337 emit_bytes (acfg, buf, code - buf);
2338 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
2340 *tramp_size = code - buf + 4;
2341 #elif defined(TARGET_ARM64)
2342 arm64_emit_imt_trampoline (acfg, offset, tramp_size);
2343 #elif defined(TARGET_POWERPC)
2345 guint8 *code, *labels [16];
2349 /* Load the mscorlib got address */
2350 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r30);
2351 /* Load the parameter from the GOT */
2352 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
2353 ppc_ldptr_indexed (code, ppc_r12, ppc_r12, ppc_r0);
2355 /* Load and check key */
2357 ppc_ldptr (code, ppc_r0, 0, ppc_r12);
2358 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
2360 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2362 /* End-of-loop check */
2363 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
2365 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
2368 ppc_addi (code, ppc_r12, ppc_r12, 2 * sizeof (gpointer));
2371 mono_ppc_patch (labels [4], labels [1]);
2374 mono_ppc_patch (labels [2], code);
2375 ppc_ldptr (code, ppc_r12, sizeof (gpointer), ppc_r12);
2376 /* r12 now contains the value of the vtable slot */
2377 /* this is not a function descriptor on ppc64 */
2378 ppc_ldptr (code, ppc_r12, 0, ppc_r12);
2379 ppc_mtctr (code, ppc_r12);
2380 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
2383 mono_ppc_patch (labels [3], code);
2387 *tramp_size = code - buf;
2389 emit_bytes (acfg, buf, code - buf);
2391 g_assert_not_reached ();
2396 #if defined (TARGET_AMD64)
2399 amd64_emit_load_got_slot (MonoAotCompile *acfg, int dreg, int got_slot)
2402 g_assert (acfg->fp);
2403 emit_unset_mode (acfg);
2405 fprintf (acfg->fp, "mov %s+%d(%%rip), %s\n", acfg->got_symbol, (unsigned int) ((got_slot * sizeof (gpointer))), mono_arch_regname (dreg));
2412 * arch_emit_gsharedvt_arg_trampoline:
2414 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
2415 * two GOT slots which contain the argument, and the code to jump to.
2416 * TRAMP_SIZE is set to the size of the emitted trampoline.
2417 * These kinds of trampolines cannot be enumerated statically, since there could
2418 * be one trampoline per method instantiation, so we emit the same code for all
2419 * trampolines, and parameterize them using two GOT slots.
2422 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
2424 #if defined(TARGET_X86)
2428 /* Similar to the PPC code above */
2430 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
2433 /* Load mscorlib got address */
2434 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
2436 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
2437 /* Branch to the target address */
2438 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
2440 emit_bytes (acfg, buf, code - buf);
2443 g_assert (code - buf == *tramp_size);
2444 #elif defined(TARGET_ARM)
2448 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
2449 /* Similar to arch_emit_specific_trampoline () */
2452 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
2453 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
2454 /* Load the arg value from the GOT */
2455 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
2456 /* Load the addr from the GOT */
2457 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
2459 ARM_BX (code, ARMREG_R1);
2461 g_assert (code - buf == 20);
2464 emit_bytes (acfg, buf, code - buf);
2465 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
2466 #elif defined(TARGET_ARM64)
2467 arm64_emit_gsharedvt_arg_trampoline (acfg, offset, tramp_size);
2468 #elif defined (TARGET_AMD64)
2470 amd64_emit_load_got_slot (acfg, AMD64_RAX, offset);
2471 amd64_emit_load_got_slot (acfg, MONO_ARCH_IMT_SCRATCH_REG, offset + 1);
2472 g_assert (AMD64_R11 == MONO_ARCH_IMT_SCRATCH_REG);
2473 fprintf (acfg->fp, "jmp *%%r11\n");
2477 g_assert_not_reached ();
2481 /* END OF ARCH SPECIFIC CODE */
2484 mono_get_field_token (MonoClassField *field)
2486 MonoClass *klass = field->parent;
2489 for (i = 0; i < klass->field.count; ++i) {
2490 if (field == &klass->fields [i])
2491 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
2494 g_assert_not_reached ();
2499 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
2503 //printf ("ENCODE: %d 0x%x.\n", value, value);
2506 * Same encoding as the one used in the metadata, extended to handle values
2507 * greater than 0x1fffffff.
2509 if ((value >= 0) && (value <= 127))
2511 else if ((value >= 0) && (value <= 16383)) {
2512 p [0] = 0x80 | (value >> 8);
2513 p [1] = value & 0xff;
2515 } else if ((value >= 0) && (value <= 0x1fffffff)) {
2516 p [0] = (value >> 24) | 0xc0;
2517 p [1] = (value >> 16) & 0xff;
2518 p [2] = (value >> 8) & 0xff;
2519 p [3] = value & 0xff;
2524 p [1] = (value >> 24) & 0xff;
2525 p [2] = (value >> 16) & 0xff;
2526 p [3] = (value >> 8) & 0xff;
2527 p [4] = value & 0xff;
2535 stream_init (MonoDynamicStream *sh)
2538 sh->alloc_size = 4096;
2539 sh->data = (char *)g_malloc (4096);
2541 /* So offsets are > 0 */
2547 make_room_in_stream (MonoDynamicStream *stream, int size)
2549 if (size <= stream->alloc_size)
2552 while (stream->alloc_size <= size) {
2553 if (stream->alloc_size < 4096)
2554 stream->alloc_size = 4096;
2556 stream->alloc_size *= 2;
2559 stream->data = (char *)g_realloc (stream->data, stream->alloc_size);
2563 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2567 make_room_in_stream (stream, stream->index + len);
2568 memcpy (stream->data + stream->index, data, len);
2569 idx = stream->index;
2570 stream->index += len;
2577 * Add data to the binary blob inside the aot image. Returns the offset inside the
2578 * blob where the data was stored.
2581 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2583 g_assert (!acfg->blob_closed);
2585 if (acfg->blob.alloc_size == 0)
2586 stream_init (&acfg->blob);
2588 return add_stream_data (&acfg->blob, (char*)data, data_len);
2592 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2597 if (acfg->blob.alloc_size == 0)
2598 stream_init (&acfg->blob);
2600 count = acfg->blob.index % align;
2602 /* we assume the stream data will be aligned */
2604 add_stream_data (&acfg->blob, buf, 4 - count);
2606 return add_stream_data (&acfg->blob, (char*)data, data_len);
2609 /* Emit a table of data into the aot image */
2611 emit_aot_data (MonoAotCompile *acfg, MonoAotFileTable table, const char *symbol, guint8 *data, int size)
2613 if (acfg->data_outfile) {
2614 acfg->table_offsets [(int)table] = acfg->datafile_offset;
2615 fwrite (data,1, size, acfg->data_outfile);
2616 acfg->datafile_offset += size;
2617 // align the data to 8 bytes. Put zeros in the file (so that every build results in consistent output).
2618 int align = 8 - size % 8;
2619 acfg->datafile_offset += align;
2620 guint8 align_buf [16];
2621 memset (&align_buf, 0, sizeof (align_buf));
2622 fwrite (align_buf, align, 1, acfg->data_outfile);
2623 } else if (acfg->llvm) {
2624 mono_llvm_emit_aot_data (symbol, data, size);
2626 emit_section_change (acfg, RODATA_SECT, 0);
2627 emit_alignment (acfg, 8);
2628 emit_label (acfg, symbol);
2629 emit_bytes (acfg, data, size);
2634 * emit_offset_table:
2636 * Emit a table of increasing offsets in a compact form using differential encoding.
2637 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2638 * group size, the more compact the table becomes, but the slower it becomes to compute
2639 * a given entry. Returns the size of the table.
2642 emit_offset_table (MonoAotCompile *acfg, const char *symbol, MonoAotFileTable table, int noffsets, int group_size, gint32 *offsets)
2644 gint32 current_offset;
2645 int i, buf_size, ngroups, index_entry_size;
2647 guint8 *data_p, *data_buf;
2648 guint32 *index_offsets;
2650 ngroups = (noffsets + (group_size - 1)) / group_size;
2652 index_offsets = g_new0 (guint32, ngroups);
2654 buf_size = noffsets * 4;
2655 p = buf = (guint8 *)g_malloc0 (buf_size);
2658 for (i = 0; i < noffsets; ++i) {
2659 //printf ("D: %d -> %d\n", i, offsets [i]);
2660 if ((i % group_size) == 0) {
2661 index_offsets [i / group_size] = p - buf;
2662 /* Emit the full value for these entries */
2663 encode_value (offsets [i], p, &p);
2665 /* The offsets are allowed to be non-increasing */
2666 //g_assert (offsets [i] >= current_offset);
2667 encode_value (offsets [i] - current_offset, p, &p);
2669 current_offset = offsets [i];
2674 if (ngroups && index_offsets [ngroups - 1] < 65000)
2675 index_entry_size = 2;
2677 index_entry_size = 4;
2679 buf_size = (data_p - data_buf) + (ngroups * 4) + 16;
2680 p = buf = (guint8 *)g_malloc0 (buf_size);
2682 /* Emit the header */
2683 encode_int (noffsets, p, &p);
2684 encode_int (group_size, p, &p);
2685 encode_int (ngroups, p, &p);
2686 encode_int (index_entry_size, p, &p);
2688 /* Emit the index */
2689 for (i = 0; i < ngroups; ++i) {
2690 if (index_entry_size == 2)
2691 encode_int16 (index_offsets [i], p, &p);
2693 encode_int (index_offsets [i], p, &p);
2696 memcpy (p, data_buf, data_p - data_buf);
2697 p += data_p - data_buf;
2699 g_assert (p - buf <= buf_size);
2701 emit_aot_data (acfg, table, symbol, buf, p - buf);
2706 return (int)(p - buf);
2710 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2714 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2718 index = g_hash_table_size (cfg->image_hash);
2719 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2720 g_ptr_array_add (cfg->image_table, image);
2726 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2729 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2731 /* FIXME: Search referenced images as well */
2732 if (!acfg->typespec_classes) {
2733 acfg->typespec_classes = g_hash_table_new (NULL, NULL);
2734 for (i = 0; i < len; i++) {
2736 int typespec = MONO_TOKEN_TYPE_SPEC | (i + 1);
2737 MonoClass *klass_key = mono_class_get_and_inflate_typespec_checked (acfg->image, typespec, NULL, &error);
2738 if (!is_ok (&error)) {
2739 mono_error_cleanup (&error);
2742 g_hash_table_insert (acfg->typespec_classes, klass_key, GINT_TO_POINTER (typespec));
2745 return GPOINTER_TO_INT (g_hash_table_lookup (acfg->typespec_classes, klass));
2749 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2752 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2755 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2758 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2761 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2766 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2770 if (klass->generic_class) {
2772 g_assert (klass->type_token);
2774 /* Find a typespec for a class if possible */
2775 token = find_typespec_for_class (acfg, klass);
2777 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2778 encode_value (token, p, &p);
2780 MonoClass *gclass = klass->generic_class->container_class;
2781 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2782 static int count = 0;
2785 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2786 encode_klass_ref (acfg, gclass, p, &p);
2787 encode_ginst (acfg, inst, p, &p);
2791 } else if (klass->type_token) {
2792 int iindex = get_image_index (acfg, klass->image);
2794 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2796 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2797 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2799 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2800 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2801 encode_value (get_image_index (acfg, klass->image), p, &p);
2803 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2804 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2805 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2807 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2809 encode_value (par->gshared_constraint ? 1 : 0, p, &p);
2810 if (par->gshared_constraint) {
2811 MonoGSharedGenericParam *gpar = (MonoGSharedGenericParam*)par;
2812 encode_type (acfg, par->gshared_constraint, p, &p);
2813 encode_klass_ref (acfg, mono_class_from_generic_parameter (gpar->parent, NULL, klass->byval_arg.type == MONO_TYPE_MVAR), p, &p);
2815 encode_value (klass->byval_arg.type, p, &p);
2816 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2818 encode_value (container->is_anonymous ? 0 : 1, p, &p);
2820 if (!container->is_anonymous) {
2821 encode_value (container->is_method, p, &p);
2822 if (container->is_method)
2823 encode_method_ref (acfg, container->owner.method, p, &p);
2825 encode_klass_ref (acfg, container->owner.klass, p, &p);
2828 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2829 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2830 encode_type (acfg, &klass->byval_arg, p, &p);
2833 g_assert (klass->rank > 0);
2834 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2835 encode_value (klass->rank, p, &p);
2836 encode_klass_ref (acfg, klass->element_class, p, &p);
2844 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2845 * standard metadata encoding.
2848 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2850 gboolean shared = FALSE;
2853 * The encoding of generic instances is large so emit them only once.
2855 if (klass->generic_class) {
2857 g_assert (klass->type_token);
2859 /* Find a typespec for a class if possible */
2860 token = find_typespec_for_class (acfg, klass);
2863 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2868 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2872 buf2 = (guint8 *)g_malloc (1024);
2875 encode_klass_ref_inner (acfg, klass, p, &p);
2876 g_assert (p - buf2 < 1024);
2878 offset = add_to_blob (acfg, buf2, p - buf2);
2881 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2887 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2888 encode_value (offset, p, &p);
2893 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2897 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2899 guint32 token = mono_get_field_token (field);
2902 encode_klass_ref (cfg, field->parent, p, &p);
2903 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2904 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2909 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2914 encode_value (inst->type_argc, p, &p);
2915 for (i = 0; i < inst->type_argc; ++i)
2916 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2921 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2924 MonoGenericInst *inst;
2926 inst = context->class_inst;
2928 g_assert (inst->type_argc);
2929 encode_ginst (acfg, inst, p, &p);
2931 encode_value (0, p, &p);
2933 inst = context->method_inst;
2935 g_assert (inst->type_argc);
2936 encode_ginst (acfg, inst, p, &p);
2938 encode_value (0, p, &p);
2944 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2948 g_assert (t->num_mods == 0);
2949 /* t->attrs can be ignored */
2950 //g_assert (t->attrs == 0);
2953 *p = MONO_TYPE_PINNED;
2957 *p = MONO_TYPE_BYREF;
2965 case MONO_TYPE_VOID:
2966 case MONO_TYPE_BOOLEAN:
2967 case MONO_TYPE_CHAR:
2980 case MONO_TYPE_STRING:
2981 case MONO_TYPE_OBJECT:
2982 case MONO_TYPE_TYPEDBYREF:
2984 case MONO_TYPE_VALUETYPE:
2985 case MONO_TYPE_CLASS:
2986 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2988 case MONO_TYPE_SZARRAY:
2989 encode_klass_ref (acfg, t->data.klass, p, &p);
2992 encode_type (acfg, t->data.type, p, &p);
2994 case MONO_TYPE_GENERICINST: {
2995 MonoClass *gclass = t->data.generic_class->container_class;
2996 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2998 encode_klass_ref (acfg, gclass, p, &p);
2999 encode_ginst (acfg, inst, p, &p);
3002 case MONO_TYPE_ARRAY: {
3003 MonoArrayType *array = t->data.array;
3006 encode_klass_ref (acfg, array->eklass, p, &p);
3007 encode_value (array->rank, p, &p);
3008 encode_value (array->numsizes, p, &p);
3009 for (i = 0; i < array->numsizes; ++i)
3010 encode_value (array->sizes [i], p, &p);
3011 encode_value (array->numlobounds, p, &p);
3012 for (i = 0; i < array->numlobounds; ++i)
3013 encode_value (array->lobounds [i], p, &p);
3017 case MONO_TYPE_MVAR:
3018 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
3021 g_assert_not_reached ();
3028 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
3034 /* Similar to the metadata encoding */
3035 if (sig->generic_param_count)
3039 if (sig->explicit_this)
3041 flags |= (sig->call_convention & 0x0F);
3045 if (sig->generic_param_count)
3046 encode_value (sig->generic_param_count, p, &p);
3047 encode_value (sig->param_count, p, &p);
3049 encode_type (acfg, sig->ret, p, &p);
3050 for (i = 0; i < sig->param_count; ++i) {
3051 if (sig->sentinelpos == i) {
3052 *p = MONO_TYPE_SENTINEL;
3055 encode_type (acfg, sig->params [i], p, &p);
3061 #define MAX_IMAGE_INDEX 250
3064 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
3066 guint32 image_index = get_image_index (acfg, method->klass->image);
3067 guint32 token = method->token;
3068 MonoJumpInfoToken *ji;
3072 * The encoding for most methods is as follows:
3073 * - image index encoded as a leb128
3074 * - token index encoded as a leb128
3075 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
3076 * types of method encodings.
3079 /* Mark methods which can't use aot trampolines because they need the further
3080 * processing in mono_magic_trampoline () which requires a MonoMethod*.
3082 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
3083 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
3084 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
3086 if (method->wrapper_type) {
3087 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3089 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
3091 encode_value (method->wrapper_type, p, &p);
3093 switch (method->wrapper_type) {
3094 case MONO_WRAPPER_REMOTING_INVOKE:
3095 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3096 case MONO_WRAPPER_XDOMAIN_INVOKE: {
3099 m = mono_marshal_method_from_wrapper (method);
3101 encode_method_ref (acfg, m, p, &p);
3104 case MONO_WRAPPER_PROXY_ISINST:
3105 case MONO_WRAPPER_LDFLD:
3106 case MONO_WRAPPER_LDFLDA:
3107 case MONO_WRAPPER_STFLD:
3108 case MONO_WRAPPER_ISINST: {
3110 encode_klass_ref (acfg, info->d.proxy.klass, p, &p);
3113 case MONO_WRAPPER_ALLOC: {
3114 /* The GC name is saved once in MonoAotFileInfo */
3115 g_assert (info->d.alloc.alloc_type != -1);
3116 encode_value (info->d.alloc.alloc_type, p, &p);
3119 case MONO_WRAPPER_WRITE_BARRIER: {
3123 case MONO_WRAPPER_STELEMREF: {
3125 encode_value (info->subtype, p, &p);
3126 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
3127 encode_value (info->d.virtual_stelemref.kind, p, &p);
3130 case MONO_WRAPPER_UNKNOWN: {
3132 encode_value (info->subtype, p, &p);
3133 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
3134 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
3135 encode_klass_ref (acfg, method->klass, p, &p);
3136 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
3137 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
3138 else if (info->subtype == WRAPPER_SUBTYPE_ARRAY_ACCESSOR)
3139 encode_method_ref (acfg, info->d.array_accessor.method, p, &p);
3140 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG)
3141 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3142 else if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)
3143 encode_signature (acfg, info->d.gsharedvt.sig, p, &p);
3146 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
3148 encode_value (info->subtype, p, &p);
3149 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
3150 strcpy ((char*)p, method->name);
3151 p += strlen (method->name) + 1;
3152 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
3153 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3155 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE || info->subtype == WRAPPER_SUBTYPE_PINVOKE);
3156 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
3160 case MONO_WRAPPER_SYNCHRONIZED: {
3163 m = mono_marshal_method_from_wrapper (method);
3165 g_assert (m != method);
3166 encode_method_ref (acfg, m, p, &p);
3169 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
3171 encode_value (info->subtype, p, &p);
3173 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
3174 encode_value (info->d.element_addr.rank, p, &p);
3175 encode_value (info->d.element_addr.elem_size, p, &p);
3176 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
3177 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
3179 g_assert_not_reached ();
3183 case MONO_WRAPPER_CASTCLASS: {
3185 encode_value (info->subtype, p, &p);
3188 case MONO_WRAPPER_RUNTIME_INVOKE: {
3190 encode_value (info->subtype, p, &p);
3191 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
3192 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
3193 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
3194 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
3197 case MONO_WRAPPER_DELEGATE_INVOKE:
3198 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3199 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
3200 if (method->is_inflated) {
3201 /* These wrappers are identified by their class */
3202 encode_value (1, p, &p);
3203 encode_klass_ref (acfg, method->klass, p, &p);
3205 MonoMethodSignature *sig = mono_method_signature (method);
3206 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3208 encode_value (0, p, &p);
3209 if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
3210 encode_value (info ? info->subtype : 0, p, &p);
3211 encode_signature (acfg, sig, p, &p);
3215 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
3217 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
3218 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
3222 g_assert_not_reached ();
3224 } else if (mono_method_signature (method)->is_inflated) {
3226 * This is a generic method, find the original token which referenced it and
3228 * Obtain the token from information recorded by the JIT.
3230 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3232 image_index = get_image_index (acfg, ji->image);
3233 g_assert (image_index < MAX_IMAGE_INDEX);
3236 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3237 encode_value (image_index, p, &p);
3238 encode_value (token, p, &p);
3240 MonoMethod *declaring;
3241 MonoGenericContext *context = mono_method_get_context (method);
3243 g_assert (method->is_inflated);
3244 declaring = ((MonoMethodInflated*)method)->declaring;
3247 * This might be a non-generic method of a generic instance, which
3248 * doesn't have a token since the reference is generated by the JIT
3249 * like Nullable:Box/Unbox, or by generic sharing.
3251 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
3252 /* Encode the klass */
3253 encode_klass_ref (acfg, method->klass, p, &p);
3254 /* Encode the method */
3255 image_index = get_image_index (acfg, method->klass->image);
3256 g_assert (image_index < MAX_IMAGE_INDEX);
3257 g_assert (declaring->token);
3258 token = declaring->token;
3259 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3260 encode_value (image_index, p, &p);
3261 encode_value (token, p, &p);
3262 encode_generic_context (acfg, context, p, &p);
3264 } else if (token == 0) {
3265 /* This might be a method of a constructed type like int[,].Set */
3266 /* Obtain the token from information recorded by the JIT */
3267 ji = (MonoJumpInfoToken *)g_hash_table_lookup (acfg->token_info_hash, method);
3269 image_index = get_image_index (acfg, ji->image);
3270 g_assert (image_index < MAX_IMAGE_INDEX);
3273 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
3274 encode_value (image_index, p, &p);
3275 encode_value (token, p, &p);
3278 g_assert (method->klass->rank);
3280 /* Encode directly */
3281 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
3282 encode_klass_ref (acfg, method->klass, p, &p);
3283 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
3284 encode_value (0, p, &p);
3285 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
3286 encode_value (1, p, &p);
3287 else if (!strcmp (method->name, "Get"))
3288 encode_value (2, p, &p);
3289 else if (!strcmp (method->name, "Address"))
3290 encode_value (3, p, &p);
3291 else if (!strcmp (method->name, "Set"))
3292 encode_value (4, p, &p);
3294 g_assert_not_reached ();
3297 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
3299 if (image_index >= MONO_AOT_METHODREF_MIN) {
3300 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
3301 encode_value (image_index, p, &p);
3302 encode_value (mono_metadata_token_index (token), p, &p);
3304 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
3311 compare_patches (gconstpointer a, gconstpointer b)
3315 i = (*(MonoJumpInfo**)a)->ip.i;
3316 j = (*(MonoJumpInfo**)b)->ip.i;
3327 static G_GNUC_UNUSED char*
3328 patch_to_string (MonoJumpInfo *patch_info)
3332 str = g_string_new ("");
3334 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
3336 switch (patch_info->type) {
3337 case MONO_PATCH_INFO_VTABLE:
3338 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
3343 g_string_append_printf (str, ")");
3344 return g_string_free (str, FALSE);
3350 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
3353 static inline gboolean
3354 is_plt_patch (MonoJumpInfo *patch_info)
3356 switch (patch_info->type) {
3357 case MONO_PATCH_INFO_METHOD:
3358 case MONO_PATCH_INFO_INTERNAL_METHOD:
3359 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3360 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
3361 case MONO_PATCH_INFO_RGCTX_FETCH:
3371 * Return the symbol identifying the plt entry PLT_OFFSET.
3374 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
3378 * The Apple linker reorganizes object files, so it doesn't like branches to local
3379 * labels, since those have no relocations.
3381 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
3383 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
3390 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
3392 static MonoPltEntry*
3393 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3396 gboolean synchronized = FALSE;
3397 static int synchronized_symbol_idx;
3399 if (!is_plt_patch (patch_info))
3402 if (!acfg->patch_to_plt_entry [patch_info->type])
3403 acfg->patch_to_plt_entry [patch_info->type] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
3404 res = (MonoPltEntry *)g_hash_table_lookup (acfg->patch_to_plt_entry [patch_info->type], patch_info);
3406 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
3408 * Allocate a separate PLT slot for each such patch, since some plt
3409 * entries will refer to the method itself, and some will refer to the
3413 synchronized = TRUE;
3417 MonoJumpInfo *new_ji;
3419 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3421 res = (MonoPltEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
3422 res->plt_offset = acfg->plt_offset;
3424 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
3425 if (acfg->aot_opts.write_symbols)
3426 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
3428 /* Avoid duplicate symbols because we don't cache */
3429 res->symbol = g_strdup_printf ("%s_%d", res->symbol, synchronized_symbol_idx);
3431 res->debug_sym = g_strdup_printf ("%s_%d", res->debug_sym, synchronized_symbol_idx);
3432 synchronized_symbol_idx ++;
3435 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
3437 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
3439 g_hash_table_insert (acfg->patch_to_plt_entry [new_ji->type], new_ji, res);
3441 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
3443 //g_assert (mono_patch_info_equal (patch_info, new_ji));
3444 //mono_print_ji (patch_info); printf ("\n");
3445 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
3447 acfg->plt_offset ++;
3456 * Returns the offset of the GOT slot where the runtime object resulting from resolving
3457 * JI could be found if it exists, otherwise allocates a new one.
3460 get_got_offset (MonoAotCompile *acfg, gboolean llvm, MonoJumpInfo *ji)
3463 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
3465 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (info->patch_to_got_offset_by_type [ji->type], ji));
3467 return got_offset - 1;
3470 got_offset = acfg->llvm_got_offset;
3471 acfg->llvm_got_offset ++;
3473 got_offset = acfg->got_offset;
3474 acfg->got_offset ++;
3477 acfg->stats.got_slots ++;
3478 acfg->stats.got_slot_types [ji->type] ++;
3480 g_hash_table_insert (info->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
3481 g_hash_table_insert (info->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
3482 g_ptr_array_add (info->got_patches, ji);
3487 /* Add a method to the list of methods which need to be emitted */
3489 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
3492 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
3493 g_ptr_array_add (acfg->methods, method);
3494 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
3495 acfg->nmethods = acfg->methods->len + 1;
3498 if (method->wrapper_type || extra)
3499 g_ptr_array_add (acfg->extra_methods, method);
3503 prefer_gsharedvt_method (MonoAotCompile *acfg, MonoMethod *method)
3505 /* One instantiation with valuetypes is generated for each async method */
3506 if (method->klass->image == mono_defaults.corlib && (!strcmp (method->klass->name, "AsyncMethodBuilderCore") || !strcmp (method->klass->name, "AsyncVoidMethodBuilder")))
3513 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
3515 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3523 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
3527 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
3531 index = acfg->method_index;
3532 add_method_with_index (acfg, method, index, extra);
3534 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
3536 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
3538 acfg->method_index ++;
3544 add_method (MonoAotCompile *acfg, MonoMethod *method)
3546 return add_method_full (acfg, method, FALSE, 0);
3550 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
3552 if (mono_method_is_generic_sharable_full (method, TRUE, TRUE, FALSE))
3553 method = mini_get_shared_method (method);
3554 else if ((acfg->opts & MONO_OPT_GSHAREDVT) && prefer_gsharedvt_method (acfg, method) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, TRUE))
3555 /* Use the gsharedvt version */
3556 method = mini_get_shared_method_full (method, TRUE, TRUE);
3558 if (acfg->aot_opts.log_generics)
3559 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
3561 add_method_full (acfg, method, TRUE, depth);
3565 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
3567 add_extra_method_with_depth (acfg, method, 0);
3571 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
3573 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
3574 MonoJitICallInfo *callinfo = (MonoJitICallInfo *)value;
3575 MonoMethod *wrapper;
3581 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
3582 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, TRUE);
3585 add_method (acfg, wrapper);
3589 get_runtime_invoke_sig (MonoMethodSignature *sig)
3591 MonoMethodBuilder *mb;
3594 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
3595 m = mono_mb_create_method (mb, sig, 16);
3596 MonoMethod *invoke = mono_marshal_get_runtime_invoke (m, FALSE);
3602 get_runtime_invoke (MonoAotCompile *acfg, MonoMethod *method, gboolean virtual_)
3604 return mono_marshal_get_runtime_invoke (method, virtual_);
3608 can_marshal_struct (MonoClass *klass)
3610 MonoClassField *field;
3611 gboolean can_marshal = TRUE;
3612 gpointer iter = NULL;
3613 MonoMarshalType *info;
3616 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3619 info = mono_marshal_load_type_info (klass);
3621 /* Only allow a few field types to avoid asserts in the marshalling code */
3622 while ((field = mono_class_get_fields (klass, &iter))) {
3623 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3626 switch (field->type->type) {
3631 case MONO_TYPE_BOOLEAN:
3634 case MONO_TYPE_CHAR:
3642 case MONO_TYPE_STRING:
3644 case MONO_TYPE_VALUETYPE:
3645 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3646 can_marshal = FALSE;
3648 case MONO_TYPE_SZARRAY: {
3649 gboolean has_mspec = FALSE;
3652 for (i = 0; i < info->num_fields; ++i) {
3653 if (info->fields [i].field == field && info->fields [i].mspec)
3658 can_marshal = FALSE;
3662 can_marshal = FALSE;
3668 /* Its hard to compute whenever these can be marshalled or not */
3669 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3676 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3678 /* Create a vtype instantiation */
3679 MonoGenericContext shared_context;
3681 MonoGenericInst *inst;
3682 MonoGenericContainer *container;
3683 MonoClass **constraints;
3686 memset (ctx, 0, sizeof (MonoGenericContext));
3688 if (method->klass->generic_container) {
3689 shared_context = method->klass->generic_container->context;
3690 inst = shared_context.class_inst;
3692 args = g_new0 (MonoType*, inst->type_argc);
3693 for (i = 0; i < inst->type_argc; ++i) {
3694 args [i] = &mono_defaults.int_class->byval_arg;
3696 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3698 if (method->is_generic) {
3699 container = mono_method_get_generic_container (method);
3700 shared_context = container->context;
3701 inst = shared_context.method_inst;
3703 args = g_new0 (MonoType*, inst->type_argc);
3704 for (i = 0; i < container->type_argc; ++i) {
3705 MonoGenericParamInfo *info = &container->type_params [i].info;
3706 gboolean ref_only = FALSE;
3708 if (info && info->constraints) {
3709 constraints = info->constraints;
3711 while (*constraints) {
3712 MonoClass *cklass = *constraints;
3713 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3714 /* Inflaring the method with our vtype would not be valid */
3721 args [i] = &mono_defaults.object_class->byval_arg;
3723 args [i] = &mono_defaults.int_class->byval_arg;
3725 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3730 add_wrappers (MonoAotCompile *acfg)
3732 MonoMethod *method, *m;
3734 MonoMethodSignature *sig, *csig;
3738 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3739 * so there is only one wrapper of a given type, or inlining their contents into their
3742 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3745 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3746 gboolean skip = FALSE;
3748 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3749 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
3751 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3752 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3753 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3756 /* Skip methods which can not be handled by get_runtime_invoke () */
3757 sig = mono_method_signature (method);
3760 if ((sig->ret->type == MONO_TYPE_PTR) ||
3761 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3763 if (mono_class_is_open_constructed_type (sig->ret))
3766 for (j = 0; j < sig->param_count; j++) {
3767 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3769 if (mono_class_is_open_constructed_type (sig->params [j]))
3773 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3774 if (!mono_class_is_contextbound (method->klass)) {
3775 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3776 gboolean has_nullable = FALSE;
3778 for (j = 0; j < sig->param_count; j++) {
3779 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3780 has_nullable = TRUE;
3783 if (info && !has_nullable && !acfg->aot_opts.llvm_only) {
3784 /* Supported by the dynamic runtime-invoke wrapper */
3788 mono_arch_dyn_call_free (info);
3792 if (acfg->aot_opts.llvm_only)
3793 /* Supported by the gsharedvt based runtime-invoke wrapper */
3797 //printf ("%s\n", mono_method_full_name (method, TRUE));
3798 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3802 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3805 /* Runtime invoke wrappers */
3807 /* void runtime-invoke () [.cctor] */
3808 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 () [Finalize] */
3813 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3815 csig->ret = &mono_defaults.void_class->byval_arg;
3816 add_method (acfg, get_runtime_invoke_sig (csig));
3818 /* void runtime-invoke (string) [exception ctor] */
3819 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3821 csig->ret = &mono_defaults.void_class->byval_arg;
3822 csig->params [0] = &mono_defaults.string_class->byval_arg;
3823 add_method (acfg, get_runtime_invoke_sig (csig));
3825 /* void runtime-invoke (string, string) [exception ctor] */
3826 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3828 csig->ret = &mono_defaults.void_class->byval_arg;
3829 csig->params [0] = &mono_defaults.string_class->byval_arg;
3830 csig->params [1] = &mono_defaults.string_class->byval_arg;
3831 add_method (acfg, get_runtime_invoke_sig (csig));
3833 /* string runtime-invoke () [Exception.ToString ()] */
3834 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3836 csig->ret = &mono_defaults.string_class->byval_arg;
3837 add_method (acfg, get_runtime_invoke_sig (csig));
3839 /* void runtime-invoke (string, Exception) [exception ctor] */
3840 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3842 csig->ret = &mono_defaults.void_class->byval_arg;
3843 csig->params [0] = &mono_defaults.string_class->byval_arg;
3844 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3845 add_method (acfg, get_runtime_invoke_sig (csig));
3847 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3848 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3850 csig->ret = &(mono_class_load_from_name (
3851 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3852 csig->params [0] = &mono_defaults.string_class->byval_arg;
3853 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3854 add_method (acfg, get_runtime_invoke_sig (csig));
3856 /* runtime-invoke used by finalizers */
3857 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3859 /* This is used by mono_runtime_capture_context () */
3860 method = mono_get_context_capture_method ();
3862 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3864 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3865 if (!acfg->aot_opts.llvm_only)
3866 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3869 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3870 if (acfg->aot_opts.llvm_only) {
3873 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3874 for (variants = 0; variants < 4; ++variants) {
3875 for (i = 0; i < 16; ++i) {
3876 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3877 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3885 add_method (acfg, mono_marshal_get_stelemref ());
3887 if (MONO_ARCH_HAVE_TLS_GET) {
3888 /* Managed Allocators */
3889 nallocators = mono_gc_get_managed_allocator_types ();
3890 for (i = 0; i < nallocators; ++i) {
3891 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3892 add_method (acfg, m);
3893 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3894 add_method (acfg, m);
3898 /* write barriers */
3899 if (mono_gc_is_moving ()) {
3900 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3901 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3904 /* Stelemref wrappers */
3906 MonoMethod **wrappers;
3909 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3910 for (i = 0; i < nwrappers; ++i)
3911 add_method (acfg, wrappers [i]);
3915 /* castclass_with_check wrapper */
3916 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3917 /* isinst_with_check wrapper */
3918 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3920 /* JIT icall wrappers */
3921 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3922 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3926 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3927 * we use the original method instead at runtime.
3928 * Since full-aot doesn't support remoting, this is not a problem.
3931 /* remoting-invoke wrappers */
3932 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3934 MonoMethodSignature *sig;
3936 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3937 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3938 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3940 sig = mono_method_signature (method);
3942 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3943 m = mono_marshal_get_remoting_invoke_with_check (method);
3945 add_method (acfg, m);
3950 /* delegate-invoke wrappers */
3951 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3954 MonoCustomAttrInfo *cattr;
3956 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3957 klass = mono_class_get_checked (acfg->image, token, &error);
3960 mono_error_cleanup (&error);
3964 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3967 if (!klass->generic_container) {
3968 method = mono_get_delegate_invoke (klass);
3970 m = mono_marshal_get_delegate_invoke (method, NULL);
3972 add_method (acfg, m);
3974 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3976 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3978 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3980 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3982 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3983 if (!is_ok (&error)) {
3984 mono_error_cleanup (&error);
3991 for (j = 0; j < cattr->num_attrs; ++j)
3992 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3994 if (j < cattr->num_attrs) {
3996 MonoMethod *wrapper;
3997 MonoMethod *del_invoke;
3999 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4000 invoke = mono_get_delegate_invoke (klass);
4001 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4002 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4003 add_method (acfg, wrapper);
4004 add_method (acfg, del_invoke);
4007 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
4009 MonoGenericContext ctx;
4010 MonoMethod *inst, *gshared;
4013 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4016 method = mono_get_delegate_invoke (klass);
4017 create_gsharedvt_inst (acfg, method, &ctx);
4019 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4020 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4022 m = mono_marshal_get_delegate_invoke (inst, NULL);
4023 g_assert (m->is_inflated);
4025 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4026 add_extra_method (acfg, gshared);
4029 method = mono_get_delegate_begin_invoke (klass);
4030 create_gsharedvt_inst (acfg, method, &ctx);
4032 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4033 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4035 m = mono_marshal_get_delegate_begin_invoke (inst);
4036 g_assert (m->is_inflated);
4038 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4039 add_extra_method (acfg, gshared);
4042 method = mono_get_delegate_end_invoke (klass);
4043 create_gsharedvt_inst (acfg, method, &ctx);
4045 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4046 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4048 m = mono_marshal_get_delegate_end_invoke (inst);
4049 g_assert (m->is_inflated);
4051 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4052 add_extra_method (acfg, gshared);
4057 /* array access wrappers */
4058 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4062 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4063 klass = mono_class_get_checked (acfg->image, token, &error);
4066 mono_error_cleanup (&error);
4070 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4071 MonoMethod *m, *wrapper;
4073 /* Add runtime-invoke wrappers too */
4075 m = mono_class_get_method_from_name (klass, "Get", -1);
4077 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4078 add_extra_method (acfg, wrapper);
4079 if (!acfg->aot_opts.llvm_only)
4080 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4082 m = mono_class_get_method_from_name (klass, "Set", -1);
4084 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4085 add_extra_method (acfg, wrapper);
4086 if (!acfg->aot_opts.llvm_only)
4087 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4091 /* Synchronized wrappers */
4092 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4094 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4095 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4096 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4098 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4099 if (method->is_generic) {
4101 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
4103 MonoGenericContext ctx;
4104 MonoMethod *inst, *gshared, *m;
4107 * Create a generic wrapper for a generic instance, and AOT that.
4109 create_gsharedvt_inst (acfg, method, &ctx);
4110 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4111 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4112 m = mono_marshal_get_synchronized_wrapper (inst);
4113 g_assert (m->is_inflated);
4114 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4115 add_method (acfg, gshared);
4117 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4122 /* pinvoke wrappers */
4123 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4126 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4128 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4129 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4131 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4132 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4133 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4137 /* native-to-managed wrappers */
4138 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4141 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4142 MonoCustomAttrInfo *cattr;
4145 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4146 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4149 * Only generate native-to-managed wrappers for methods which have an
4150 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4151 * name to avoid defining a new assembly to contain it.
4153 cattr = mono_custom_attrs_from_method_checked (method, &error);
4154 if (!is_ok (&error)) {
4155 char *name = mono_method_get_full_name (method);
4156 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4161 for (j = 0; j < cattr->num_attrs; ++j)
4162 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4164 if (j < cattr->num_attrs) {
4165 MonoCustomAttrEntry *e = &cattr->attrs [j];
4166 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4167 const char *p = (const char*)e->data;
4169 int slen, num_named, named_type;
4173 char *export_name = NULL;
4174 MonoMethod *wrapper;
4176 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4177 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4178 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4179 mono_method_full_name (method, TRUE));
4183 g_assert (sig->param_count == 1);
4184 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4187 * Decode the cattr manually since we can't create objects
4188 * during aot compilation.
4194 /* From load_cattr_value () in reflection.c */
4195 slen = mono_metadata_decode_value (p, &p);
4196 n = (char *)g_memdup (p, slen + 1);
4198 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4200 mono_error_assert_ok (&error);
4203 klass = mono_class_from_mono_type (t);
4204 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4208 num_named = read16 (p);
4211 g_assert (num_named < 2);
4212 if (num_named == 1) {
4216 /* parse ExportSymbol attribute */
4218 named_type = *named;
4220 /* data_type = *named; */
4223 name_len = mono_metadata_decode_blob_size (named, &named);
4224 name = (char *)g_malloc (name_len + 1);
4225 memcpy (name, named, name_len);
4226 name [name_len] = 0;
4229 g_assert (named_type == 0x54);
4230 g_assert (!strcmp (name, "ExportSymbol"));
4232 /* load_cattr_value (), string case */
4233 g_assert (*named != (char)0xff);
4234 slen = mono_metadata_decode_value (named, &named);
4235 export_name = (char *)g_malloc (slen + 1);
4236 memcpy (export_name, named, slen);
4237 export_name [slen] = 0;
4241 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4242 add_method (acfg, wrapper);
4244 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4249 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4250 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4251 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4255 /* StructureToPtr/PtrToStructure wrappers */
4256 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4260 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4261 klass = mono_class_get_checked (acfg->image, token, &error);
4264 mono_error_cleanup (&error);
4268 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4269 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4270 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4271 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4277 has_type_vars (MonoClass *klass)
4279 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4282 return has_type_vars (klass->element_class);
4283 if (klass->generic_class) {
4284 MonoGenericContext *context = &klass->generic_class->context;
4285 if (context->class_inst) {
4288 for (i = 0; i < context->class_inst->type_argc; ++i)
4289 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4293 if (klass->generic_container)
4299 is_vt_inst (MonoGenericInst *inst)
4303 for (i = 0; i < inst->type_argc; ++i) {
4304 MonoType *t = inst->type_argv [i];
4305 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4312 method_has_type_vars (MonoMethod *method)
4314 if (has_type_vars (method->klass))
4317 if (method->is_inflated) {
4318 MonoGenericContext *context = mono_method_get_context (method);
4319 if (context->method_inst) {
4322 for (i = 0; i < context->method_inst->type_argc; ++i)
4323 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4331 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4333 return opts->mode == MONO_AOT_MODE_FULL;
4337 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4339 return opts->mode == MONO_AOT_MODE_HYBRID;
4342 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4345 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4347 /* This might lead to a huge code blowup so only do it if neccesary */
4348 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4351 add_generic_class_with_depth (acfg, klass, 0, ref);
4355 check_type_depth (MonoType *t, int depth)
4363 case MONO_TYPE_GENERICINST: {
4364 MonoGenericClass *gklass = t->data.generic_class;
4365 MonoGenericInst *ginst = gklass->context.class_inst;
4368 for (i = 0; i < ginst->type_argc; ++i) {
4369 if (check_type_depth (ginst->type_argv [i], depth + 1))
4383 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4386 * add_generic_class:
4388 * Add all methods of a generic class.
4391 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4394 MonoClassField *field;
4396 gboolean use_gsharedvt = FALSE;
4398 if (!acfg->ginst_hash)
4399 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4401 mono_class_init (klass);
4403 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4406 if (has_type_vars (klass))
4409 if (!klass->generic_class && !klass->rank)
4412 if (mono_class_has_failure (klass))
4415 if (!acfg->ginst_hash)
4416 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4418 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4421 if (check_type_depth (&klass->byval_arg, 0))
4424 if (acfg->aot_opts.log_generics)
4425 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4427 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4430 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4431 * Enable this only for some classes since gsharedvt might not support all methods.
4433 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) &&
4434 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4435 use_gsharedvt = TRUE;
4438 while ((method = mono_class_get_methods (klass, &iter))) {
4439 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4441 * This is partial sharing, and we can't handle it yet
4446 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4448 add_types_from_method_header (acfg, method);
4452 if (method->is_generic)
4457 * FIXME: Instances which are referenced by these methods are not added,
4458 * for example Array.Resize<int> for List<int>.Add ().
4460 add_extra_method_with_depth (acfg, method, depth + 1);
4464 while ((field = mono_class_get_fields (klass, &iter))) {
4465 if (field->type->type == MONO_TYPE_GENERICINST)
4466 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4469 if (klass->delegate) {
4470 method = mono_get_delegate_invoke (klass);
4472 method = mono_marshal_get_delegate_invoke (method, NULL);
4474 if (acfg->aot_opts.log_generics)
4475 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4477 add_method (acfg, method);
4480 /* Add superclasses */
4482 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4485 * For ICollection<T>, add instances of the helper methods
4486 * in Array, since a T[] could be cast to ICollection<T>.
4488 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4489 (!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"))) {
4490 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4491 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4495 if (!strcmp (klass->name, "IEnumerator`1"))
4496 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4498 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4500 /* Add the T[]/InternalEnumerator class */
4501 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4506 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4507 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4511 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4512 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4513 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4517 while ((method = mono_class_get_methods (array_class, &iter))) {
4518 if (strstr (method->name, name_prefix)) {
4519 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4521 add_extra_method_with_depth (acfg, m, depth);
4525 g_free (name_prefix);
4528 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4529 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4531 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4532 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4533 MonoGenericContext ctx;
4534 MonoType *args [16];
4536 memset (&ctx, 0, sizeof (ctx));
4538 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4540 args [0] = &tclass->byval_arg;
4541 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4543 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4544 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4546 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4547 MonoClass *gcomparer_inst;
4548 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4549 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4550 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4552 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4556 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4557 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4559 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4560 MonoClass *iface, *gcomparer, *iface_inst;
4561 MonoGenericContext ctx;
4562 MonoType *args [16];
4564 memset (&ctx, 0, sizeof (ctx));
4566 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4568 args [0] = &tclass->byval_arg;
4569 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4571 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4572 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4574 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4575 MonoClass *gcomparer_inst;
4578 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4579 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4580 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4581 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4585 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4586 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4587 MonoClass *enum_comparer;
4588 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4589 MonoGenericContext ctx;
4590 MonoType *args [16];
4592 if (mono_class_is_enum (tclass)) {
4593 MonoClass *enum_comparer_inst;
4596 memset (&ctx, 0, sizeof (ctx));
4597 args [0] = &tclass->byval_arg;
4598 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4600 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4601 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4602 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4603 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4607 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4608 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4609 MonoClass *comparer;
4610 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4611 MonoGenericContext ctx;
4612 MonoType *args [16];
4614 if (mono_class_is_enum (tclass)) {
4615 MonoClass *comparer_inst;
4618 memset (&ctx, 0, sizeof (ctx));
4619 args [0] = &tclass->byval_arg;
4620 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4622 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4623 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4624 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4625 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4631 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4634 MonoGenericContext ctx;
4635 MonoType *args [16];
4637 if (acfg->aot_opts.no_instances)
4640 memset (&ctx, 0, sizeof (ctx));
4642 for (i = 0; i < ninsts; ++i) {
4644 MonoClass *generic_inst;
4645 args [0] = insts [i];
4646 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4647 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4648 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4649 add_generic_class (acfg, generic_inst, force, "");
4654 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4657 MonoMethodHeader *header;
4658 MonoMethodSignature *sig;
4661 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4663 sig = mono_method_signature (method);
4666 for (j = 0; j < sig->param_count; ++j)
4667 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4668 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4671 header = mono_method_get_header_checked (method, &error);
4674 for (j = 0; j < header->num_locals; ++j)
4675 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4676 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4677 mono_metadata_free_mh (header);
4679 mono_error_cleanup (&error); /* FIXME report the error */
4685 * add_generic_instances:
4687 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4690 add_generic_instances (MonoAotCompile *acfg)
4695 MonoGenericContext *context;
4697 if (acfg->aot_opts.no_instances)
4700 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4702 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4703 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4706 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4707 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4708 mono_error_cleanup (&error);
4712 if (method->klass->image != acfg->image)
4715 context = mono_method_get_context (method);
4717 if (context && ((context->class_inst && context->class_inst->is_open)))
4721 * For open methods, create an instantiation which can be passed to the JIT.
4722 * FIXME: Handle class_inst as well.
4724 if (context && context->method_inst && context->method_inst->is_open) {
4726 MonoGenericContext shared_context;
4727 MonoGenericInst *inst;
4728 MonoType **type_argv;
4730 MonoMethod *declaring_method;
4731 gboolean supported = TRUE;
4733 /* Check that the context doesn't contain open constructed types */
4734 if (context->class_inst) {
4735 inst = context->class_inst;
4736 for (i = 0; i < inst->type_argc; ++i) {
4737 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)
4739 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4743 if (context->method_inst) {
4744 inst = context->method_inst;
4745 for (i = 0; i < inst->type_argc; ++i) {
4746 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)
4748 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4756 memset (&shared_context, 0, sizeof (MonoGenericContext));
4758 inst = context->class_inst;
4760 type_argv = g_new0 (MonoType*, inst->type_argc);
4761 for (i = 0; i < inst->type_argc; ++i) {
4762 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)
4763 type_argv [i] = &mono_defaults.object_class->byval_arg;
4765 type_argv [i] = inst->type_argv [i];
4768 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4772 inst = context->method_inst;
4774 type_argv = g_new0 (MonoType*, inst->type_argc);
4775 for (i = 0; i < inst->type_argc; ++i) {
4776 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)
4777 type_argv [i] = &mono_defaults.object_class->byval_arg;
4779 type_argv [i] = inst->type_argv [i];
4782 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4786 if (method->is_generic || method->klass->generic_container)
4787 declaring_method = method;
4789 declaring_method = mono_method_get_declaring_generic_method (method);
4791 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4792 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4796 * If the method is fully sharable, it was already added in place of its
4797 * generic definition.
4799 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4803 * FIXME: Partially shared methods are not shared here, so we end up with
4804 * many identical methods.
4806 add_extra_method (acfg, method);
4809 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4813 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4815 klass = mono_class_get_checked (acfg->image, token, &error);
4816 if (!klass || klass->rank) {
4817 mono_error_cleanup (&error);
4821 add_generic_class (acfg, klass, FALSE, "typespec");
4824 /* Add types of args/locals */
4825 for (i = 0; i < acfg->methods->len; ++i) {
4826 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4827 add_types_from_method_header (acfg, method);
4830 if (acfg->image == mono_defaults.corlib) {
4832 MonoType *insts [256];
4835 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4836 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4837 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4838 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4839 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4840 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4841 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4842 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4843 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4844 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4845 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4846 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4848 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4849 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4851 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4852 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4854 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4856 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4858 MonoClass *enum_comparer;
4859 MonoType *insts [16];
4863 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4864 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4865 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4866 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4867 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4868 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4871 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4872 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4873 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4876 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4877 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4878 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4880 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4882 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4883 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4884 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4887 /* Add instances of the array generic interfaces for primitive types */
4888 /* This will add instances of the InternalArray_ helper methods in Array too */
4889 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4891 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4893 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4895 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4897 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4899 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4902 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4903 * used for all instances of GetGenericValueImpl by the AOT runtime.
4906 MonoGenericContext ctx;
4907 MonoType *args [16];
4908 MonoMethod *get_method;
4909 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4911 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4915 memset (&ctx, 0, sizeof (ctx));
4916 args [0] = &mono_defaults.object_class->byval_arg;
4917 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4918 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4919 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4923 /* Same for CompareExchange<T>/Exchange<T> */
4925 MonoGenericContext ctx;
4926 MonoType *args [16];
4928 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4929 gpointer iter = NULL;
4931 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4932 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4934 memset (&ctx, 0, sizeof (ctx));
4935 args [0] = &mono_defaults.object_class->byval_arg;
4936 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4937 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4938 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4943 /* Same for Volatile.Read/Write<T> */
4945 MonoGenericContext ctx;
4946 MonoType *args [16];
4948 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4949 gpointer iter = NULL;
4951 if (volatile_klass) {
4952 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4953 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4955 memset (&ctx, 0, sizeof (ctx));
4956 args [0] = &mono_defaults.object_class->byval_arg;
4957 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4958 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4959 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4965 /* object[] accessor wrappers. */
4966 for (i = 1; i < 4; ++i) {
4967 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
4970 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
4973 m = mono_marshal_get_array_accessor_wrapper (m);
4974 add_extra_method (acfg, m);
4976 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
4979 m = mono_marshal_get_array_accessor_wrapper (m);
4980 add_extra_method (acfg, m);
4982 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
4985 m = mono_marshal_get_array_accessor_wrapper (m);
4986 add_extra_method (acfg, m);
4992 * is_direct_callable:
4994 * Return whenever the method identified by JI is directly callable without
4995 * going through the PLT.
4998 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5000 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5001 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5003 gboolean direct_callable = TRUE;
5005 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5006 direct_callable = FALSE;
5007 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5008 // FIXME: Maybe call the wrapper directly ?
5009 direct_callable = FALSE;
5011 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5012 /* Disable this so all calls go through load_method (), see the
5013 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5014 * mono_debugger_agent_init ().
5016 direct_callable = FALSE;
5019 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5020 /* sgen does some initialization when the allocator method is created */
5021 direct_callable = FALSE;
5022 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5023 /* we don't know at compile time whether sgen is concurrent or not */
5024 direct_callable = FALSE;
5026 if (direct_callable)
5029 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5030 if (acfg->aot_opts.direct_pinvoke)
5032 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5033 if (acfg->aot_opts.direct_icalls)
5041 #ifdef MONO_ARCH_AOT_SUPPORTED
5043 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5045 MonoImage *image = method->klass->image;
5046 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5047 MonoTableInfo *tables = image->tables;
5048 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5049 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5050 guint32 im_cols [MONO_IMPLMAP_SIZE];
5053 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5057 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5060 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5062 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5065 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5067 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5073 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5080 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5082 if (a->native_offset == b->native_offset)
5083 return a->il_offset - b->il_offset;
5085 return a->native_offset - b->native_offset;
5089 * compute_line_numbers:
5091 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5094 static MonoDebugSourceLocation**
5095 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5097 MonoDebugMethodInfo *minfo;
5098 MonoDebugLineNumberEntry *ln_array;
5099 MonoDebugSourceLocation *loc;
5100 int i, prev_line, prev_il_offset;
5101 int *native_to_il_offset = NULL;
5102 MonoDebugSourceLocation **res;
5105 minfo = mono_debug_lookup_method (method);
5108 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5109 if (debug_info->code_size != code_size)
5112 g_assert (code_size);
5114 /* Compute the native->IL offset mapping */
5116 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5117 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5119 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5121 native_to_il_offset = g_new0 (int, code_size + 1);
5123 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5125 MonoDebugLineNumberEntry *lne = &ln_array [i];
5128 for (j = 0; j < lne->native_offset; ++j)
5129 native_to_il_offset [j] = -1;
5132 if (i < debug_info->num_line_numbers - 1) {
5133 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5135 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5136 native_to_il_offset [j] = lne->il_offset;
5138 for (j = lne->native_offset; j < code_size; ++j)
5139 native_to_il_offset [j] = lne->il_offset;
5144 /* Compute the native->line number mapping */
5145 res = g_new0 (MonoDebugSourceLocation*, code_size);
5146 prev_il_offset = -1;
5149 for (i = 0; i < code_size; ++i) {
5150 int il_offset = native_to_il_offset [i];
5152 if (il_offset == -1 || il_offset == prev_il_offset)
5154 prev_il_offset = il_offset;
5155 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5156 if (!(loc && loc->source_file))
5158 if (loc->row == prev_line) {
5159 mono_debug_symfile_free_location (loc);
5162 prev_line = loc->row;
5163 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5165 /* This will cover the prolog too */
5175 get_file_index (MonoAotCompile *acfg, const char *source_file)
5179 // FIXME: Free these
5180 if (!acfg->dwarf_ln_filenames)
5181 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5182 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5184 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5185 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5186 emit_unset_mode (acfg);
5187 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5199 * emit_and_reloc_code:
5201 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5202 * is true, calls are made through the GOT too. This is used for emitting trampolines
5203 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5204 * since trampolines are needed to make PTL work.
5207 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5209 int i, pindex, start_index;
5211 MonoJumpInfo *patch_info;
5212 MonoDebugSourceLocation **locs = NULL;
5213 gboolean skip, prologue_end = FALSE;
5214 #ifdef MONO_ARCH_AOT_SUPPORTED
5215 gboolean direct_call, external_call;
5217 const char *direct_call_target = 0;
5218 const char *direct_pinvoke;
5221 if (acfg->gas_line_numbers && method && debug_info) {
5222 locs = compute_line_numbers (method, code_len, debug_info);
5224 int findex = get_file_index (acfg, "<unknown>");
5225 emit_unset_mode (acfg);
5226 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5230 /* Collect and sort relocations */
5231 patches = g_ptr_array_new ();
5232 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5233 g_ptr_array_add (patches, patch_info);
5234 g_ptr_array_sort (patches, compare_patches);
5237 for (i = 0; i < code_len; i += INST_LEN) {
5239 for (pindex = start_index; pindex < patches->len; ++pindex) {
5240 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5241 if (patch_info->ip.i >= i)
5245 if (locs && locs [i]) {
5246 MonoDebugSourceLocation *loc = locs [i];
5248 const char *options;
5250 findex = get_file_index (acfg, loc->source_file);
5251 emit_unset_mode (acfg);
5253 options = " prologue_end";
5256 prologue_end = TRUE;
5257 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5258 mono_debug_symfile_free_location (loc);
5262 #ifdef MONO_ARCH_AOT_SUPPORTED
5263 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5264 start_index = pindex;
5266 switch (patch_info->type) {
5267 case MONO_PATCH_INFO_NONE:
5269 case MONO_PATCH_INFO_GOT_OFFSET: {
5272 arch_emit_got_offset (acfg, code + i, &code_size);
5273 i += code_size - INST_LEN;
5275 patch_info->type = MONO_PATCH_INFO_NONE;
5278 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5279 int code_size, index;
5280 char *selector = (char *)patch_info->data.target;
5282 if (!acfg->objc_selector_to_index)
5283 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5284 if (!acfg->objc_selectors)
5285 acfg->objc_selectors = g_ptr_array_new ();
5286 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5290 index = acfg->objc_selector_index;
5291 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5292 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5293 acfg->objc_selector_index ++;
5296 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5297 i += code_size - INST_LEN;
5299 patch_info->type = MONO_PATCH_INFO_NONE;
5304 * If this patch is a call, try emitting a direct call instead of
5305 * through a PLT entry. This is possible if the called method is in
5306 * the same assembly and requires no initialization.
5308 direct_call = FALSE;
5309 external_call = FALSE;
5310 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5311 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5312 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5313 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5315 direct_call_target = callee_cfg->asm_symbol;
5316 patch_info->type = MONO_PATCH_INFO_NONE;
5317 acfg->stats.direct_calls ++;
5320 acfg->stats.all_calls ++;
5321 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5322 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5323 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5324 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5326 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5327 if (direct_pinvoke) {
5329 g_assert (strlen (direct_pinvoke) < 1000);
5330 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5333 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5334 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5335 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5336 /* Call to a C function implementing a jit icall */
5338 external_call = TRUE;
5339 g_assert (strlen (sym) < 1000);
5340 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5342 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5343 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5344 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5345 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5346 /* Call to a jit icall without a wrapper */
5348 external_call = TRUE;
5349 g_assert (strlen (sym) < 1000);
5350 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5355 patch_info->type = MONO_PATCH_INFO_NONE;
5356 acfg->stats.direct_calls ++;
5359 if (!got_only && !direct_call) {
5360 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5362 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5364 direct_call_target = plt_entry->symbol;
5366 /* Nullify the patch */
5367 patch_info->type = MONO_PATCH_INFO_NONE;
5368 plt_entry->jit_used = TRUE;
5375 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5376 i += call_size - INST_LEN;
5380 got_slot = get_got_offset (acfg, FALSE, patch_info);
5382 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5383 i += code_size - INST_LEN;
5389 #endif /* MONO_ARCH_AOT_SUPPORTED */
5392 /* Find next patch */
5394 for (pindex = start_index; pindex < patches->len; ++pindex) {
5395 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5396 if (patch_info->ip.i >= i)
5400 /* Try to emit multiple bytes at once */
5401 if (pindex < patches->len && patch_info->ip.i > i) {
5404 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5405 if (locs && locs [limit])
5409 emit_code_bytes (acfg, code + i, limit - i);
5410 i = limit - INST_LEN;
5412 emit_code_bytes (acfg, code + i, INST_LEN);
5417 g_ptr_array_free (patches, TRUE);
5424 * Return a modified version of S which only includes characters permissible in symbols.
5427 sanitize_symbol (MonoAotCompile *acfg, char *s)
5429 gboolean process = FALSE;
5438 for (i = 0; i < len; ++i)
5439 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5444 gs = g_string_sized_new (len);
5445 for (i = 0; i < len; ++i) {
5447 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5448 g_string_append_c (gs, c);
5449 } else if (c > 0x7f) {
5450 /* multi-byte utf8 */
5451 g_string_append_printf (gs, "_0x%x", c);
5454 while (c >> 6 == 0x2) {
5455 g_string_append_printf (gs, "%x", c);
5459 g_string_append_printf (gs, "_");
5462 g_string_append_c (gs, '_');
5466 res = mono_mempool_strdup (acfg->mempool, gs->str);
5467 g_string_free (gs, TRUE);
5472 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5474 char *name1, *name2, *cached;
5475 int i, j, len, count;
5476 MonoMethod *cached_method;
5478 name1 = mono_method_full_name (method, TRUE);
5481 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5482 if ((!prefix || !*prefix) && name1 [0] == 'L')
5486 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5487 char adjustedPrefix [MAX_SYMBOL_SIZE];
5488 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5491 len = strlen (name1);
5492 name2 = (char *)malloc (strlen (prefix) + len + 16);
5493 memcpy (name2, prefix, strlen (prefix));
5494 j = strlen (prefix);
5495 for (i = 0; i < len; ++i) {
5496 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5498 } else if (isalnum (name1 [i])) {
5499 name2 [j ++] = name1 [i];
5500 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5502 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5505 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5515 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5516 if (!(cached_method && cached_method != method))
5518 sprintf (name2 + j, "_%d", count);
5522 cached = g_strdup (name2);
5523 g_hash_table_insert (cache, cached, method);
5529 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5534 char *debug_sym = NULL;
5535 char *symbol = NULL;
5536 int func_alignment = AOT_FUNC_ALIGNMENT;
5539 method = cfg->orig_method;
5540 code = cfg->native_code;
5542 method_index = get_method_index (acfg, method);
5543 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5545 /* Make the labels local */
5546 emit_section_change (acfg, ".text", 0);
5547 emit_alignment_code (acfg, func_alignment);
5549 if (acfg->global_symbols && acfg->need_no_dead_strip)
5550 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5552 emit_label (acfg, cfg->asm_symbol);
5554 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5556 * Write a C style symbol for every method, this has two uses:
5557 * - it works on platforms where the dwarf debugging info is not
5559 * - it allows the setting of breakpoints of aot-ed methods.
5561 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5562 cfg->asm_debug_symbol = g_strdup (debug_sym);
5564 if (acfg->need_no_dead_strip)
5565 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5566 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5567 emit_label (acfg, debug_sym);
5570 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5572 /* Emit a global symbol for the method */
5573 emit_global_inner (acfg, export_name, TRUE);
5574 emit_label (acfg, export_name);
5577 if (cfg->verbose_level > 0)
5578 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5580 acfg->stats.code_size += cfg->code_len;
5582 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5584 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 ()));
5588 if (acfg->aot_opts.write_symbols) {
5590 emit_symbol_size (acfg, debug_sym, ".");
5592 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5596 emit_label (acfg, symbol);
5603 * Encode PATCH_INFO into its disk representation.
5606 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5610 switch (patch_info->type) {
5611 case MONO_PATCH_INFO_NONE:
5613 case MONO_PATCH_INFO_IMAGE:
5614 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5616 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5617 case MONO_PATCH_INFO_JIT_TLS_ID:
5618 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5619 case MONO_PATCH_INFO_GC_NURSERY_START:
5620 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5622 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5623 encode_value (patch_info->data.index, p, &p);
5625 case MONO_PATCH_INFO_METHOD_REL:
5626 encode_value ((gint)patch_info->data.offset, p, &p);
5628 case MONO_PATCH_INFO_SWITCH: {
5629 gpointer *table = (gpointer *)patch_info->data.table->table;
5632 encode_value (patch_info->data.table->table_size, p, &p);
5633 for (k = 0; k < patch_info->data.table->table_size; k++)
5634 encode_value ((int)(gssize)table [k], p, &p);
5637 case MONO_PATCH_INFO_METHODCONST:
5638 case MONO_PATCH_INFO_METHOD:
5639 case MONO_PATCH_INFO_METHOD_JUMP:
5640 case MONO_PATCH_INFO_ICALL_ADDR:
5641 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5642 case MONO_PATCH_INFO_METHOD_RGCTX:
5643 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5644 encode_method_ref (acfg, patch_info->data.method, p, &p);
5646 case MONO_PATCH_INFO_AOT_JIT_INFO:
5647 encode_value (patch_info->data.index, p, &p);
5649 case MONO_PATCH_INFO_INTERNAL_METHOD:
5650 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5651 guint32 len = strlen (patch_info->data.name);
5653 encode_value (len, p, &p);
5655 memcpy (p, patch_info->data.name, len);
5660 case MONO_PATCH_INFO_LDSTR: {
5661 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5662 guint32 token = patch_info->data.token->token;
5663 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5664 encode_value (image_index, p, &p);
5665 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5668 case MONO_PATCH_INFO_RVA:
5669 case MONO_PATCH_INFO_DECLSEC:
5670 case MONO_PATCH_INFO_LDTOKEN:
5671 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5672 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5673 encode_value (patch_info->data.token->token, p, &p);
5674 encode_value (patch_info->data.token->has_context, p, &p);
5675 if (patch_info->data.token->has_context)
5676 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5678 case MONO_PATCH_INFO_EXC_NAME: {
5679 MonoClass *ex_class;
5682 mono_class_load_from_name (mono_defaults.exception_class->image,
5683 "System", (const char *)patch_info->data.target);
5684 encode_klass_ref (acfg, ex_class, p, &p);
5687 case MONO_PATCH_INFO_R4:
5688 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5690 case MONO_PATCH_INFO_R8:
5691 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5692 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5694 case MONO_PATCH_INFO_VTABLE:
5695 case MONO_PATCH_INFO_CLASS:
5696 case MONO_PATCH_INFO_IID:
5697 case MONO_PATCH_INFO_ADJUSTED_IID:
5698 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5700 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5701 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5702 if (patch_info->data.del_tramp->method) {
5703 encode_value (1, p, &p);
5704 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5706 encode_value (0, p, &p);
5708 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5710 case MONO_PATCH_INFO_FIELD:
5711 case MONO_PATCH_INFO_SFLDA:
5712 encode_field_info (acfg, patch_info->data.field, p, &p);
5714 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5716 case MONO_PATCH_INFO_RGCTX_FETCH:
5717 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5718 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5723 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5724 * reference the same method, so encode the method only once.
5726 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5728 buf2 = (guint8 *)g_malloc (1024);
5731 encode_method_ref (acfg, entry->method, p2, &p2);
5732 g_assert (p2 - buf2 < 1024);
5734 offset = add_to_blob (acfg, buf2, p2 - buf2);
5737 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5742 encode_value (offset, p, &p);
5743 g_assert ((int)entry->info_type < 256);
5744 g_assert (entry->data->type < 256);
5745 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5746 encode_patch (acfg, entry->data, p, &p);
5749 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5750 case MONO_PATCH_INFO_AOT_MODULE:
5752 case MONO_PATCH_INFO_SIGNATURE:
5753 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5754 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5756 case MONO_PATCH_INFO_TLS_OFFSET:
5757 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5759 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5760 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5761 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5763 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5764 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5767 encode_method_ref (acfg, info->method, p, &p);
5768 encode_value (info->num_entries, p, &p);
5769 for (i = 0; i < info->num_entries; ++i) {
5770 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5772 encode_value (template_->info_type, p, &p);
5773 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5774 case MONO_PATCH_INFO_CLASS:
5775 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5777 case MONO_PATCH_INFO_FIELD:
5778 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5781 g_assert_not_reached ();
5787 case MONO_PATCH_INFO_LDSTR_LIT: {
5788 const char *s = (const char *)patch_info->data.target;
5789 int len = strlen (s);
5791 encode_value (len, p, &p);
5792 memcpy (p, s, len + 1);
5796 case MONO_PATCH_INFO_VIRT_METHOD:
5797 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5798 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5800 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5803 g_warning ("unable to handle jump info %d", patch_info->type);
5804 g_assert_not_reached ();
5811 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5814 guint32 pindex, offset;
5815 MonoJumpInfo *patch_info;
5817 encode_value (n_patches, p, &p);
5819 for (pindex = 0; pindex < patches->len; ++pindex) {
5820 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5822 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5826 offset = get_got_offset (acfg, llvm, patch_info);
5827 encode_value (offset, p, &p);
5834 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5837 int pindex, buf_size, n_patches;
5839 MonoJumpInfo *patch_info;
5840 guint32 method_index;
5842 guint32 first_got_offset;
5844 method = cfg->orig_method;
5846 method_index = get_method_index (acfg, method);
5848 /* Sort relocations */
5849 patches = g_ptr_array_new ();
5850 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5851 g_ptr_array_add (patches, patch_info);
5852 g_ptr_array_sort (patches, compare_patches);
5854 first_got_offset = acfg->cfgs [method_index]->got_offset;
5856 /**********************/
5857 /* Encode method info */
5858 /**********************/
5860 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5861 p = buf = (guint8 *)g_malloc (buf_size);
5863 if (mono_class_get_cctor (method->klass)) {
5864 encode_value (1, p, &p);
5865 encode_klass_ref (acfg, method->klass, p, &p);
5867 /* Not needed when loading the method */
5868 encode_value (0, p, &p);
5871 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5874 for (pindex = 0; pindex < patches->len; ++pindex) {
5875 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5877 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5878 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5879 patch_info->type = MONO_PATCH_INFO_NONE;
5884 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5885 /* Stored in a GOT slot initialized at module load time */
5886 patch_info->type = MONO_PATCH_INFO_NONE;
5890 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5891 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5892 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5893 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5894 /* Stored in a GOT slot initialized at module load time */
5895 patch_info->type = MONO_PATCH_INFO_NONE;
5899 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5900 /* Calls are made through the PLT */
5901 patch_info->type = MONO_PATCH_INFO_NONE;
5909 g_assert (cfg->has_got_slots);
5911 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5913 g_ptr_array_free (patches, TRUE);
5915 acfg->stats.info_size += p - buf;
5917 g_assert (p - buf < buf_size);
5919 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5924 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5926 guint32 cache_index;
5929 /* Reuse the unwind module to canonize and store unwind info entries */
5930 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5932 /* Use +/- 1 to distinguish 0s from missing entries */
5933 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5941 * It would be easier to use assembler symbols, but the caller needs an
5944 offset = acfg->unwind_info_offset;
5945 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5946 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5949 encode_value (encoded_len, p, &p);
5951 acfg->unwind_info_offset += encoded_len + (p - buf);
5957 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5960 guint32 debug_info_size, seq_points_size;
5962 MonoMethodHeader *header;
5963 guint8 *p, *buf, *debug_info;
5964 MonoJitInfo *jinfo = cfg->jit_info;
5966 gboolean use_unwind_ops = FALSE;
5967 MonoSeqPointInfo *seq_points;
5969 code = cfg->native_code;
5970 header = cfg->header;
5972 if (!acfg->aot_opts.nodebug) {
5973 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5976 debug_info_size = 0;
5979 seq_points = cfg->seq_point_info;
5980 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5982 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5984 p = buf = (guint8 *)g_malloc (buf_size);
5986 use_unwind_ops = cfg->unwind_ops != NULL;
5988 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);
5990 encode_value (flags, p, &p);
5992 if (use_unwind_ops) {
5993 guint32 encoded_len;
5995 guint32 unwind_desc;
5997 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
5999 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6000 encode_value (unwind_desc, p, &p);
6004 encode_value (jinfo->unwind_info, p, &p);
6007 /*Encode the number of holes before the number of clauses to make decoding easier*/
6008 if (jinfo->has_try_block_holes) {
6009 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6010 encode_value (table->num_holes, p, &p);
6013 if (jinfo->has_arch_eh_info) {
6015 * In AOT mode, the code length is calculated from the address of the previous method,
6016 * which could include alignment padding, so calculating the start of the epilog as
6017 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6019 encode_value (jinfo->code_size, p, &p);
6022 /* Exception table */
6023 if (cfg->compile_llvm) {
6025 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6026 * since the information is only available to llc. Instead, we let llc save the data
6027 * into the LSDA, and read it from there at runtime.
6029 /* The assembly might be CIL stripped so emit the data ourselves */
6030 if (header->num_clauses)
6031 encode_value (header->num_clauses, p, &p);
6033 for (k = 0; k < header->num_clauses; ++k) {
6034 MonoExceptionClause *clause;
6036 clause = &header->clauses [k];
6038 encode_value (clause->flags, p, &p);
6039 if (clause->data.catch_class) {
6040 encode_value (1, p, &p);
6041 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6043 encode_value (0, p, &p);
6046 /* Emit the IL ranges too, since they might not be available at runtime */
6047 encode_value (clause->try_offset, p, &p);
6048 encode_value (clause->try_len, p, &p);
6049 encode_value (clause->handler_offset, p, &p);
6050 encode_value (clause->handler_len, p, &p);
6052 /* Emit a list of nesting clauses */
6053 for (i = 0; i < header->num_clauses; ++i) {
6055 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6057 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6059 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6060 encode_value (i, p, &p);
6062 encode_value (-1, p, &p);
6065 if (jinfo->num_clauses)
6066 encode_value (jinfo->num_clauses, p, &p);
6068 for (k = 0; k < jinfo->num_clauses; ++k) {
6069 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6071 encode_value (ei->flags, p, &p);
6072 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6073 /* Not used for catch clauses */
6074 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6075 encode_value (ei->exvar_offset, p, &p);
6077 encode_value (ei->exvar_offset, p, &p);
6080 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6081 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6083 if (ei->data.catch_class) {
6087 buf2 = (guint8 *)g_malloc (4096);
6089 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6091 g_assert (len < 4096);
6092 encode_value (len, p, &p);
6093 memcpy (p, buf2, len);
6097 encode_value (0, p, &p);
6101 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6102 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6103 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6107 if (jinfo->has_try_block_holes) {
6108 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6109 for (i = 0; i < table->num_holes; ++i) {
6110 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6111 encode_value (hole->clause, p, &p);
6112 encode_value (hole->length, p, &p);
6113 encode_value (hole->offset, p, &p);
6117 if (jinfo->has_arch_eh_info) {
6118 MonoArchEHJitInfo *eh_info;
6120 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6121 encode_value (eh_info->stack_size, p, &p);
6122 encode_value (eh_info->epilog_size, p, &p);
6125 if (jinfo->has_generic_jit_info) {
6126 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6127 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6131 encode_value (gi->nlocs, p, &p);
6133 for (i = 0; i < gi->nlocs; ++i) {
6134 MonoDwarfLocListEntry *entry = &gi->locations [i];
6136 encode_value (entry->is_reg ? 1 : 0, p, &p);
6137 encode_value (entry->reg, p, &p);
6139 encode_value (entry->offset, p, &p);
6141 g_assert (entry->from == 0);
6143 encode_value (entry->from, p, &p);
6144 encode_value (entry->to, p, &p);
6147 if (!cfg->compile_llvm) {
6148 encode_value (gi->has_this ? 1 : 0, p, &p);
6149 encode_value (gi->this_reg, p, &p);
6150 encode_value (gi->this_offset, p, &p);
6155 * Need to encode jinfo->method too, since it is not equal to 'method'
6156 * when using generic sharing.
6158 buf2 = (guint8 *)g_malloc (4096);
6160 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6162 g_assert (len < 4096);
6163 encode_value (len, p, &p);
6164 memcpy (p, buf2, len);
6168 if (gsctx && gsctx->is_gsharedvt) {
6169 encode_value (1, p, &p);
6171 encode_value (0, p, &p);
6175 if (seq_points_size)
6176 p += mono_seq_point_info_write (seq_points, p);
6178 g_assert (debug_info_size < buf_size);
6180 encode_value (debug_info_size, p, &p);
6181 if (debug_info_size) {
6182 memcpy (p, debug_info, debug_info_size);
6183 p += debug_info_size;
6184 g_free (debug_info);
6189 encode_value (cfg->gc_map_size, p, &p);
6190 /* The GC map requires 4 bytes of alignment */
6191 while ((gsize)p % 4)
6193 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6194 p += cfg->gc_map_size;
6197 acfg->stats.ex_info_size += p - buf;
6199 g_assert (p - buf < buf_size);
6202 /* The GC Map requires 4 byte alignment */
6203 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6208 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6211 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6213 int i, buf_size, res;
6214 gboolean no_special_static, cant_encode;
6215 gpointer iter = NULL;
6218 mono_error_cleanup (&error);
6222 p = buf = (guint8 *)g_malloc (buf_size);
6224 /* Mark as unusable */
6225 encode_value (-1, p, &p);
6227 res = add_to_blob (acfg, buf, p - buf);
6233 buf_size = 10240 + (klass->vtable_size * 16);
6234 p = buf = (guint8 *)g_malloc (buf_size);
6238 mono_class_init (klass);
6240 mono_class_get_nested_types (klass, &iter);
6241 g_assert (klass->nested_classes_inited);
6243 mono_class_setup_vtable (klass);
6246 * Emit all the information which is required for creating vtables so
6247 * the runtime does not need to create the MonoMethod structures which
6248 * take up a lot of space.
6251 no_special_static = !mono_class_has_special_static_fields (klass);
6253 /* Check whenever we have enough info to encode the vtable */
6254 cant_encode = FALSE;
6255 for (i = 0; i < klass->vtable_size; ++i) {
6256 MonoMethod *cm = klass->vtable [i];
6258 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6262 mono_class_has_finalizer (klass);
6264 if (klass->generic_container || cant_encode) {
6265 encode_value (-1, p, &p);
6267 encode_value (klass->vtable_size, p, &p);
6268 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);
6269 if (klass->has_cctor)
6270 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6271 if (klass->has_finalize)
6272 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6274 encode_value (klass->instance_size, p, &p);
6275 encode_value (mono_class_data_size (klass), p, &p);
6276 encode_value (klass->packing_size, p, &p);
6277 encode_value (klass->min_align, p, &p);
6279 for (i = 0; i < klass->vtable_size; ++i) {
6280 MonoMethod *cm = klass->vtable [i];
6283 encode_method_ref (acfg, cm, p, &p);
6285 encode_value (0, p, &p);
6289 acfg->stats.class_info_size += p - buf;
6291 g_assert (p - buf < buf_size);
6292 res = add_to_blob (acfg, buf, p - buf);
6299 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6301 char *debug_sym = NULL;
6304 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6305 /* Need to add a prefix to create unique symbols */
6306 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6308 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6309 prefix = mangle_symbol_alloc ("plt_");
6311 prefix = g_strdup ("plt_");
6316 case MONO_PATCH_INFO_METHOD:
6317 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6319 case MONO_PATCH_INFO_INTERNAL_METHOD:
6320 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6322 case MONO_PATCH_INFO_RGCTX_FETCH:
6323 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6325 case MONO_PATCH_INFO_ICALL_ADDR:
6326 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6327 char *s = get_debug_sym (ji->data.method, "", cache);
6329 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6333 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6334 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6342 return sanitize_symbol (acfg, debug_sym);
6346 * Calls made from AOTed code are routed through a table of jumps similar to the
6347 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6348 * control to the AOT runtime through a trampoline.
6351 emit_plt (MonoAotCompile *acfg)
6355 if (acfg->aot_opts.llvm_only) {
6356 g_assert (acfg->plt_offset == 1);
6362 emit_section_change (acfg, ".text", 0);
6363 emit_alignment_code (acfg, 16);
6364 emit_info_symbol (acfg, "plt");
6365 emit_label (acfg, acfg->plt_symbol);
6367 for (i = 0; i < acfg->plt_offset; ++i) {
6368 char *debug_sym = NULL;
6369 MonoPltEntry *plt_entry = NULL;
6373 * The first plt entry is unused.
6377 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6379 debug_sym = plt_entry->debug_sym;
6381 if (acfg->thumb_mixed && !plt_entry->jit_used)
6382 /* Emit only a thumb version */
6385 /* Skip plt entries not actually called */
6386 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6389 if (acfg->llvm && !acfg->thumb_mixed) {
6390 emit_label (acfg, plt_entry->llvm_symbol);
6392 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6393 #if defined(TARGET_MACH)
6394 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6400 if (acfg->need_no_dead_strip) {
6401 emit_unset_mode (acfg);
6402 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6404 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6405 emit_label (acfg, debug_sym);
6408 emit_label (acfg, plt_entry->symbol);
6410 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6413 emit_symbol_size (acfg, debug_sym, ".");
6416 if (acfg->thumb_mixed) {
6417 /* Make sure the ARM symbols don't alias the thumb ones */
6418 emit_zero_bytes (acfg, 16);
6421 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6424 for (i = 0; i < acfg->plt_offset; ++i) {
6425 char *debug_sym = NULL;
6426 MonoPltEntry *plt_entry = NULL;
6431 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6433 /* Skip plt entries not actually called by LLVM code */
6434 if (!plt_entry->llvm_used)
6437 if (acfg->aot_opts.write_symbols) {
6438 if (plt_entry->debug_sym)
6439 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6443 #if defined(TARGET_MACH)
6444 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6445 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6447 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6448 emit_label (acfg, debug_sym);
6450 fprintf (acfg->fp, "\n.thumb_func\n");
6452 emit_label (acfg, plt_entry->llvm_symbol);
6455 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6457 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6460 emit_symbol_size (acfg, debug_sym, ".");
6466 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6468 emit_info_symbol (acfg, "plt_end");
6472 * emit_trampoline_full:
6474 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6475 * create_jit_info_for_trampoline ().
6477 static G_GNUC_UNUSED void
6478 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6480 char start_symbol [MAX_SYMBOL_SIZE];
6481 char end_symbol [MAX_SYMBOL_SIZE];
6482 char symbol [MAX_SYMBOL_SIZE];
6483 guint32 buf_size, info_offset;
6484 MonoJumpInfo *patch_info;
6497 code_size = info->code_size;
6499 unwind_ops = info->unwind_ops;
6503 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6505 emit_section_change (acfg, ".text", 0);
6506 emit_global (acfg, start_symbol, TRUE);
6507 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6508 emit_label (acfg, start_symbol);
6510 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6511 emit_label (acfg, symbol);
6514 * The code should access everything through the GOT, so we pass
6517 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6519 emit_symbol_size (acfg, start_symbol, ".");
6522 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6523 emit_label (acfg, end_symbol);
6528 /* Sort relocations */
6529 patches = g_ptr_array_new ();
6530 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6531 if (patch_info->type != MONO_PATCH_INFO_NONE)
6532 g_ptr_array_add (patches, patch_info);
6533 g_ptr_array_sort (patches, compare_patches);
6535 buf_size = patches->len * 128 + 128;
6536 buf = (guint8 *)g_malloc (buf_size);
6539 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6540 g_assert (p - buf < buf_size);
6541 g_ptr_array_free (patches, TRUE);
6543 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6545 info_offset = add_to_blob (acfg, buf, p - buf);
6547 emit_section_change (acfg, RODATA_SECT, 0);
6548 emit_global (acfg, symbol, FALSE);
6549 emit_label (acfg, symbol);
6551 emit_int32 (acfg, info_offset);
6555 guint32 encoded_len;
6559 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6561 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6562 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6565 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6566 emit_int32 (acfg, uw_offset);
6569 /* Emit debug info */
6571 char symbol2 [MAX_SYMBOL_SIZE];
6573 sprintf (symbol, "%s", name);
6574 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6577 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6583 static G_GNUC_UNUSED void
6584 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6586 emit_trampoline_full (acfg, got_offset, info, TRUE);
6590 emit_trampolines (MonoAotCompile *acfg)
6592 char symbol [MAX_SYMBOL_SIZE];
6593 char end_symbol [MAX_SYMBOL_SIZE];
6594 int i, tramp_got_offset;
6596 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6600 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6603 g_assert (acfg->image->assembly);
6605 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6606 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6607 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6608 MonoTrampInfo *info;
6611 * Emit the generic trampolines.
6613 * We could save some code by treating the generic trampolines as a wrapper
6614 * method, but that approach has its own complexities, so we choose the simpler
6617 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6618 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6619 #ifdef DISABLE_REMOTING
6620 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6623 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6624 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6627 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6628 emit_trampoline (acfg, acfg->got_offset, info);
6631 /* Emit the exception related code pieces */
6632 mono_arch_get_restore_context (&info, TRUE);
6633 emit_trampoline (acfg, acfg->got_offset, info);
6634 mono_arch_get_call_filter (&info, TRUE);
6635 emit_trampoline (acfg, acfg->got_offset, info);
6636 mono_arch_get_throw_exception (&info, TRUE);
6637 emit_trampoline (acfg, acfg->got_offset, info);
6638 mono_arch_get_rethrow_exception (&info, TRUE);
6639 emit_trampoline (acfg, acfg->got_offset, info);
6640 mono_arch_get_throw_corlib_exception (&info, TRUE);
6641 emit_trampoline (acfg, acfg->got_offset, info);
6643 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6644 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6645 emit_trampoline (acfg, acfg->got_offset, info);
6646 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6647 emit_trampoline (acfg, acfg->got_offset, info);
6650 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6651 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6653 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6655 /* Create a separate out trampoline for more information in stack traces */
6656 info->name = g_strdup ("gsharedvt_out_trampoline");
6657 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6661 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6663 GSList *l = mono_arch_get_trampolines (TRUE);
6666 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6668 emit_trampoline (acfg, acfg->got_offset, info);
6674 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6677 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6678 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6679 emit_trampoline (acfg, acfg->got_offset, info);
6682 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6683 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6684 emit_trampoline (acfg, acfg->got_offset, info);
6688 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6689 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6690 emit_trampoline (acfg, acfg->got_offset, info);
6696 /* delegate_invoke_impl trampolines */
6697 l = mono_arch_get_delegate_invoke_impls ();
6699 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6701 emit_trampoline (acfg, acfg->got_offset, info);
6706 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6707 mono_arch_create_handler_block_trampoline (&info, TRUE);
6708 emit_trampoline (acfg, acfg->got_offset, info);
6711 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6713 /* Emit trampolines which are numerous */
6716 * These include the following:
6717 * - specific trampolines
6718 * - static rgctx invoke trampolines
6720 * These trampolines have the same code, they are parameterized by GOT
6722 * They are defined in this file, in the arch_... routines instead of
6723 * in tramp-<ARCH>.c, since it is easier to do it this way.
6727 * When running in aot-only mode, we can't create specific trampolines at
6728 * runtime, so we create a few, and save them in the AOT file.
6729 * Normal trampolines embed their argument as a literal inside the
6730 * trampoline code, we can't do that here, so instead we embed an offset
6731 * which needs to be added to the trampoline address to get the address of
6732 * the GOT slot which contains the argument value.
6733 * The generated trampolines jump to the generic trampolines using another
6734 * GOT slot, which will be setup by the AOT loader to point to the
6735 * generic trampoline code of the given type.
6739 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6743 emit_section_change (acfg, ".text", 0);
6745 tramp_got_offset = acfg->got_offset;
6747 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6749 case MONO_AOT_TRAMP_SPECIFIC:
6750 sprintf (symbol, "specific_trampolines");
6752 case MONO_AOT_TRAMP_STATIC_RGCTX:
6753 sprintf (symbol, "static_rgctx_trampolines");
6755 case MONO_AOT_TRAMP_IMT:
6756 sprintf (symbol, "imt_trampolines");
6758 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6759 sprintf (symbol, "gsharedvt_arg_trampolines");
6762 g_assert_not_reached ();
6765 sprintf (end_symbol, "%s_e", symbol);
6767 if (acfg->aot_opts.write_symbols)
6768 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6770 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6771 emit_info_symbol (acfg, symbol);
6773 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6775 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6779 case MONO_AOT_TRAMP_SPECIFIC:
6780 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6781 tramp_got_offset += 2;
6783 case MONO_AOT_TRAMP_STATIC_RGCTX:
6784 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6785 tramp_got_offset += 2;
6787 case MONO_AOT_TRAMP_IMT:
6788 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6789 tramp_got_offset += 1;
6791 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6792 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6793 tramp_got_offset += 2;
6796 g_assert_not_reached ();
6798 if (!acfg->trampoline_size [ntype]) {
6799 g_assert (tramp_size);
6800 acfg->trampoline_size [ntype] = tramp_size;
6804 emit_label (acfg, end_symbol);
6805 emit_int32 (acfg, 0);
6808 arch_emit_specific_trampoline_pages (acfg);
6810 /* Reserve some entries at the end of the GOT for our use */
6811 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6814 acfg->got_offset += acfg->num_trampoline_got_entries;
6818 str_begins_with (const char *str1, const char *str2)
6820 int len = strlen (str2);
6821 return strncmp (str1, str2, len) == 0;
6825 mono_aot_readonly_field_override (MonoClassField *field)
6828 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6829 char *p = rdv->name;
6831 len = strlen (field->parent->name_space);
6832 if (strncmp (p, field->parent->name_space, len))
6837 len = strlen (field->parent->name);
6838 if (strncmp (p, field->parent->name, len))
6843 if (strcmp (p, field->name))
6845 switch (rdv->type) {
6847 return &rdv->value.i1;
6849 return &rdv->value.i2;
6851 return &rdv->value.i4;
6860 add_readonly_value (MonoAotOptions *opts, const char *val)
6865 /* the format of val is:
6866 * namespace.typename.fieldname=type/value
6867 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6869 fval = strrchr (val, '/');
6871 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6874 tval = strrchr (val, '=');
6876 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6879 rdv = g_new0 (ReadOnlyValue, 1);
6880 rdv->name = (char *)g_malloc0 (tval - val + 1);
6881 memcpy (rdv->name, val, tval - val);
6884 if (strncmp (tval, "i1", 2) == 0) {
6885 rdv->value.i1 = atoi (fval);
6886 rdv->type = MONO_TYPE_I1;
6887 } else if (strncmp (tval, "i2", 2) == 0) {
6888 rdv->value.i2 = atoi (fval);
6889 rdv->type = MONO_TYPE_I2;
6890 } else if (strncmp (tval, "i4", 2) == 0) {
6891 rdv->value.i4 = atoi (fval);
6892 rdv->type = MONO_TYPE_I4;
6894 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6897 rdv->next = readonly_values;
6898 readonly_values = rdv;
6902 clean_path (gchar * path)
6907 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6910 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6917 wrap_path (gchar * path)
6923 // If the string contains no spaces, just return the original string.
6924 if (strstr (path, " ") == NULL)
6927 // If the string is already wrapped in quotes, return it.
6928 len = strlen (path);
6929 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6932 // If the string contains spaces, then wrap it in quotes.
6933 gchar *clean = g_strdup_printf ("\"%s\"", path);
6938 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
6940 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
6942 ptrdiff_t len = end-start;
6944 g_ptr_array_add (args, g_strndup (start, len));
6948 mono_aot_split_options (const char *aot_options)
6950 enum MonoAotOptionState {
6951 MONO_AOT_OPTION_STATE_DEFAULT,
6952 MONO_AOT_OPTION_STATE_STRING,
6953 MONO_AOT_OPTION_STATE_ESCAPE,
6956 GPtrArray *args = g_ptr_array_new ();
6957 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6958 gchar const *opt_start = aot_options;
6959 gboolean end_of_string = FALSE;
6962 g_return_val_if_fail (aot_options != NULL, NULL);
6964 while ((cur = *aot_options) != '\0') {
6965 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6970 // If we find a quote, then if we're in the default case then
6971 // it means we've found the start of a string, if not then it
6972 // means we've found the end of the string and should switch
6973 // back to the default case.
6975 case MONO_AOT_OPTION_STATE_DEFAULT:
6976 state = MONO_AOT_OPTION_STATE_STRING;
6978 case MONO_AOT_OPTION_STATE_STRING:
6979 state = MONO_AOT_OPTION_STATE_DEFAULT;
6981 case MONO_AOT_OPTION_STATE_ESCAPE:
6982 g_assert_not_reached ();
6987 // If we've found an escaping operator, then this means we
6988 // should not process the next character if inside a string.
6989 if (state == MONO_AOT_OPTION_STATE_STRING)
6990 state = MONO_AOT_OPTION_STATE_ESCAPE;
6993 // If we're in the default state then this means we've found
6994 // an option, store it for later processing.
6995 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7003 // If the next character is end of string, then process the last option.
7004 if (*(aot_options) == '\0') {
7005 end_of_string = TRUE;
7011 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7012 opt_start = ++aot_options;
7015 goto restart; // Check for null and continue loop
7022 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7026 args = mono_aot_split_options (aot_options ? aot_options : "");
7027 for (int i = 0; i < args->len; ++i) {
7028 const char *arg = (const char *)g_ptr_array_index (args, i);
7030 if (str_begins_with (arg, "outfile=")) {
7031 opts->outfile = g_strdup (arg + strlen ("outfile="));
7032 } else if (str_begins_with (arg, "llvm-outfile=")) {
7033 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7034 } else if (str_begins_with (arg, "temp-path=")) {
7035 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7036 } else if (str_begins_with (arg, "save-temps")) {
7037 opts->save_temps = TRUE;
7038 } else if (str_begins_with (arg, "keep-temps")) {
7039 opts->save_temps = TRUE;
7040 } else if (str_begins_with (arg, "write-symbols")) {
7041 opts->write_symbols = TRUE;
7042 } else if (str_begins_with (arg, "no-write-symbols")) {
7043 opts->write_symbols = FALSE;
7044 } else if (str_begins_with (arg, "metadata-only")) {
7045 opts->metadata_only = TRUE;
7046 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7047 opts->bind_to_runtime_version = TRUE;
7048 } else if (str_begins_with (arg, "full")) {
7049 opts->mode = MONO_AOT_MODE_FULL;
7050 } else if (str_begins_with (arg, "hybrid")) {
7051 opts->mode = MONO_AOT_MODE_HYBRID;
7052 } else if (str_begins_with (arg, "threads=")) {
7053 opts->nthreads = atoi (arg + strlen ("threads="));
7054 } else if (str_begins_with (arg, "static")) {
7055 opts->static_link = TRUE;
7056 opts->no_dlsym = TRUE;
7057 } else if (str_begins_with (arg, "asmonly")) {
7058 opts->asm_only = TRUE;
7059 } else if (str_begins_with (arg, "asmwriter")) {
7060 opts->asm_writer = TRUE;
7061 } else if (str_begins_with (arg, "nodebug")) {
7062 opts->nodebug = TRUE;
7063 } else if (str_begins_with (arg, "dwarfdebug")) {
7064 opts->dwarf_debug = TRUE;
7065 } else if (str_begins_with (arg, "nopagetrampolines")) {
7066 opts->use_trampolines_page = FALSE;
7067 } else if (str_begins_with (arg, "ntrampolines=")) {
7068 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7069 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7070 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7071 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7072 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7073 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7074 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7075 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7076 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7077 } else if (str_begins_with (arg, "tool-prefix=")) {
7078 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7079 } else if (str_begins_with (arg, "ld-flags=")) {
7080 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7081 } else if (str_begins_with (arg, "soft-debug")) {
7082 opts->soft_debug = TRUE;
7083 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7084 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7085 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7086 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7087 } else if (str_begins_with (arg, "msym-dir=")) {
7088 debug_options.no_seq_points_compact_data = FALSE;
7089 opts->gen_msym_dir = TRUE;
7090 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7091 } else if (str_begins_with (arg, "direct-pinvoke")) {
7092 opts->direct_pinvoke = TRUE;
7093 } else if (str_begins_with (arg, "direct-icalls")) {
7094 opts->direct_icalls = TRUE;
7095 } else if (str_begins_with (arg, "no-direct-calls")) {
7096 opts->no_direct_calls = TRUE;
7097 } else if (str_begins_with (arg, "print-skipped")) {
7098 opts->print_skipped_methods = TRUE;
7099 } else if (str_begins_with (arg, "stats")) {
7101 } else if (str_begins_with (arg, "no-instances")) {
7102 opts->no_instances = TRUE;
7103 } else if (str_begins_with (arg, "log-generics")) {
7104 opts->log_generics = TRUE;
7105 } else if (str_begins_with (arg, "log-instances=")) {
7106 opts->log_instances = TRUE;
7107 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7108 } else if (str_begins_with (arg, "log-instances")) {
7109 opts->log_instances = TRUE;
7110 } else if (str_begins_with (arg, "internal-logfile=")) {
7111 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7112 } else if (str_begins_with (arg, "mtriple=")) {
7113 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7114 } else if (str_begins_with (arg, "llvm-path=")) {
7115 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7116 } else if (!strcmp (arg, "llvm")) {
7118 } else if (str_begins_with (arg, "readonly-value=")) {
7119 add_readonly_value (opts, arg + strlen ("readonly-value="));
7120 } else if (str_begins_with (arg, "info")) {
7121 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7123 } else if (str_begins_with (arg, "gc-maps")) {
7124 mini_gc_enable_gc_maps_for_aot ();
7125 } else if (str_begins_with (arg, "dump")) {
7126 opts->dump_json = TRUE;
7127 } else if (str_begins_with (arg, "llvmonly")) {
7128 opts->mode = MONO_AOT_MODE_FULL;
7130 opts->llvm_only = TRUE;
7131 } else if (str_begins_with (arg, "data-outfile=")) {
7132 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7133 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7134 printf ("Supported options for --aot:\n");
7135 printf (" outfile=\n");
7136 printf (" llvm-outfile=\n");
7137 printf (" llvm-path=\n");
7138 printf (" temp-path=\n");
7139 printf (" save-temps\n");
7140 printf (" keep-temps\n");
7141 printf (" write-symbols\n");
7142 printf (" metadata-only\n");
7143 printf (" bind-to-runtime-version\n");
7145 printf (" threads=\n");
7146 printf (" static\n");
7147 printf (" asmonly\n");
7148 printf (" asmwriter\n");
7149 printf (" nodebug\n");
7150 printf (" dwarfdebug\n");
7151 printf (" ntrampolines=\n");
7152 printf (" nrgctx-trampolines=\n");
7153 printf (" nimt-trampolines=\n");
7154 printf (" ngsharedvt-trampolines=\n");
7155 printf (" tool-prefix=\n");
7156 printf (" readonly-value=\n");
7157 printf (" soft-debug\n");
7158 printf (" msym-dir=\n");
7159 printf (" gc-maps\n");
7160 printf (" print-skipped\n");
7161 printf (" no-instances\n");
7162 printf (" stats\n");
7165 printf (" help/?\n");
7168 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7172 g_free ((gpointer) arg);
7175 if (opts->use_trampolines_page) {
7176 opts->ntrampolines = 0;
7177 opts->nrgctx_trampolines = 0;
7178 opts->nimt_trampolines = 0;
7179 opts->ngsharedvt_arg_trampolines = 0;
7182 g_ptr_array_free (args, /*free_seg=*/TRUE);
7186 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7188 MonoMethod *method = (MonoMethod*)key;
7189 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7190 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7191 MonoJumpInfoToken *new_ji;
7193 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7194 new_ji->image = ji->image;
7195 new_ji->token = ji->token;
7196 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7200 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7202 if (klass->type_token)
7204 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7207 return can_encode_class (acfg, klass->element_class);
7212 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7214 if (method->wrapper_type) {
7215 switch (method->wrapper_type) {
7216 case MONO_WRAPPER_NONE:
7217 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7218 case MONO_WRAPPER_XDOMAIN_INVOKE:
7219 case MONO_WRAPPER_STFLD:
7220 case MONO_WRAPPER_LDFLD:
7221 case MONO_WRAPPER_LDFLDA:
7222 case MONO_WRAPPER_STELEMREF:
7223 case MONO_WRAPPER_ISINST:
7224 case MONO_WRAPPER_PROXY_ISINST:
7225 case MONO_WRAPPER_ALLOC:
7226 case MONO_WRAPPER_REMOTING_INVOKE:
7227 case MONO_WRAPPER_UNKNOWN:
7228 case MONO_WRAPPER_WRITE_BARRIER:
7229 case MONO_WRAPPER_DELEGATE_INVOKE:
7230 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7231 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7232 case MONO_WRAPPER_SYNCHRONIZED:
7234 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7235 case MONO_WRAPPER_CASTCLASS: {
7236 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7245 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7249 if (!method->token) {
7250 /* The method is part of a constructed type like Int[,].Set (). */
7251 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7252 if (method->klass->rank)
7262 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7264 switch (patch_info->type) {
7265 case MONO_PATCH_INFO_METHOD:
7266 case MONO_PATCH_INFO_METHODCONST:
7267 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7268 MonoMethod *method = patch_info->data.method;
7270 return can_encode_method (acfg, method);
7272 case MONO_PATCH_INFO_VTABLE:
7273 case MONO_PATCH_INFO_CLASS:
7274 case MONO_PATCH_INFO_IID:
7275 case MONO_PATCH_INFO_ADJUSTED_IID:
7276 if (!can_encode_class (acfg, patch_info->data.klass)) {
7277 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7281 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7282 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7283 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7288 case MONO_PATCH_INFO_RGCTX_FETCH:
7289 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7290 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7292 if (!can_encode_method (acfg, entry->method))
7294 if (!can_encode_patch (acfg, entry->data))
7306 is_concrete_type (MonoType *t)
7311 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7313 if (t->type == MONO_TYPE_GENERICINST) {
7314 MonoGenericContext *orig_ctx;
7315 MonoGenericInst *inst;
7318 if (!MONO_TYPE_ISSTRUCT (t))
7320 klass = mono_class_from_mono_type (t);
7321 orig_ctx = &klass->generic_class->context;
7323 inst = orig_ctx->class_inst;
7325 for (i = 0; i < inst->type_argc; ++i) {
7326 arg = mini_get_underlying_type (inst->type_argv [i]);
7327 if (!is_concrete_type (arg))
7331 inst = orig_ctx->method_inst;
7333 for (i = 0; i < inst->type_argc; ++i) {
7334 arg = mini_get_underlying_type (inst->type_argv [i]);
7335 if (!is_concrete_type (arg))
7343 /* LOCKING: Assumes the loader lock is held */
7345 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7347 MonoMethod *wrapper;
7348 gboolean concrete = TRUE;
7349 gboolean add_in = gsharedvt_in;
7350 gboolean add_out = gsharedvt_out;
7352 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7354 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7357 if (!add_in && !add_out)
7360 if (mini_is_gsharedvt_variable_signature (sig))
7364 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7366 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7368 if (!sig->has_type_parameters) {
7369 //printf ("%s\n", mono_signature_full_name (sig));
7372 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7373 add_extra_method (acfg, wrapper);
7375 if (gsharedvt_out) {
7376 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7377 add_extra_method (acfg, wrapper);
7380 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7381 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7384 //printf ("%s\n", mono_signature_full_name (sig));
7386 copy->ret = mini_get_underlying_type (sig->ret);
7387 if (!is_concrete_type (copy->ret))
7389 for (i = 0; i < sig->param_count; ++i) {
7390 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7391 if (!is_concrete_type (copy->params [i]))
7395 copy->has_type_parameters = 0;
7398 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7399 add_extra_method (acfg, wrapper);
7402 if (gsharedvt_out) {
7403 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7404 add_extra_method (acfg, wrapper);
7407 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7415 * AOT compile a given method.
7416 * This function might be called by multiple threads, so it must be thread-safe.
7419 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7422 MonoJumpInfo *patch_info;
7425 MonoMethod *wrapped;
7429 if (acfg->aot_opts.metadata_only)
7432 mono_acfg_lock (acfg);
7433 index = get_method_index (acfg, method);
7434 mono_acfg_unlock (acfg);
7436 /* fixme: maybe we can also precompile wrapper methods */
7437 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7438 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7439 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7440 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7444 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7447 wrapped = mono_marshal_method_from_wrapper (method);
7448 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7449 // FIXME: The wrapper should be generic too, but it is not
7452 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7455 InterlockedIncrement (&acfg->stats.mcount);
7458 if (method->is_generic || method->klass->generic_container) {
7459 InterlockedIncrement (&acfg->stats.genericcount);
7464 //acfg->aot_opts.print_skipped_methods = TRUE;
7467 * Since these methods are the only ones which are compiled with
7468 * AOT support, and they are not used by runtime startup/shutdown code,
7469 * the runtime will not see AOT methods during AOT compilation,so it
7470 * does not need to support them by creating a fake GOT etc.
7472 flags = JIT_FLAG_AOT;
7473 if (mono_aot_mode_is_full (&acfg->aot_opts))
7474 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7476 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7477 if (acfg->aot_opts.llvm_only)
7478 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7479 if (acfg->aot_opts.no_direct_calls)
7480 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7482 jit_timer = mono_time_track_start ();
7483 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7484 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7486 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7487 if (acfg->aot_opts.print_skipped_methods)
7488 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7489 InterlockedIncrement (&acfg->stats.genericcount);
7492 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7493 if (acfg->aot_opts.print_skipped_methods)
7494 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7495 /* Let the exception happen at runtime */
7499 if (cfg->disable_aot) {
7500 if (acfg->aot_opts.print_skipped_methods)
7501 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7502 InterlockedIncrement (&acfg->stats.ocount);
7505 cfg->method_index = index;
7507 /* Nullify patches which need no aot processing */
7508 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7509 switch (patch_info->type) {
7510 case MONO_PATCH_INFO_LABEL:
7511 case MONO_PATCH_INFO_BB:
7512 patch_info->type = MONO_PATCH_INFO_NONE;
7519 /* Collect method->token associations from the cfg */
7520 mono_acfg_lock (acfg);
7521 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7522 mono_acfg_unlock (acfg);
7523 g_hash_table_destroy (cfg->token_info_hash);
7524 cfg->token_info_hash = NULL;
7527 * Check for absolute addresses.
7530 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7531 switch (patch_info->type) {
7532 case MONO_PATCH_INFO_ABS:
7533 /* unable to handle this */
7542 if (acfg->aot_opts.print_skipped_methods)
7543 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7544 InterlockedIncrement (&acfg->stats.abscount);
7548 /* Lock for the rest of the code */
7549 mono_acfg_lock (acfg);
7552 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7553 else if (cfg->gshared)
7554 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7555 else if (cfg->method->wrapper_type)
7556 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7558 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7561 * Check for methods/klasses we can't encode.
7564 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7565 if (!can_encode_patch (acfg, patch_info))
7570 if (acfg->aot_opts.print_skipped_methods)
7571 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7572 acfg->stats.ocount++;
7573 mono_acfg_unlock (acfg);
7577 if (!cfg->compile_llvm)
7578 acfg->has_jitted_code = TRUE;
7580 if (method->is_inflated && acfg->aot_opts.log_instances) {
7581 if (acfg->instances_logfile)
7582 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7584 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7587 /* Adds generic instances referenced by this method */
7589 * The depth is used to avoid infinite loops when generic virtual recursion is
7592 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7593 if (!acfg->aot_opts.no_instances && depth < 32) {
7594 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7595 switch (patch_info->type) {
7596 case MONO_PATCH_INFO_RGCTX_FETCH:
7597 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7598 case MONO_PATCH_INFO_METHOD: {
7599 MonoMethod *m = NULL;
7601 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7602 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7604 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7605 m = e->data->data.method;
7607 m = patch_info->data.method;
7612 if (m->is_inflated) {
7613 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7614 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7615 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7616 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7617 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7618 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7620 add_extra_method_with_depth (acfg, m, depth + 1);
7621 add_types_from_method_header (acfg, m);
7624 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7626 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7627 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7629 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7630 add_extra_method_with_depth (acfg, m, depth + 1);
7634 case MONO_PATCH_INFO_VTABLE: {
7635 MonoClass *klass = patch_info->data.klass;
7637 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7638 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7641 case MONO_PATCH_INFO_SFLDA: {
7642 MonoClass *klass = patch_info->data.field->parent;
7644 /* The .cctor needs to run at runtime. */
7645 if (klass->generic_class && !mono_generic_context_is_sharable_full (&klass->generic_class->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7646 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7655 /* Determine whenever the method has GOT slots */
7656 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7657 switch (patch_info->type) {
7658 case MONO_PATCH_INFO_GOT_OFFSET:
7659 case MONO_PATCH_INFO_NONE:
7660 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7661 case MONO_PATCH_INFO_GC_NURSERY_START:
7662 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7664 case MONO_PATCH_INFO_IMAGE:
7665 /* The assembly is stored in GOT slot 0 */
7666 if (patch_info->data.image != acfg->image)
7667 cfg->has_got_slots = TRUE;
7670 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7671 cfg->has_got_slots = TRUE;
7676 if (!cfg->has_got_slots)
7677 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7679 /* Add gsharedvt wrappers for signatures used by the method */
7680 if (acfg->aot_opts.llvm_only) {
7683 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7684 /* These only need out wrappers */
7685 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7687 for (l = cfg->signatures; l; l = l->next) {
7688 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7690 /* These only need in wrappers */
7691 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7696 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7698 /* Make a copy of the patch info which is in the mempool */
7700 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7702 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7703 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7706 patches = new_patch_info;
7708 patches_end->next = new_patch_info;
7709 patches_end = new_patch_info;
7711 cfg->patch_info = patches;
7713 /* Make a copy of the unwind info */
7715 GSList *l, *unwind_ops;
7719 for (l = cfg->unwind_ops; l; l = l->next) {
7720 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7721 memcpy (op, l->data, sizeof (MonoUnwindOp));
7722 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7724 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7726 /* Make a copy of the argument/local info */
7729 MonoInst **args, **locals;
7730 MonoMethodSignature *sig;
7731 MonoMethodHeader *header;
7734 sig = mono_method_signature (method);
7735 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7736 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7737 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7738 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7742 header = mono_method_get_header_checked (method, &error);
7743 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7744 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7745 for (i = 0; i < header->num_locals; ++i) {
7746 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7747 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7749 mono_metadata_free_mh (header);
7750 cfg->locals = locals;
7753 /* Free some fields used by cfg to conserve memory */
7754 mono_empty_compile (cfg);
7756 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7758 while (index >= acfg->cfgs_size) {
7759 MonoCompile **new_cfgs;
7762 new_size = acfg->cfgs_size * 2;
7763 new_cfgs = g_new0 (MonoCompile*, new_size);
7764 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7765 g_free (acfg->cfgs);
7766 acfg->cfgs = new_cfgs;
7767 acfg->cfgs_size = new_size;
7769 acfg->cfgs [index] = cfg;
7771 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7773 mono_update_jit_stats (cfg);
7776 if (cfg->orig_method->wrapper_type)
7777 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7780 mono_acfg_unlock (acfg);
7782 InterlockedIncrement (&acfg->stats.ccount);
7786 compile_thread_main (gpointer user_data)
7788 MonoDomain *domain = ((MonoDomain **)user_data) [0];
7789 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [1];
7790 GPtrArray *methods = ((GPtrArray **)user_data) [2];
7794 MonoThread *thread = mono_thread_attach (domain);
7795 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7796 mono_error_assert_ok (&error);
7798 for (i = 0; i < methods->len; ++i)
7799 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7805 load_profile_files (MonoAotCompile *acfg)
7809 int file_index, res, method_index, i;
7812 GList *unordered, *l;
7817 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7819 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7824 infile = fopen (tmp, "r");
7827 printf ("Using profile data file '%s'\n", tmp);
7832 res = fscanf (infile, "%32s\n", ver);
7833 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7834 printf ("Profile file has wrong version or invalid.\n");
7841 MonoMethodDesc *desc;
7844 if (fgets (name, 1023, infile) == NULL)
7847 /* Kill the newline */
7848 if (strlen (name) > 0)
7849 name [strlen (name) - 1] = '\0';
7851 desc = mono_method_desc_new (name, TRUE);
7853 method = mono_method_desc_search_in_image (desc, acfg->image);
7855 if (method && mono_method_get_token (method)) {
7856 token = mono_method_get_token (method);
7857 method_index = mono_metadata_token_index (token) - 1;
7860 for (i = 0; i < acfg->method_order->len; ++i) {
7861 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7867 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7869 //printf ("No method found matching '%s'.\n", name);
7875 /* Add missing methods */
7877 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7879 for (i = 0; i < acfg->method_order->len; ++i) {
7880 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7886 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7888 unordered = g_list_reverse (unordered);
7889 for (l = unordered; l; l = l->next)
7890 g_ptr_array_add (acfg->method_order, l->data);
7893 /* Used by the LLVM backend */
7895 mono_aot_get_got_offset (MonoJumpInfo *ji)
7897 return get_got_offset (llvm_acfg, TRUE, ji);
7901 * mono_aot_is_shared_got_offset:
7903 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7904 * when the AOT image is loaded.
7907 mono_aot_is_shared_got_offset (int offset)
7909 return offset < llvm_acfg->nshared_got_entries;
7913 mono_aot_get_method_name (MonoCompile *cfg)
7915 if (llvm_acfg->aot_opts.static_link)
7916 /* Include the assembly name too to avoid duplicate symbol errors */
7917 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7919 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7923 * mono_aot_is_linkonce_method:
7925 * Return whenever METHOD should be emitted with linkonce linkage,
7926 * eliminating duplicate copies when compiling in static mode.
7929 mono_aot_is_linkonce_method (MonoMethod *method)
7935 // FIXME: Add more cases
7936 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7938 info = mono_marshal_get_wrapper_info (method);
7939 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7946 append_mangled_type (GString *s, MonoType *t)
7949 g_string_append_printf (s, "b");
7951 case MONO_TYPE_VOID:
7952 g_string_append_printf (s, "void_");
7955 g_string_append_printf (s, "i1");
7958 g_string_append_printf (s, "u1");
7961 g_string_append_printf (s, "i2");
7964 g_string_append_printf (s, "u2");
7967 g_string_append_printf (s, "i4");
7970 g_string_append_printf (s, "u4");
7973 g_string_append_printf (s, "i8");
7976 g_string_append_printf (s, "u8");
7979 g_string_append_printf (s, "ii");
7982 g_string_append_printf (s, "ui");
7985 g_string_append_printf (s, "fl");
7988 g_string_append_printf (s, "do");
7991 char *fullname = mono_type_full_name (t);
7997 * Have to create a mangled name which is:
8001 temp = g_string_new ("");
8002 len = strlen (fullname);
8003 for (i = 0; i < len; ++i) {
8004 char c = fullname [i];
8006 g_string_append_c (temp, c);
8007 } else if (c == '_') {
8008 g_string_append_c (temp, '_');
8009 g_string_append_c (temp, '_');
8011 g_string_append_c (temp, '_');
8012 g_string_append_printf (temp, "%x", (int)c);
8015 temps = g_string_free (temp, FALSE);
8016 /* Include the length to avoid different length type names aliasing each other */
8017 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8026 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8031 supported = append_mangled_type (s, sig->ret);
8035 g_string_append_printf (s, "this_");
8036 for (i = 0; i < sig->param_count; ++i) {
8037 supported = append_mangled_type (s, sig->params [i]);
8046 * mono_aot_get_mangled_method_name:
8048 * Return a unique mangled name for METHOD, or NULL.
8051 mono_aot_get_mangled_method_name (MonoMethod *method)
8057 // FIXME: Add more cases
8058 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8060 info = mono_marshal_get_wrapper_info (method);
8061 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8064 s = g_string_new ("");
8066 g_string_append_printf (s, "aot_method_w_");
8068 switch (info->subtype) {
8069 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8070 g_string_append_printf (s, "gsharedvt_in_");
8072 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8073 g_string_append_printf (s, "gsharedvt_out_");
8076 g_assert_not_reached ();
8080 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8082 g_string_free (s, TRUE);
8086 return g_string_free (s, FALSE);
8090 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8092 return is_direct_callable (llvm_acfg, NULL, patch_info);
8096 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8098 MonoPltEntry *plt_entry;
8100 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8101 plt_entry->llvm_used = FALSE;
8105 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8107 const char *sym = NULL;
8109 if (llvm_acfg->aot_opts.direct_icalls) {
8110 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8111 /* Call to a C function implementing a jit icall */
8112 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8113 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8114 MonoMethod *method = (MonoMethod *)data;
8115 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8116 sym = mono_lookup_icall_symbol (method);
8117 else if (llvm_acfg->aot_opts.direct_pinvoke)
8118 sym = get_pinvoke_import (llvm_acfg, method);
8121 return g_strdup (sym);
8127 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8129 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8130 MonoPltEntry *plt_entry;
8131 const char *sym = NULL;
8134 ji->data.target = data;
8136 if (!can_encode_patch (llvm_acfg, ji))
8139 if (llvm_acfg->aot_opts.direct_icalls) {
8140 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8141 /* Call to a C function implementing a jit icall */
8142 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8143 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8144 MonoMethod *method = (MonoMethod *)data;
8145 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8146 sym = mono_lookup_icall_symbol (method);
8149 return g_strdup (sym);
8152 plt_entry = get_plt_entry (llvm_acfg, ji);
8153 plt_entry->llvm_used = TRUE;
8155 #if defined(TARGET_MACH)
8156 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8158 return g_strdup_printf (plt_entry->llvm_symbol);
8163 mono_aot_get_method_index (MonoMethod *method)
8165 g_assert (llvm_acfg);
8166 return get_method_index (llvm_acfg, method);
8170 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8174 mono_acfg_lock (llvm_acfg);
8175 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8176 mono_acfg_unlock (llvm_acfg);
8182 execute_system (const char * command)
8187 // We need an extra set of quotes around the whole command to properly handle commands
8188 // with spaces since internally the command is called through "cmd /c.
8189 command = g_strdup_printf ("\"%s\"", command);
8191 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8192 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8193 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8194 status = _wsystem (wstr);
8198 #elif defined (HAVE_SYSTEM)
8199 status = system (command);
8201 g_assert_not_reached ();
8212 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8216 emit_llvm_file (MonoAotCompile *acfg)
8218 char *command, *opts, *tempbc, *optbc, *output_fname;
8220 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8221 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8222 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8224 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8225 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8228 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8231 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8232 * a lot of time, and doesn't seem to save much space.
8233 * The following optimizations cannot be enabled:
8235 * - 'jump-threading' changes our blockaddress references to int constants.
8236 * - 'basiccg' fails because it contains:
8237 * if (CS && !isa<IntrinsicInst>(II)) {
8238 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8239 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8240 * The opt list below was produced by taking the output of:
8241 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8242 * then removing tailcallelim + the global opts.
8243 * strip-dead-prototypes deletes unused intrinsics definitions.
8245 /* The dse pass is disabled because of #13734 and #17616 */
8247 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8248 * // If we have no DataLayout information around, then the size of the store
8249 * // is inferrable from the pointee type. If they are the same type, then
8250 * // we know that the store is safe.
8251 * if (AA.getDataLayout() == 0 &&
8252 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8253 * return OverwriteComplete;
8254 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8256 if (acfg->aot_opts.llvm_only)
8257 // FIXME: This doesn't work yet
8258 opts = g_strdup ("");
8260 #if LLVM_API_VERSION > 100
8261 opts = g_strdup ("-O2 -disable-tail-calls");
8263 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");
8265 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8266 aot_printf (acfg, "Executing opt: %s\n", command);
8267 if (execute_system (command) != 0)
8271 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8272 /* Nothing else to do */
8275 if (acfg->aot_opts.llvm_only) {
8276 /* Use the stock clang from xcode */
8278 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);
8280 aot_printf (acfg, "Executing clang: %s\n", command);
8281 if (execute_system (command) != 0)
8286 if (!acfg->llc_args)
8287 acfg->llc_args = g_string_new ("");
8289 /* Verbose asm slows down llc greatly */
8290 g_string_append (acfg->llc_args, " -asm-verbose=false");
8292 if (acfg->aot_opts.mtriple)
8293 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8295 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8297 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8299 #if LLVM_API_VERSION > 100
8300 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8303 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8304 /* ios requires PIC code now */
8305 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8307 if (llvm_acfg->aot_opts.static_link)
8308 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8310 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8313 if (acfg->llvm_owriter) {
8314 /* Emit an object file directly */
8315 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8316 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8318 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8320 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8321 g_free (output_fname);
8323 aot_printf (acfg, "Executing llc: %s\n", command);
8325 if (execute_system (command) != 0)
8332 emit_code (MonoAotCompile *acfg)
8334 int oindex, i, prev_index;
8335 gboolean saved_unbox_info = FALSE;
8336 char symbol [MAX_SYMBOL_SIZE];
8338 if (acfg->aot_opts.llvm_only)
8341 #if defined(TARGET_POWERPC64)
8342 sprintf (symbol, ".Lgot_addr");
8343 emit_section_change (acfg, ".text", 0);
8344 emit_alignment (acfg, 8);
8345 emit_label (acfg, symbol);
8346 emit_pointer (acfg, acfg->got_symbol);
8350 * This global symbol is used to compute the address of each method using the
8351 * code_offsets array. It is also used to compute the memory ranges occupied by
8352 * AOT code, so it must be equal to the address of the first emitted method.
8354 emit_section_change (acfg, ".text", 0);
8355 emit_alignment_code (acfg, 8);
8356 emit_info_symbol (acfg, "jit_code_start");
8359 * Emit some padding so the local symbol for the first method doesn't have the
8360 * same address as 'methods'.
8362 emit_padding (acfg, 16);
8364 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8368 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8370 cfg = acfg->cfgs [i];
8375 method = cfg->orig_method;
8377 /* Emit unbox trampoline */
8378 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8379 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8381 emit_section_change (acfg, ".text", 0);
8383 if (acfg->thumb_mixed && cfg->compile_llvm) {
8384 emit_set_thumb_mode (acfg);
8385 fprintf (acfg->fp, "\n.thumb_func\n");
8388 emit_label (acfg, symbol);
8390 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8392 if (acfg->thumb_mixed && cfg->compile_llvm)
8393 emit_set_arm_mode (acfg);
8395 if (!saved_unbox_info) {
8396 char user_symbol [128];
8398 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8400 emit_label (acfg, "ut_end");
8402 unwind_ops = mono_unwind_get_cie_program ();
8403 save_unwind_info (acfg, user_symbol, unwind_ops);
8404 mono_free_unwind_info (unwind_ops);
8406 /* Save the unbox trampoline size */
8407 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8409 saved_unbox_info = TRUE;
8413 if (cfg->compile_llvm)
8414 acfg->stats.llvm_count ++;
8416 emit_method_code (acfg, cfg);
8419 emit_section_change (acfg, ".text", 0);
8420 emit_alignment_code (acfg, 8);
8421 emit_info_symbol (acfg, "jit_code_end");
8423 /* To distinguish it from the next symbol */
8424 emit_padding (acfg, 4);
8427 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8428 * from optimizing them away, since it doesn't see that code_offsets references them.
8429 * JITted methods don't need this since they are referenced using assembler local
8431 * FIXME: This is why write-symbols doesn't work on OSX ?
8433 if (acfg->llvm && acfg->need_no_dead_strip) {
8434 fprintf (acfg->fp, "\n");
8435 for (i = 0; i < acfg->nmethods; ++i) {
8436 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8437 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8442 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8443 * This is PIE code, and the linker can update it if needed.
8446 sprintf (symbol, "method_addresses");
8447 emit_section_change (acfg, ".text", 1);
8448 emit_alignment_code (acfg, 8);
8449 emit_info_symbol (acfg, symbol);
8450 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8451 emit_unset_mode (acfg);
8452 if (acfg->need_no_dead_strip)
8453 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8455 for (i = 0; i < acfg->nmethods; ++i) {
8456 #ifdef MONO_ARCH_AOT_SUPPORTED
8459 if (acfg->cfgs [i]) {
8460 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8462 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8467 sprintf (symbol, "method_addresses_end");
8468 emit_label (acfg, symbol);
8471 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8472 sprintf (symbol, "unbox_trampolines");
8473 emit_section_change (acfg, RODATA_SECT, 0);
8474 emit_alignment (acfg, 8);
8475 emit_info_symbol (acfg, symbol);
8478 for (i = 0; i < acfg->nmethods; ++i) {
8483 cfg = acfg->cfgs [i];
8487 method = cfg->orig_method;
8489 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8490 index = get_method_index (acfg, method);
8492 emit_int32 (acfg, index);
8493 /* Make sure the table is sorted by index */
8494 g_assert (index > prev_index);
8498 sprintf (symbol, "unbox_trampolines_end");
8499 emit_info_symbol (acfg, symbol);
8500 emit_int32 (acfg, 0);
8502 /* Emit a separate table with the trampoline addresses/offsets */
8503 sprintf (symbol, "unbox_trampoline_addresses");
8504 emit_section_change (acfg, ".text", 0);
8505 emit_alignment_code (acfg, 8);
8506 emit_info_symbol (acfg, symbol);
8508 for (i = 0; i < acfg->nmethods; ++i) {
8513 cfg = acfg->cfgs [i];
8517 method = cfg->orig_method;
8519 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8520 #ifdef MONO_ARCH_AOT_SUPPORTED
8523 index = get_method_index (acfg, method);
8524 sprintf (symbol, "ut_%d", index);
8526 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8530 emit_int32 (acfg, 0);
8534 emit_info (MonoAotCompile *acfg)
8539 offsets = g_new0 (gint32, acfg->nmethods);
8541 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8542 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8544 if (acfg->cfgs [i]) {
8545 emit_method_info (acfg, acfg->cfgs [i]);
8546 offsets [i] = acfg->cfgs [i]->method_info_offset;
8552 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8557 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8559 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8560 #define mix(a,b,c) { \
8561 a -= c; a ^= rot(c, 4); c += b; \
8562 b -= a; b ^= rot(a, 6); a += c; \
8563 c -= b; c ^= rot(b, 8); b += a; \
8564 a -= c; a ^= rot(c,16); c += b; \
8565 b -= a; b ^= rot(a,19); a += c; \
8566 c -= b; c ^= rot(b, 4); b += a; \
8568 #define final(a,b,c) { \
8569 c ^= b; c -= rot(b,14); \
8570 a ^= c; a -= rot(c,11); \
8571 b ^= a; b -= rot(a,25); \
8572 c ^= b; c -= rot(b,16); \
8573 a ^= c; a -= rot(c,4); \
8574 b ^= a; b -= rot(a,14); \
8575 c ^= b; c -= rot(b,24); \
8579 mono_aot_type_hash (MonoType *t1)
8581 guint hash = t1->type;
8583 hash |= t1->byref << 6; /* do not collide with t1->type values */
8585 case MONO_TYPE_VALUETYPE:
8586 case MONO_TYPE_CLASS:
8587 case MONO_TYPE_SZARRAY:
8588 /* check if the distribution is good enough */
8589 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8591 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8592 case MONO_TYPE_ARRAY:
8593 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8594 case MONO_TYPE_GENERICINST:
8595 return ((hash << 5) - hash) ^ 0;
8602 * mono_aot_method_hash:
8604 * Return a hash code for methods which only depends on metadata.
8607 mono_aot_method_hash (MonoMethod *method)
8609 MonoMethodSignature *sig;
8613 guint32 *hashes_start, *hashes;
8615 MonoGenericInst *class_ginst = NULL;
8616 MonoGenericInst *ginst = NULL;
8618 /* Similar to the hash in mono_method_get_imt_slot () */
8620 sig = mono_method_signature (method);
8622 if (method->klass->generic_class)
8623 class_ginst = method->klass->generic_class->context.class_inst;
8624 if (method->is_inflated)
8625 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8627 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8628 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8629 hashes = hashes_start;
8631 /* Some wrappers are assigned to random classes */
8632 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8633 klass = method->klass;
8635 klass = mono_defaults.object_class;
8637 if (!method->wrapper_type) {
8640 if (klass->generic_class)
8641 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8643 full_name = mono_type_full_name (&klass->byval_arg);
8645 hashes [0] = mono_metadata_str_hash (full_name);
8649 hashes [0] = mono_metadata_str_hash (klass->name);
8650 hashes [1] = mono_metadata_str_hash (klass->name_space);
8652 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8653 /* The method name includes a stringified pointer */
8656 hashes [2] = mono_metadata_str_hash (method->name);
8657 hashes [3] = method->wrapper_type;
8658 hashes [4] = mono_aot_type_hash (sig->ret);
8660 for (i = 0; i < sig->param_count; i++) {
8661 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8664 for (i = 0; i < class_ginst->type_argc; ++i)
8665 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8668 for (i = 0; i < ginst->type_argc; ++i)
8669 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8671 g_assert (hindex == hashes_count);
8673 /* Setup internal state */
8674 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8676 /* Handle most of the hashes */
8677 while (hashes_count > 3) {
8686 /* Handle the last 3 hashes (all the case statements fall through) */
8687 switch (hashes_count) {
8688 case 3 : c += hashes [2];
8689 case 2 : b += hashes [1];
8690 case 1 : a += hashes [0];
8692 case 0: /* nothing left to add */
8696 g_free (hashes_start);
8705 * mono_aot_get_array_helper_from_wrapper;
8707 * Get the helper method in Array called by an array wrapper method.
8710 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8714 MonoGenericContext ctx;
8715 MonoType *args [16];
8716 char *mname, *iname, *s, *s2, *helper_name = NULL;
8718 prefix = "System.Collections.Generic";
8719 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8720 s2 = strstr (s, "`1.");
8726 //printf ("X: %s %s\n", iname, mname);
8728 if (!strcmp (iname, "IList"))
8729 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8731 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8732 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8734 g_free (helper_name);
8737 if (m->is_generic) {
8739 memset (&ctx, 0, sizeof (ctx));
8740 args [0] = &method->klass->element_class->byval_arg;
8741 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8742 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8743 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8749 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8751 typedef struct HashEntry {
8752 guint32 key, value, index;
8753 struct HashEntry *next;
8757 * emit_extra_methods:
8759 * Emit methods which are not in the METHOD table, like wrappers.
8762 emit_extra_methods (MonoAotCompile *acfg)
8764 int i, table_size, buf_size;
8766 guint32 *info_offsets;
8769 HashEntry *entry, *new_entry;
8770 int nmethods, max_chain_length;
8773 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8775 /* Emit method info */
8777 for (i = 0; i < acfg->extra_methods->len; ++i) {
8778 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8779 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8785 p = buf = (guint8 *)g_malloc (buf_size);
8789 method = cfg->method_to_register;
8791 encode_method_ref (acfg, method, p, &p);
8793 g_assert ((p - buf) < buf_size);
8795 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8800 * Construct a chained hash table for mapping indexes in extra_method_info to
8803 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8804 table = g_ptr_array_sized_new (table_size);
8805 for (i = 0; i < table_size; ++i)
8806 g_ptr_array_add (table, NULL);
8807 chain_lengths = g_new0 (int, table_size);
8808 max_chain_length = 0;
8809 for (i = 0; i < acfg->extra_methods->len; ++i) {
8810 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8811 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8817 key = info_offsets [i];
8818 value = get_method_index (acfg, method);
8820 hash = mono_aot_method_hash (method) % table_size;
8821 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8823 chain_lengths [hash] ++;
8824 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8826 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8827 new_entry->key = key;
8828 new_entry->value = value;
8830 entry = (HashEntry *)g_ptr_array_index (table, hash);
8831 if (entry == NULL) {
8832 new_entry->index = hash;
8833 g_ptr_array_index (table, hash) = new_entry;
8836 entry = entry->next;
8838 entry->next = new_entry;
8839 new_entry->index = table->len;
8840 g_ptr_array_add (table, new_entry);
8843 g_free (chain_lengths);
8845 //printf ("MAX: %d\n", max_chain_length);
8847 buf_size = table->len * 12 + 4;
8848 p = buf = (guint8 *)g_malloc (buf_size);
8849 encode_int (table_size, p, &p);
8851 for (i = 0; i < table->len; ++i) {
8852 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8854 if (entry == NULL) {
8855 encode_int (0, p, &p);
8856 encode_int (0, p, &p);
8857 encode_int (0, p, &p);
8859 //g_assert (entry->key > 0);
8860 encode_int (entry->key, p, &p);
8861 encode_int (entry->value, p, &p);
8863 encode_int (entry->next->index, p, &p);
8865 encode_int (0, p, &p);
8868 g_assert (p - buf <= buf_size);
8870 /* Emit the table */
8871 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8876 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8877 * This is used by mono_aot_find_jit_info ().
8879 buf_size = acfg->extra_methods->len * 8 + 4;
8880 p = buf = (guint8 *)g_malloc (buf_size);
8881 encode_int (acfg->extra_methods->len, p, &p);
8882 for (i = 0; i < acfg->extra_methods->len; ++i) {
8883 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8885 encode_int (get_method_index (acfg, method), p, &p);
8886 encode_int (info_offsets [i], p, &p);
8888 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8891 g_free (info_offsets);
8892 g_ptr_array_free (table, TRUE);
8896 generate_aotid (guint8* aotid)
8898 gpointer rand_handle;
8902 rand_handle = mono_rand_init (NULL, 0);
8904 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8905 mono_error_assert_ok (&error);
8907 mono_rand_close (rand_handle);
8911 emit_exception_info (MonoAotCompile *acfg)
8915 SeqPointData sp_data;
8916 gboolean seq_points_to_file = FALSE;
8918 offsets = g_new0 (gint32, acfg->nmethods);
8919 for (i = 0; i < acfg->nmethods; ++i) {
8920 if (acfg->cfgs [i]) {
8921 MonoCompile *cfg = acfg->cfgs [i];
8923 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8924 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8925 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8926 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8927 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8929 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8930 offsets [i] = cfg->ex_info_offset;
8932 if (method_seq_points_to_file) {
8933 if (!seq_points_to_file) {
8934 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8935 seq_points_to_file = TRUE;
8937 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8944 if (seq_points_to_file) {
8945 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8946 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8947 char *image_basename = g_path_get_basename (acfg->image->name);
8948 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8949 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8951 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8952 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8956 mono_seq_point_data_write (&sp_data, aot_file_path);
8957 mono_seq_point_data_free (&sp_data);
8961 g_free (image_basename);
8963 g_free (aot_file_path);
8966 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8971 emit_unwind_info (MonoAotCompile *acfg)
8976 if (acfg->aot_opts.llvm_only) {
8977 g_assert (acfg->unwind_ops->len == 0);
8982 * The unwind info contains a lot of duplicates so we emit each unique
8983 * entry once, and only store the offset from the start of the table in the
8987 sprintf (symbol, "unwind_info");
8988 emit_section_change (acfg, RODATA_SECT, 1);
8989 emit_alignment (acfg, 8);
8990 emit_info_symbol (acfg, symbol);
8992 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8993 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8994 guint8 *unwind_info;
8995 guint32 unwind_info_len;
8999 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9002 encode_value (unwind_info_len, p, &p);
9003 emit_bytes (acfg, buf, p - buf);
9004 emit_bytes (acfg, unwind_info, unwind_info_len);
9006 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9011 emit_class_info (MonoAotCompile *acfg)
9016 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9017 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9018 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9020 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);
9024 typedef struct ClassNameTableEntry {
9025 guint32 token, index;
9026 struct ClassNameTableEntry *next;
9027 } ClassNameTableEntry;
9030 emit_class_name_table (MonoAotCompile *acfg)
9032 int i, table_size, buf_size;
9033 guint32 token, hash;
9038 ClassNameTableEntry *entry, *new_entry;
9041 * Construct a chained hash table for mapping class names to typedef tokens.
9043 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9044 table = g_ptr_array_sized_new (table_size);
9045 for (i = 0; i < table_size; ++i)
9046 g_ptr_array_add (table, NULL);
9047 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9049 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9050 klass = mono_class_get_checked (acfg->image, token, &error);
9052 mono_error_cleanup (&error);
9055 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9056 hash = mono_metadata_str_hash (full_name) % table_size;
9059 /* FIXME: Allocate from the mempool */
9060 new_entry = g_new0 (ClassNameTableEntry, 1);
9061 new_entry->token = token;
9063 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9064 if (entry == NULL) {
9065 new_entry->index = hash;
9066 g_ptr_array_index (table, hash) = new_entry;
9069 entry = entry->next;
9071 entry->next = new_entry;
9072 new_entry->index = table->len;
9073 g_ptr_array_add (table, new_entry);
9077 /* Emit the table */
9078 buf_size = table->len * 4 + 4;
9079 p = buf = (guint8 *)g_malloc0 (buf_size);
9081 /* FIXME: Optimize memory usage */
9082 g_assert (table_size < 65000);
9083 encode_int16 (table_size, p, &p);
9084 g_assert (table->len < 65000);
9085 for (i = 0; i < table->len; ++i) {
9086 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9088 if (entry == NULL) {
9089 encode_int16 (0, p, &p);
9090 encode_int16 (0, p, &p);
9092 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9094 encode_int16 (entry->next->index, p, &p);
9096 encode_int16 (0, p, &p);
9100 g_assert (p - buf <= buf_size);
9101 g_ptr_array_free (table, TRUE);
9103 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9109 emit_image_table (MonoAotCompile *acfg)
9115 * The image table is small but referenced in a lot of places.
9116 * So we emit it at once, and reference its elements by an index.
9118 buf_size = acfg->image_table->len * 28 + 4;
9119 for (i = 0; i < acfg->image_table->len; i++) {
9120 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9121 MonoAssemblyName *aname = &image->assembly->aname;
9123 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9126 buf = p = (guint8 *)g_malloc0 (buf_size);
9127 encode_int (acfg->image_table->len, p, &p);
9128 for (i = 0; i < acfg->image_table->len; i++) {
9129 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9130 MonoAssemblyName *aname = &image->assembly->aname;
9132 /* FIXME: Support multi-module assemblies */
9133 g_assert (image->assembly->image == image);
9135 encode_string (image->assembly_name, p, &p);
9136 encode_string (image->guid, p, &p);
9137 encode_string (aname->culture ? aname->culture : "", p, &p);
9138 encode_string ((const char*)aname->public_key_token, p, &p);
9140 while (GPOINTER_TO_UINT (p) % 8 != 0)
9143 encode_int (aname->flags, p, &p);
9144 encode_int (aname->major, p, &p);
9145 encode_int (aname->minor, p, &p);
9146 encode_int (aname->build, p, &p);
9147 encode_int (aname->revision, p, &p);
9149 g_assert (p - buf <= buf_size);
9151 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9157 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9159 int i, first_plt_got_patch = 0, buf_size;
9161 guint32 *got_info_offsets;
9162 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9164 /* Add the patches needed by the PLT to the GOT */
9166 acfg->plt_got_offset_base = acfg->got_offset;
9167 first_plt_got_patch = info->got_patches->len;
9168 for (i = 1; i < acfg->plt_offset; ++i) {
9169 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9171 g_ptr_array_add (info->got_patches, plt_entry->ji);
9173 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9176 acfg->got_offset += acfg->plt_offset;
9181 * - optimize offsets table.
9182 * - reduce number of exported symbols.
9183 * - emit info for a klass only once.
9184 * - determine when a method uses a GOT slot which is guaranteed to be already
9186 * - clean up and document the code.
9187 * - use String.Empty in class libs.
9190 /* Encode info required to decode shared GOT entries */
9191 buf_size = info->got_patches->len * 128;
9192 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9193 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9195 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9197 if (acfg->plt_offset)
9198 acfg->plt_got_info_offsets [0] = 0;
9200 for (i = 0; i < info->got_patches->len; ++i) {
9201 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9206 encode_value (ji->type, p, &p);
9208 encode_patch (acfg, ji, p, &p);
9209 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9210 g_assert (p - buf <= buf_size);
9211 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9213 if (!llvm && i >= first_plt_got_patch)
9214 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9215 acfg->stats.got_info_size += p - buf;
9218 /* Emit got_info_offsets table */
9220 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9221 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);
9225 emit_got (MonoAotCompile *acfg)
9227 char symbol [MAX_SYMBOL_SIZE];
9229 if (acfg->aot_opts.llvm_only)
9232 /* Don't make GOT global so accesses to it don't need relocations */
9233 sprintf (symbol, "%s", acfg->got_symbol);
9236 emit_unset_mode (acfg);
9237 fprintf (acfg->fp, ".section __DATA, __bss\n");
9238 emit_alignment (acfg, 8);
9240 emit_info_symbol (acfg, "jit_got");
9241 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9243 emit_section_change (acfg, ".bss", 0);
9244 emit_alignment (acfg, 8);
9245 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9246 emit_label (acfg, symbol);
9248 emit_info_symbol (acfg, "jit_got");
9249 if (acfg->got_offset > 0)
9250 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9253 sprintf (symbol, "got_end");
9254 emit_label (acfg, symbol);
9257 typedef struct GlobalsTableEntry {
9258 guint32 value, index;
9259 struct GlobalsTableEntry *next;
9260 } GlobalsTableEntry;
9263 emit_globals (MonoAotCompile *acfg)
9269 GlobalsTableEntry *entry, *new_entry;
9271 if (!acfg->aot_opts.static_link)
9273 if (acfg->aot_opts.llvm_only) {
9274 g_assert (acfg->globals->len == 0);
9279 * When static linking, we emit a table containing our globals.
9283 * Construct a chained hash table for mapping global names to their index in
9284 * the globals table.
9286 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9287 table = g_ptr_array_sized_new (table_size);
9288 for (i = 0; i < table_size; ++i)
9289 g_ptr_array_add (table, NULL);
9290 for (i = 0; i < acfg->globals->len; ++i) {
9291 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9293 hash = mono_metadata_str_hash (name) % table_size;
9295 /* FIXME: Allocate from the mempool */
9296 new_entry = g_new0 (GlobalsTableEntry, 1);
9297 new_entry->value = i;
9299 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9300 if (entry == NULL) {
9301 new_entry->index = hash;
9302 g_ptr_array_index (table, hash) = new_entry;
9305 entry = entry->next;
9307 entry->next = new_entry;
9308 new_entry->index = table->len;
9309 g_ptr_array_add (table, new_entry);
9313 /* Emit the table */
9314 sprintf (symbol, ".Lglobals_hash");
9315 emit_section_change (acfg, RODATA_SECT, 0);
9316 emit_alignment (acfg, 8);
9317 emit_label (acfg, symbol);
9319 /* FIXME: Optimize memory usage */
9320 g_assert (table_size < 65000);
9321 emit_int16 (acfg, table_size);
9322 for (i = 0; i < table->len; ++i) {
9323 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9325 if (entry == NULL) {
9326 emit_int16 (acfg, 0);
9327 emit_int16 (acfg, 0);
9329 emit_int16 (acfg, entry->value + 1);
9331 emit_int16 (acfg, entry->next->index);
9333 emit_int16 (acfg, 0);
9337 /* Emit the names */
9338 for (i = 0; i < acfg->globals->len; ++i) {
9339 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9341 sprintf (symbol, "name_%d", i);
9342 emit_section_change (acfg, RODATA_SECT, 1);
9344 emit_alignment (acfg, 4);
9346 emit_label (acfg, symbol);
9347 emit_string (acfg, name);
9350 /* Emit the globals table */
9351 sprintf (symbol, "globals");
9352 emit_section_change (acfg, ".data", 0);
9353 /* This is not a global, since it is accessed by the init function */
9354 emit_alignment (acfg, 8);
9355 emit_info_symbol (acfg, symbol);
9357 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9358 emit_pointer (acfg, symbol);
9360 for (i = 0; i < acfg->globals->len; ++i) {
9361 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9363 sprintf (symbol, "name_%d", i);
9364 emit_pointer (acfg, symbol);
9366 g_assert (strlen (name) < sizeof (symbol));
9367 sprintf (symbol, "%s", name);
9368 emit_pointer (acfg, symbol);
9370 /* Null terminate the table */
9371 emit_int32 (acfg, 0);
9372 emit_int32 (acfg, 0);
9376 emit_mem_end (MonoAotCompile *acfg)
9380 if (acfg->aot_opts.llvm_only)
9383 sprintf (symbol, "mem_end");
9384 emit_section_change (acfg, ".text", 1);
9385 emit_alignment_code (acfg, 8);
9386 emit_label (acfg, symbol);
9390 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9394 info->version = MONO_AOT_FILE_VERSION;
9395 info->plt_got_offset_base = acfg->plt_got_offset_base;
9396 info->got_size = acfg->got_offset * sizeof (gpointer);
9397 info->plt_size = acfg->plt_offset;
9398 info->nmethods = acfg->nmethods;
9399 info->flags = acfg->flags;
9400 info->opts = acfg->opts;
9401 info->simd_opts = acfg->simd_opts;
9402 info->gc_name_index = acfg->gc_name_offset;
9403 info->datafile_size = acfg->datafile_offset;
9404 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9405 info->table_offsets [i] = acfg->table_offsets [i];
9406 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9407 info->num_trampolines [i] = acfg->num_trampolines [i];
9408 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9409 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9410 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9411 info->trampoline_size [i] = acfg->trampoline_size [i];
9412 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9414 info->double_align = MONO_ABI_ALIGNOF (double);
9415 info->long_align = MONO_ABI_ALIGNOF (gint64);
9416 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9417 info->tramp_page_size = acfg->tramp_page_size;
9418 info->nshared_got_entries = acfg->nshared_got_entries;
9419 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9420 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9422 memcpy(&info->aotid, acfg->image->aotid, 16);
9426 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9428 char symbol [MAX_SYMBOL_SIZE];
9430 const char **symbols;
9432 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9434 symbols [sindex ++] = acfg->got_symbol;
9436 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9437 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9439 symbols [sindex ++] = NULL;
9440 symbols [sindex ++] = NULL;
9442 /* llvm_get_method */
9443 symbols [sindex ++] = NULL;
9444 /* llvm_get_unbox_tramp */
9445 symbols [sindex ++] = NULL;
9446 if (!acfg->aot_opts.llvm_only) {
9447 symbols [sindex ++] = "jit_code_start";
9448 symbols [sindex ++] = "jit_code_end";
9449 symbols [sindex ++] = "method_addresses";
9451 symbols [sindex ++] = NULL;
9452 symbols [sindex ++] = NULL;
9453 symbols [sindex ++] = NULL;
9455 if (acfg->data_outfile) {
9456 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9457 symbols [sindex ++] = NULL;
9459 symbols [sindex ++] = "blob";
9460 symbols [sindex ++] = "class_name_table";
9461 symbols [sindex ++] = "class_info_offsets";
9462 symbols [sindex ++] = "method_info_offsets";
9463 symbols [sindex ++] = "ex_info_offsets";
9464 symbols [sindex ++] = "extra_method_info_offsets";
9465 symbols [sindex ++] = "extra_method_table";
9466 symbols [sindex ++] = "got_info_offsets";
9468 symbols [sindex ++] = "llvm_got_info_offsets";
9470 symbols [sindex ++] = NULL;
9471 symbols [sindex ++] = "image_table";
9473 symbols [sindex ++] = "mem_end";
9474 symbols [sindex ++] = "assembly_guid";
9475 symbols [sindex ++] = "runtime_version";
9476 if (acfg->num_trampoline_got_entries) {
9477 symbols [sindex ++] = "specific_trampolines";
9478 symbols [sindex ++] = "static_rgctx_trampolines";
9479 symbols [sindex ++] = "imt_trampolines";
9480 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9482 symbols [sindex ++] = NULL;
9483 symbols [sindex ++] = NULL;
9484 symbols [sindex ++] = NULL;
9485 symbols [sindex ++] = NULL;
9487 if (acfg->aot_opts.static_link) {
9488 symbols [sindex ++] = "globals";
9490 symbols [sindex ++] = NULL;
9492 symbols [sindex ++] = "assembly_name";
9493 symbols [sindex ++] = "plt";
9494 symbols [sindex ++] = "plt_end";
9495 symbols [sindex ++] = "unwind_info";
9496 if (!acfg->aot_opts.llvm_only) {
9497 symbols [sindex ++] = "unbox_trampolines";
9498 symbols [sindex ++] = "unbox_trampolines_end";
9499 symbols [sindex ++] = "unbox_trampoline_addresses";
9501 symbols [sindex ++] = NULL;
9502 symbols [sindex ++] = NULL;
9503 symbols [sindex ++] = NULL;
9506 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9508 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9509 emit_section_change (acfg, ".data", 0);
9510 emit_alignment (acfg, 8);
9511 emit_label (acfg, symbol);
9512 if (!acfg->aot_opts.static_link)
9513 emit_global (acfg, symbol, FALSE);
9515 /* The data emitted here must match MonoAotFileInfo. */
9517 emit_int32 (acfg, info->version);
9518 emit_int32 (acfg, info->dummy);
9521 * We emit pointers to our data structures instead of emitting global symbols which
9522 * point to them, to reduce the number of globals, and because using globals leads to
9523 * various problems (i.e. arm/thumb).
9525 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9526 emit_pointer (acfg, symbols [i]);
9528 emit_int32 (acfg, info->plt_got_offset_base);
9529 emit_int32 (acfg, info->got_size);
9530 emit_int32 (acfg, info->plt_size);
9531 emit_int32 (acfg, info->nmethods);
9532 emit_int32 (acfg, info->flags);
9533 emit_int32 (acfg, info->opts);
9534 emit_int32 (acfg, info->simd_opts);
9535 emit_int32 (acfg, info->gc_name_index);
9536 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9537 emit_int32 (acfg, info->double_align);
9538 emit_int32 (acfg, info->long_align);
9539 emit_int32 (acfg, info->generic_tramp_num);
9540 emit_int32 (acfg, info->tramp_page_size);
9541 emit_int32 (acfg, info->nshared_got_entries);
9542 emit_int32 (acfg, info->datafile_size);
9544 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9545 emit_int32 (acfg, info->table_offsets [i]);
9546 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9547 emit_int32 (acfg, info->num_trampolines [i]);
9548 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9549 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9550 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9551 emit_int32 (acfg, info->trampoline_size [i]);
9552 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9553 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9555 emit_bytes (acfg, info->aotid, 16);
9557 if (acfg->aot_opts.static_link) {
9558 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9559 emit_alignment (acfg, sizeof (gpointer));
9560 emit_label (acfg, acfg->static_linking_symbol);
9561 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9566 * Emit a structure containing all the information not stored elsewhere.
9569 emit_file_info (MonoAotCompile *acfg)
9572 MonoAotFileInfo *info;
9574 if (acfg->aot_opts.bind_to_runtime_version) {
9575 build_info = mono_get_runtime_build_info ();
9576 emit_string_symbol (acfg, "runtime_version", build_info);
9577 g_free (build_info);
9579 emit_string_symbol (acfg, "runtime_version", "");
9582 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9584 /* Emit a string holding the assembly name */
9585 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9587 info = g_new0 (MonoAotFileInfo, 1);
9588 init_aot_file_info (acfg, info);
9590 if (acfg->aot_opts.static_link) {
9591 char symbol [MAX_SYMBOL_SIZE];
9595 * Emit a global symbol which can be passed by an embedding app to
9596 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9599 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9601 /* Get rid of characters which cannot occur in symbols */
9603 for (p = symbol; *p; ++p) {
9604 if (!(isalnum (*p) || *p == '_'))
9607 acfg->static_linking_symbol = g_strdup (symbol);
9611 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9613 emit_aot_file_info (acfg, info);
9617 emit_blob (MonoAotCompile *acfg)
9619 acfg->blob_closed = TRUE;
9621 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9625 emit_objc_selectors (MonoAotCompile *acfg)
9630 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9635 * cat > foo.m << EOF
9638 * return @selector(print:);
9643 mono_img_writer_emit_unset_mode (acfg->w);
9644 g_assert (acfg->fp);
9645 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9646 fprintf (acfg->fp, ".align 3\n");
9647 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9648 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9649 emit_label (acfg, symbol);
9650 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9651 emit_pointer (acfg, symbol);
9654 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9655 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9656 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9657 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9660 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9661 fprintf (acfg->fp, ".align 3\n");
9662 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9663 fprintf (acfg->fp, ".long 0\n");
9664 fprintf (acfg->fp, ".long 16\n");
9668 emit_dwarf_info (MonoAotCompile *acfg)
9670 #ifdef EMIT_DWARF_INFO
9674 /* DIEs for methods */
9675 for (i = 0; i < acfg->nmethods; ++i) {
9676 MonoCompile *cfg = acfg->cfgs [i];
9681 // FIXME: LLVM doesn't define .Lme_...
9682 if (cfg->compile_llvm)
9685 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9687 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 ()));
9693 collect_methods (MonoAotCompile *acfg)
9696 MonoImage *image = acfg->image;
9698 /* Collect methods */
9699 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9702 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9704 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9707 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9708 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9709 mono_error_cleanup (&error);
9713 /* Load all methods eagerly to skip the slower lazy loading code */
9714 mono_class_setup_methods (method->klass);
9716 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9717 /* Compile the wrapper instead */
9718 /* We do this here instead of add_wrappers () because it is easy to do it here */
9719 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9723 /* FIXME: Some mscorlib methods don't have debug info */
9725 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9726 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9727 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9728 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9729 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9730 if (!mono_debug_lookup_method (method)) {
9731 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9738 if (method->is_generic || method->klass->generic_container)
9739 /* Compile the ref shared version instead */
9740 method = mini_get_shared_method (method);
9742 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9743 add_method_with_index (acfg, method, i, FALSE);
9744 acfg->method_index ++;
9747 /* gsharedvt methods */
9748 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9751 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9753 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9756 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9757 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9759 if (method->is_generic || method->klass->generic_container) {
9760 MonoMethod *gshared;
9762 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9763 add_extra_method (acfg, gshared);
9767 add_generic_instances (acfg);
9769 if (mono_aot_mode_is_full (&acfg->aot_opts))
9770 add_wrappers (acfg);
9775 compile_methods (MonoAotCompile *acfg)
9779 if (acfg->aot_opts.nthreads > 0) {
9784 gpointer *user_data;
9785 MonoMethod **methods;
9787 methods_len = acfg->methods->len;
9789 len = acfg->methods->len / acfg->aot_opts.nthreads;
9792 * Partition the list of methods into fragments, and hand it to threads to
9795 threads = g_ptr_array_new ();
9796 /* Make a copy since acfg->methods is modified by compile_method () */
9797 methods = g_new0 (MonoMethod*, methods_len);
9798 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9799 for (i = 0; i < methods_len; ++i)
9800 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9802 while (i < methods_len) {
9803 frag = g_ptr_array_new ();
9804 for (j = 0; j < len; ++j) {
9805 if (i < methods_len) {
9806 g_ptr_array_add (frag, methods [i]);
9811 user_data = g_new0 (gpointer, 3);
9812 user_data [0] = mono_domain_get ();
9813 user_data [1] = acfg;
9814 user_data [2] = frag;
9816 handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, 0, NULL);
9817 g_ptr_array_add (threads, handle);
9821 for (i = 0; i < threads->len; ++i) {
9822 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9823 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9829 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9830 for (i = methods_len; i < acfg->methods->len; ++i) {
9831 /* This can new methods to acfg->methods */
9832 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9837 compile_asm (MonoAotCompile *acfg)
9839 char *command, *objfile;
9840 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9841 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9842 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9844 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9845 #define AS_OPTIONS "--64"
9846 #elif defined(TARGET_POWERPC64)
9847 #define AS_OPTIONS "-a64 -mppc64"
9848 #elif defined(sparc) && SIZEOF_VOID_P == 8
9849 #define AS_OPTIONS "-xarch=v9"
9850 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9851 #define AS_OPTIONS "-arch i386"
9853 #define AS_OPTIONS ""
9856 #ifdef __native_client_codegen__
9857 #if defined(TARGET_AMD64)
9858 #define AS_NAME "nacl64-as"
9860 #define AS_NAME "nacl-as"
9862 #elif defined(TARGET_OSX)
9863 #define AS_NAME "clang"
9865 #define AS_NAME "as"
9869 #define LD_NAME "ld"
9870 #define LD_OPTIONS "-shared -G"
9871 #elif defined(__ppc__) && defined(TARGET_MACH)
9872 #define LD_NAME "gcc"
9873 #define LD_OPTIONS "-dynamiclib"
9874 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9875 #define LD_NAME "clang"
9876 #define LD_OPTIONS "--shared"
9877 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9878 #define LD_NAME "gcc"
9879 #define LD_OPTIONS "-shared"
9880 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9881 #define LD_NAME "clang"
9882 #define LD_OPTIONS "-m32 -dynamiclib"
9883 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9884 #define LD_NAME "gcc"
9885 #define LD_OPTIONS "--shared"
9886 #elif defined(TARGET_POWERPC64)
9887 #define LD_OPTIONS "-m elf64ppc"
9891 #define LD_OPTIONS ""
9894 if (acfg->aot_opts.asm_only) {
9895 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9896 if (acfg->aot_opts.static_link)
9897 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9899 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9903 if (acfg->aot_opts.static_link) {
9904 if (acfg->aot_opts.outfile)
9905 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9907 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9909 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9913 g_string_append (acfg->as_args, "-c -x assembler");
9916 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9917 acfg->as_args ? acfg->as_args->str : "",
9918 wrap_path (objfile), wrap_path (acfg->tmpfname));
9919 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9920 if (execute_system (command) != 0) {
9926 if (acfg->llvm && !acfg->llvm_owriter) {
9927 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9928 acfg->as_args ? acfg->as_args->str : "",
9929 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9930 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9931 if (execute_system (command) != 0) {
9940 if (acfg->aot_opts.static_link) {
9941 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9942 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9947 if (acfg->aot_opts.outfile)
9948 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9950 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9952 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9955 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9957 llvm_ofile = g_strdup ("");
9960 /* replace the ; flags separators with spaces */
9961 g_strdelimit (ld_flags, ";", ' ');
9963 if (acfg->aot_opts.llvm_only)
9964 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9967 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
9968 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9969 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9972 if (acfg->aot_opts.tool_prefix) {
9973 /* Cross compiling */
9974 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9975 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9976 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9978 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
9979 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9980 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9983 command = g_strdup_printf ("clang++ %s", args);
9985 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
9991 aot_printf (acfg, "Executing the native linker: %s\n", command);
9992 if (execute_system (command) != 0) {
9993 g_free (tmp_outfile_name);
9994 g_free (outfile_name);
10003 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10004 printf ("Stripping the binary: %s\n", com);
10005 execute_system (com);
10008 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10010 * gas generates 'mapping symbols' each time code and data is mixed, which
10011 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10013 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10014 aot_printf (acfg, "Stripping the binary: %s\n", command);
10015 if (execute_system (command) != 0) {
10016 g_free (tmp_outfile_name);
10017 g_free (outfile_name);
10024 if (0 != rename (tmp_outfile_name, outfile_name)) {
10025 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10026 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10027 unlink (outfile_name);
10028 rename (tmp_outfile_name, outfile_name);
10032 #if defined(TARGET_MACH)
10033 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10034 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10035 if (execute_system (command) != 0) {
10040 if (!acfg->aot_opts.save_temps)
10043 g_free (tmp_outfile_name);
10044 g_free (outfile_name);
10047 if (acfg->aot_opts.save_temps)
10048 aot_printf (acfg, "Retained input file.\n");
10050 unlink (acfg->tmpfname);
10055 static void init_got_info (GotInfo *info)
10059 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10060 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10061 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10062 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10063 info->got_patches = g_ptr_array_new ();
10066 static MonoAotCompile*
10067 acfg_create (MonoAssembly *ass, guint32 opts)
10069 MonoImage *image = ass->image;
10070 MonoAotCompile *acfg;
10072 acfg = g_new0 (MonoAotCompile, 1);
10073 acfg->methods = g_ptr_array_new ();
10074 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10075 acfg->method_depth = g_hash_table_new (NULL, NULL);
10076 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10077 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10078 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10079 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10080 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10081 acfg->image_hash = g_hash_table_new (NULL, NULL);
10082 acfg->image_table = g_ptr_array_new ();
10083 acfg->globals = g_ptr_array_new ();
10084 acfg->image = image;
10086 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10087 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10088 acfg->mempool = mono_mempool_new ();
10089 acfg->extra_methods = g_ptr_array_new ();
10090 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10091 acfg->unwind_ops = g_ptr_array_new ();
10092 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10093 acfg->method_order = g_ptr_array_new ();
10094 acfg->export_names = g_hash_table_new (NULL, NULL);
10095 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10096 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10097 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10098 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10099 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10100 mono_os_mutex_init_recursive (&acfg->mutex);
10102 init_got_info (&acfg->got_info);
10103 init_got_info (&acfg->llvm_got_info);
10109 got_info_free (GotInfo *info)
10113 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10114 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10115 g_free (info->patch_to_got_offset_by_type);
10116 g_hash_table_destroy (info->patch_to_got_offset);
10117 g_ptr_array_free (info->got_patches, TRUE);
10121 acfg_free (MonoAotCompile *acfg)
10125 mono_img_writer_destroy (acfg->w);
10126 for (i = 0; i < acfg->nmethods; ++i)
10127 if (acfg->cfgs [i])
10128 mono_destroy_compile (acfg->cfgs [i]);
10130 g_free (acfg->cfgs);
10132 g_free (acfg->static_linking_symbol);
10133 g_free (acfg->got_symbol);
10134 g_free (acfg->plt_symbol);
10135 g_ptr_array_free (acfg->methods, TRUE);
10136 g_ptr_array_free (acfg->image_table, TRUE);
10137 g_ptr_array_free (acfg->globals, TRUE);
10138 g_ptr_array_free (acfg->unwind_ops, TRUE);
10139 g_hash_table_destroy (acfg->method_indexes);
10140 g_hash_table_destroy (acfg->method_depth);
10141 g_hash_table_destroy (acfg->plt_offset_to_entry);
10142 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10143 if (acfg->patch_to_plt_entry [i])
10144 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10146 g_free (acfg->patch_to_plt_entry);
10147 g_hash_table_destroy (acfg->method_to_cfg);
10148 g_hash_table_destroy (acfg->token_info_hash);
10149 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10150 g_hash_table_destroy (acfg->image_hash);
10151 g_hash_table_destroy (acfg->unwind_info_offsets);
10152 g_hash_table_destroy (acfg->method_label_hash);
10153 if (acfg->typespec_classes)
10154 g_hash_table_destroy (acfg->typespec_classes);
10155 g_hash_table_destroy (acfg->export_names);
10156 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10157 g_hash_table_destroy (acfg->klass_blob_hash);
10158 g_hash_table_destroy (acfg->method_blob_hash);
10159 got_info_free (&acfg->got_info);
10160 got_info_free (&acfg->llvm_got_info);
10161 mono_mempool_destroy (acfg->mempool);
10165 #define WRAPPER(e,n) n,
10166 static const char* const
10167 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10168 #include "mono/metadata/wrapper-types.h"
10172 static G_GNUC_UNUSED const char*
10173 get_wrapper_type_name (int type)
10175 return wrapper_type_names [type];
10181 static void aot_dump (MonoAotCompile *acfg)
10187 mono_json_writer_init (&writer);
10189 mono_json_writer_object_begin(&writer);
10192 mono_json_writer_indent (&writer);
10193 mono_json_writer_object_key(&writer, "methods");
10194 mono_json_writer_array_begin (&writer);
10197 for (i = 0; i < acfg->nmethods; ++i) {
10199 MonoMethod *method;
10202 cfg = acfg->cfgs [i];
10206 method = cfg->orig_method;
10208 mono_json_writer_indent (&writer);
10209 mono_json_writer_object_begin(&writer);
10211 mono_json_writer_indent (&writer);
10212 mono_json_writer_object_key(&writer, "name");
10213 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10215 mono_json_writer_indent (&writer);
10216 mono_json_writer_object_key(&writer, "signature");
10217 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10219 mono_json_writer_indent (&writer);
10220 mono_json_writer_object_key(&writer, "code_size");
10221 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10223 klass = method->klass;
10225 mono_json_writer_indent (&writer);
10226 mono_json_writer_object_key(&writer, "class");
10227 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10229 mono_json_writer_indent (&writer);
10230 mono_json_writer_object_key(&writer, "namespace");
10231 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10233 mono_json_writer_indent (&writer);
10234 mono_json_writer_object_key(&writer, "wrapper_type");
10235 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10237 mono_json_writer_indent_pop (&writer);
10238 mono_json_writer_indent (&writer);
10239 mono_json_writer_object_end (&writer);
10240 mono_json_writer_printf (&writer, ",\n");
10243 mono_json_writer_indent_pop (&writer);
10244 mono_json_writer_indent (&writer);
10245 mono_json_writer_array_end (&writer);
10246 mono_json_writer_printf (&writer, ",\n");
10250 mono_json_writer_indent_push (&writer);
10251 mono_json_writer_indent (&writer);
10252 mono_json_writer_object_key(&writer, "plt");
10253 mono_json_writer_array_begin (&writer);
10255 for (i = 0; i < acfg->plt_offset; ++i) {
10256 MonoPltEntry *plt_entry = NULL;
10261 * The first plt entry is unused.
10265 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10266 ji = plt_entry->ji;
10268 mono_json_writer_indent (&writer);
10269 mono_json_writer_printf (&writer, "{ ");
10270 mono_json_writer_object_key(&writer, "symbol");
10271 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10274 mono_json_writer_indent_pop (&writer);
10275 mono_json_writer_indent (&writer);
10276 mono_json_writer_array_end (&writer);
10277 mono_json_writer_printf (&writer, ",\n");
10282 mono_json_writer_indent_push (&writer);
10283 mono_json_writer_indent (&writer);
10284 mono_json_writer_object_key(&writer, "got");
10285 mono_json_writer_array_begin (&writer);
10287 mono_json_writer_indent_push (&writer);
10288 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10289 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10291 mono_json_writer_indent (&writer);
10292 mono_json_writer_printf (&writer, "{ ");
10293 mono_json_writer_object_key(&writer, "patch_name");
10294 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10297 mono_json_writer_indent_pop (&writer);
10298 mono_json_writer_indent (&writer);
10299 mono_json_writer_array_end (&writer);
10300 mono_json_writer_printf (&writer, ",\n");
10303 mono_json_writer_indent_pop (&writer);
10304 mono_json_writer_indent (&writer);
10305 mono_json_writer_object_end (&writer);
10307 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10308 dumpfile = fopen (dumpname, "w+");
10311 fprintf (dumpfile, "%s", writer.text->str);
10314 mono_json_writer_destroy (&writer);
10317 static const char *preinited_jit_icalls[] = {
10318 "mono_aot_init_llvm_method",
10319 "mono_aot_init_gshared_method_this",
10320 "mono_aot_init_gshared_method_mrgctx",
10321 "mono_aot_init_gshared_method_vtable",
10322 "mono_llvm_throw_corlib_exception",
10323 "mono_init_vtable_slot",
10324 "mono_helper_ldstr_mscorlib"
10328 add_preinit_got_slots (MonoAotCompile *acfg)
10334 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10335 * during method initialization etc.
10338 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10339 ji->type = MONO_PATCH_INFO_IMAGE;
10340 ji->data.image = acfg->image;
10341 get_got_offset (acfg, FALSE, ji);
10342 get_got_offset (acfg, TRUE, ji);
10344 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10345 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10346 get_got_offset (acfg, FALSE, ji);
10347 get_got_offset (acfg, TRUE, ji);
10349 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10350 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10351 get_got_offset (acfg, FALSE, ji);
10352 get_got_offset (acfg, TRUE, ji);
10354 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10355 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10356 get_got_offset (acfg, FALSE, ji);
10357 get_got_offset (acfg, TRUE, ji);
10359 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10360 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10361 get_got_offset (acfg, FALSE, ji);
10362 get_got_offset (acfg, TRUE, ji);
10364 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10365 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10366 get_got_offset (acfg, FALSE, ji);
10367 get_got_offset (acfg, TRUE, ji);
10369 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10370 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10371 get_got_offset (acfg, FALSE, ji);
10372 get_got_offset (acfg, TRUE, ji);
10374 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10375 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10376 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10377 ji->data.name = preinited_jit_icalls [i];
10378 get_got_offset (acfg, FALSE, ji);
10379 get_got_offset (acfg, TRUE, ji);
10382 acfg->nshared_got_entries = acfg->got_offset;
10386 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10388 MonoImage *image = ass->image;
10391 MonoAotCompile *acfg;
10392 char *outfile_name, *tmp_outfile_name, *p;
10393 char llvm_stats_msg [256];
10397 acfg = acfg_create (ass, opts);
10399 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10400 acfg->aot_opts.write_symbols = TRUE;
10401 acfg->aot_opts.ntrampolines = 4096;
10402 acfg->aot_opts.nrgctx_trampolines = 4096;
10403 acfg->aot_opts.nimt_trampolines = 512;
10404 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10405 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10406 acfg->aot_opts.llvm_path = g_strdup ("");
10407 acfg->aot_opts.temp_path = g_strdup ("");
10409 acfg->aot_opts.use_trampolines_page = TRUE;
10412 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10414 if (acfg->aot_opts.logfile) {
10415 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10418 if (acfg->aot_opts.data_outfile) {
10419 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10420 if (!acfg->data_outfile) {
10421 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10424 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10427 //acfg->aot_opts.print_skipped_methods = TRUE;
10429 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10430 if (opts & MONO_OPT_GSHAREDVT) {
10431 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10436 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10437 if (!acfg->aot_opts.llvm_only && (opts & MONO_OPT_GSHAREDVT)) {
10438 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10443 if (acfg->aot_opts.llvm_only) {
10444 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
10445 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10448 #ifndef ENABLE_LLVM
10449 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
10454 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10455 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts)) {
10456 acfg->opts |= MONO_OPT_GSHAREDVT;
10457 opts |= MONO_OPT_GSHAREDVT;
10461 if (opts & MONO_OPT_GSHAREDVT)
10462 mono_set_generic_sharing_vt_supported (TRUE);
10464 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10466 generate_aotid ((guint8*) &acfg->image->aotid);
10468 char *aotid = mono_guid_to_string (acfg->image->aotid);
10469 aot_printf (acfg, "AOTID %s\n", aotid);
10472 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10473 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10474 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10479 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10480 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10484 if (acfg->aot_opts.static_link)
10485 acfg->aot_opts.asm_writer = TRUE;
10487 if (acfg->aot_opts.soft_debug) {
10488 MonoDebugOptions *opt = mini_get_debug_options ();
10490 opt->mdb_optimizations = TRUE;
10491 opt->gen_sdb_seq_points = TRUE;
10493 if (!mono_debug_enabled ()) {
10494 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10497 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10500 if (mono_use_llvm || acfg->aot_opts.llvm) {
10502 acfg->aot_opts.asm_writer = TRUE;
10503 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10505 if (acfg->aot_opts.soft_debug) {
10506 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10512 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10513 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10518 if (mono_aot_mode_is_full (&acfg->aot_opts))
10519 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10521 if (mono_threads_is_coop_enabled ())
10522 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10524 if (acfg->aot_opts.instances_logfile_path) {
10525 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10526 if (!acfg->instances_logfile) {
10527 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10532 load_profile_files (acfg);
10534 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10535 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10536 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10538 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10539 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10540 if (acfg->opts & MONO_OPT_GSHAREDVT)
10541 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10544 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10548 if (mono_use_llvm || acfg->aot_opts.llvm) {
10551 * Emit all LLVM code into a separate assembly/object file and link with it
10554 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
10555 acfg->llvm_owriter = TRUE;
10556 } else if (acfg->aot_opts.llvm_outfile) {
10557 int len = strlen (acfg->aot_opts.llvm_outfile);
10559 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10560 acfg->llvm_owriter = TRUE;
10564 if (acfg->llvm && acfg->thumb_mixed)
10565 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10566 if (acfg->aot_opts.llvm_only)
10567 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10569 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10570 /* Get rid of characters which cannot occur in symbols */
10571 for (p = acfg->assembly_name_sym; *p; ++p) {
10572 if (!(isalnum (*p) || *p == '_'))
10576 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10577 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10578 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10580 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10581 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10584 acfg->method_index = 1;
10586 if (mono_aot_mode_is_full (&acfg->aot_opts))
10587 mono_set_partial_sharing_supported (TRUE);
10589 res = collect_methods (acfg);
10593 acfg->cfgs_size = acfg->methods->len + 32;
10594 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10596 /* PLT offset 0 is reserved for the PLT trampoline */
10597 acfg->plt_offset = 1;
10598 add_preinit_got_slots (acfg);
10603 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10609 compile_methods (acfg);
10613 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10619 if (acfg->aot_opts.asm_only) {
10620 if (acfg->aot_opts.outfile) {
10621 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10622 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10624 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10625 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10627 g_assert (acfg->aot_opts.llvm_outfile);
10628 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10629 if (acfg->llvm_owriter)
10630 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10632 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10634 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10635 g_strdup_printf ("%s", "temp") :
10636 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10638 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10639 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10640 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10645 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10646 if (acfg->aot_opts.outfile)
10647 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10649 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10650 acfg->fp = fopen (acfg->tmpfname, "w+");
10652 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10653 acfg->fp = fdopen (i, "w+");
10655 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10656 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10660 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10662 tmp_outfile_name = NULL;
10663 outfile_name = NULL;
10665 /* Compute symbols for methods */
10666 for (i = 0; i < acfg->nmethods; ++i) {
10667 if (acfg->cfgs [i]) {
10668 MonoCompile *cfg = acfg->cfgs [i];
10669 int method_index = get_method_index (acfg, cfg->orig_method);
10671 if (COMPILE_LLVM (cfg))
10672 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10673 else if (acfg->global_symbols || acfg->llvm)
10674 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10676 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10677 cfg->asm_debug_symbol = cfg->asm_symbol;
10681 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10683 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10685 acfg->gas_line_numbers = TRUE;
10688 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10689 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10690 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10693 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10697 mono_img_writer_emit_start (acfg->w);
10700 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10706 emit_extra_methods (acfg);
10708 emit_trampolines (acfg);
10710 emit_class_name_table (acfg);
10712 emit_got_info (acfg, FALSE);
10714 emit_got_info (acfg, TRUE);
10716 emit_exception_info (acfg);
10718 emit_unwind_info (acfg);
10720 emit_class_info (acfg);
10724 emit_image_table (acfg);
10730 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10733 const char *gc_name = mono_gc_get_gc_name ();
10734 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10739 emit_objc_selectors (acfg);
10741 emit_globals (acfg);
10743 emit_file_info (acfg);
10746 emit_dwarf_info (acfg);
10747 mono_dwarf_writer_close (acfg->dwarf);
10750 emit_mem_end (acfg);
10752 if (acfg->need_pt_gnu_stack) {
10753 /* This is required so the .so doesn't have an executable stack */
10754 /* The bin writer already emits this */
10755 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10758 if (acfg->aot_opts.data_outfile)
10759 fclose (acfg->data_outfile);
10765 res = emit_llvm_file (acfg);
10773 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10776 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10778 strcpy (llvm_stats_msg, "");
10780 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;
10782 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",
10783 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10784 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10785 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10786 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10787 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10788 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,
10789 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10790 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10791 (int)(acfg->got_offset * sizeof (gpointer)));
10792 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10793 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10795 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10796 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10797 if (acfg->stats.genericcount)
10798 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10799 if (acfg->stats.abscount)
10800 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10801 if (acfg->stats.lmfcount)
10802 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10803 if (acfg->stats.ocount)
10804 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10808 res = mono_img_writer_emit_writeout (acfg->w);
10813 res = compile_asm (acfg);
10820 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10822 if (acfg->aot_opts.stats) {
10825 aot_printf (acfg, "GOT slot distribution:\n");
10826 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10827 if (acfg->stats.got_slot_types [i])
10828 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]);
10829 aot_printf (acfg, "\nMethod stats:\n");
10830 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10831 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10832 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10833 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10836 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);
10838 if (acfg->aot_opts.dump_json)
10851 mono_aot_readonly_field_override (MonoClassField *field)
10857 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10863 mono_aot_is_shared_got_offset (int offset)