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, Assembly, bool) [DoAssemblyResolve] */
3848 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
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_class_load_from_name (mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3854 csig->params [2] = &mono_defaults.boolean_class->byval_arg;
3855 add_method (acfg, get_runtime_invoke_sig (csig));
3857 /* runtime-invoke used by finalizers */
3858 add_method (acfg, get_runtime_invoke (acfg, mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3860 /* This is used by mono_runtime_capture_context () */
3861 method = mono_get_context_capture_method ();
3863 add_method (acfg, get_runtime_invoke (acfg, method, FALSE));
3865 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3866 if (!acfg->aot_opts.llvm_only)
3867 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3870 /* These are used by mono_jit_runtime_invoke () to calls gsharedvt out wrappers */
3871 if (acfg->aot_opts.llvm_only) {
3874 /* Create simplified signatures which match the signature used by the gsharedvt out wrappers */
3875 for (variants = 0; variants < 4; ++variants) {
3876 for (i = 0; i < 16; ++i) {
3877 sig = mini_get_gsharedvt_out_sig_wrapper_signature ((variants & 1) > 0, (variants & 2) > 0, i);
3878 add_extra_method (acfg, mono_marshal_get_runtime_invoke_for_sig (sig));
3886 add_method (acfg, mono_marshal_get_stelemref ());
3888 if (MONO_ARCH_HAVE_TLS_GET) {
3889 /* Managed Allocators */
3890 nallocators = mono_gc_get_managed_allocator_types ();
3891 for (i = 0; i < nallocators; ++i) {
3892 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_REGULAR)))
3893 add_method (acfg, m);
3894 if ((m = mono_gc_get_managed_allocator_by_type (i, MANAGED_ALLOCATOR_SLOW_PATH)))
3895 add_method (acfg, m);
3899 /* write barriers */
3900 if (mono_gc_is_moving ()) {
3901 add_method (acfg, mono_gc_get_specific_write_barrier (FALSE));
3902 add_method (acfg, mono_gc_get_specific_write_barrier (TRUE));
3905 /* Stelemref wrappers */
3907 MonoMethod **wrappers;
3910 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3911 for (i = 0; i < nwrappers; ++i)
3912 add_method (acfg, wrappers [i]);
3916 /* castclass_with_check wrapper */
3917 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3918 /* isinst_with_check wrapper */
3919 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3921 /* JIT icall wrappers */
3922 /* FIXME: locking - this is "safe" as full-AOT threads don't mutate the icall hash*/
3923 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3927 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3928 * we use the original method instead at runtime.
3929 * Since full-aot doesn't support remoting, this is not a problem.
3932 /* remoting-invoke wrappers */
3933 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3935 MonoMethodSignature *sig;
3937 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3938 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
3939 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
3941 sig = mono_method_signature (method);
3943 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3944 m = mono_marshal_get_remoting_invoke_with_check (method);
3946 add_method (acfg, m);
3951 /* delegate-invoke wrappers */
3952 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3955 MonoCustomAttrInfo *cattr;
3957 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3958 klass = mono_class_get_checked (acfg->image, token, &error);
3961 mono_error_cleanup (&error);
3965 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3968 if (!klass->generic_container) {
3969 method = mono_get_delegate_invoke (klass);
3971 m = mono_marshal_get_delegate_invoke (method, NULL);
3973 add_method (acfg, m);
3975 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3977 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3979 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3981 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3983 cattr = mono_custom_attrs_from_class_checked (klass, &error);
3984 if (!is_ok (&error)) {
3985 mono_error_cleanup (&error);
3992 for (j = 0; j < cattr->num_attrs; ++j)
3993 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3995 if (j < cattr->num_attrs) {
3997 MonoMethod *wrapper;
3998 MonoMethod *del_invoke;
4000 /* Add wrappers needed by mono_ftnptr_to_delegate () */
4001 invoke = mono_get_delegate_invoke (klass);
4002 wrapper = mono_marshal_get_native_func_wrapper_aot (klass);
4003 del_invoke = mono_marshal_get_delegate_invoke_internal (invoke, FALSE, TRUE, wrapper);
4004 add_method (acfg, wrapper);
4005 add_method (acfg, del_invoke);
4008 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
4010 MonoGenericContext ctx;
4011 MonoMethod *inst, *gshared;
4014 * Emit gsharedvt versions of the generic delegate-invoke wrappers
4017 method = mono_get_delegate_invoke (klass);
4018 create_gsharedvt_inst (acfg, method, &ctx);
4020 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4021 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4023 m = mono_marshal_get_delegate_invoke (inst, NULL);
4024 g_assert (m->is_inflated);
4026 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4027 add_extra_method (acfg, gshared);
4030 method = mono_get_delegate_begin_invoke (klass);
4031 create_gsharedvt_inst (acfg, method, &ctx);
4033 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4034 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4036 m = mono_marshal_get_delegate_begin_invoke (inst);
4037 g_assert (m->is_inflated);
4039 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4040 add_extra_method (acfg, gshared);
4043 method = mono_get_delegate_end_invoke (klass);
4044 create_gsharedvt_inst (acfg, method, &ctx);
4046 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4047 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4049 m = mono_marshal_get_delegate_end_invoke (inst);
4050 g_assert (m->is_inflated);
4052 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4053 add_extra_method (acfg, gshared);
4058 /* array access wrappers */
4059 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4063 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4064 klass = mono_class_get_checked (acfg->image, token, &error);
4067 mono_error_cleanup (&error);
4071 if (klass->rank && MONO_TYPE_IS_PRIMITIVE (&klass->element_class->byval_arg)) {
4072 MonoMethod *m, *wrapper;
4074 /* Add runtime-invoke wrappers too */
4076 m = mono_class_get_method_from_name (klass, "Get", -1);
4078 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4079 add_extra_method (acfg, wrapper);
4080 if (!acfg->aot_opts.llvm_only)
4081 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4083 m = mono_class_get_method_from_name (klass, "Set", -1);
4085 wrapper = mono_marshal_get_array_accessor_wrapper (m);
4086 add_extra_method (acfg, wrapper);
4087 if (!acfg->aot_opts.llvm_only)
4088 add_extra_method (acfg, get_runtime_invoke (acfg, wrapper, FALSE));
4092 /* Synchronized wrappers */
4093 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4095 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4096 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4097 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4099 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) {
4100 if (method->is_generic) {
4102 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->klass->generic_container) {
4104 MonoGenericContext ctx;
4105 MonoMethod *inst, *gshared, *m;
4108 * Create a generic wrapper for a generic instance, and AOT that.
4110 create_gsharedvt_inst (acfg, method, &ctx);
4111 inst = mono_class_inflate_generic_method_checked (method, &ctx, &error);
4112 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4113 m = mono_marshal_get_synchronized_wrapper (inst);
4114 g_assert (m->is_inflated);
4115 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
4116 add_method (acfg, gshared);
4118 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
4123 /* pinvoke wrappers */
4124 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4127 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4129 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4130 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4132 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4133 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4134 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4138 /* native-to-managed wrappers */
4139 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4142 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4143 MonoCustomAttrInfo *cattr;
4146 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4147 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
4150 * Only generate native-to-managed wrappers for methods which have an
4151 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
4152 * name to avoid defining a new assembly to contain it.
4154 cattr = mono_custom_attrs_from_method_checked (method, &error);
4155 if (!is_ok (&error)) {
4156 char *name = mono_method_get_full_name (method);
4157 report_loader_error (acfg, &error, "Failed to load custom attributes from method %s due to %s\n", name, mono_error_get_message (&error));
4162 for (j = 0; j < cattr->num_attrs; ++j)
4163 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
4165 if (j < cattr->num_attrs) {
4166 MonoCustomAttrEntry *e = &cattr->attrs [j];
4167 MonoMethodSignature *sig = mono_method_signature (e->ctor);
4168 const char *p = (const char*)e->data;
4170 int slen, num_named, named_type;
4174 char *export_name = NULL;
4175 MonoMethod *wrapper;
4177 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
4178 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
4179 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
4180 mono_method_full_name (method, TRUE));
4184 g_assert (sig->param_count == 1);
4185 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
4188 * Decode the cattr manually since we can't create objects
4189 * during aot compilation.
4195 /* From load_cattr_value () in reflection.c */
4196 slen = mono_metadata_decode_value (p, &p);
4197 n = (char *)g_memdup (p, slen + 1);
4199 t = mono_reflection_type_from_name_checked (n, acfg->image, &error);
4201 mono_error_assert_ok (&error);
4204 klass = mono_class_from_mono_type (t);
4205 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
4209 num_named = read16 (p);
4212 g_assert (num_named < 2);
4213 if (num_named == 1) {
4217 /* parse ExportSymbol attribute */
4219 named_type = *named;
4221 /* data_type = *named; */
4224 name_len = mono_metadata_decode_blob_size (named, &named);
4225 name = (char *)g_malloc (name_len + 1);
4226 memcpy (name, named, name_len);
4227 name [name_len] = 0;
4230 g_assert (named_type == 0x54);
4231 g_assert (!strcmp (name, "ExportSymbol"));
4233 /* load_cattr_value (), string case */
4234 g_assert (*named != (char)0xff);
4235 slen = mono_metadata_decode_value (named, &named);
4236 export_name = (char *)g_malloc (slen + 1);
4237 memcpy (export_name, named, slen);
4238 export_name [slen] = 0;
4242 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
4243 add_method (acfg, wrapper);
4245 g_hash_table_insert (acfg->export_names, wrapper, export_name);
4250 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4251 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
4252 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
4256 /* StructureToPtr/PtrToStructure wrappers */
4257 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4261 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4262 klass = mono_class_get_checked (acfg->image, token, &error);
4265 mono_error_cleanup (&error);
4269 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
4270 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
4271 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
4272 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
4278 has_type_vars (MonoClass *klass)
4280 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4283 return has_type_vars (klass->element_class);
4284 if (klass->generic_class) {
4285 MonoGenericContext *context = &klass->generic_class->context;
4286 if (context->class_inst) {
4289 for (i = 0; i < context->class_inst->type_argc; ++i)
4290 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
4294 if (klass->generic_container)
4300 is_vt_inst (MonoGenericInst *inst)
4304 for (i = 0; i < inst->type_argc; ++i) {
4305 MonoType *t = inst->type_argv [i];
4306 if (MONO_TYPE_ISSTRUCT (t) || t->type == MONO_TYPE_VALUETYPE)
4313 method_has_type_vars (MonoMethod *method)
4315 if (has_type_vars (method->klass))
4318 if (method->is_inflated) {
4319 MonoGenericContext *context = mono_method_get_context (method);
4320 if (context->method_inst) {
4323 for (i = 0; i < context->method_inst->type_argc; ++i)
4324 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
4332 gboolean mono_aot_mode_is_full (MonoAotOptions *opts)
4334 return opts->mode == MONO_AOT_MODE_FULL;
4338 gboolean mono_aot_mode_is_hybrid (MonoAotOptions *opts)
4340 return opts->mode == MONO_AOT_MODE_HYBRID;
4343 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
4346 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
4348 /* This might lead to a huge code blowup so only do it if neccesary */
4349 if (!mono_aot_mode_is_full (&acfg->aot_opts) && !mono_aot_mode_is_hybrid (&acfg->aot_opts) && !force)
4352 add_generic_class_with_depth (acfg, klass, 0, ref);
4356 check_type_depth (MonoType *t, int depth)
4364 case MONO_TYPE_GENERICINST: {
4365 MonoGenericClass *gklass = t->data.generic_class;
4366 MonoGenericInst *ginst = gklass->context.class_inst;
4369 for (i = 0; i < ginst->type_argc; ++i) {
4370 if (check_type_depth (ginst->type_argv [i], depth + 1))
4384 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method);
4387 * add_generic_class:
4389 * Add all methods of a generic class.
4392 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
4395 MonoClassField *field;
4397 gboolean use_gsharedvt = FALSE;
4399 if (!acfg->ginst_hash)
4400 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4402 mono_class_init (klass);
4404 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
4407 if (has_type_vars (klass))
4410 if (!klass->generic_class && !klass->rank)
4413 if (mono_class_has_failure (klass))
4416 if (!acfg->ginst_hash)
4417 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
4419 if (g_hash_table_lookup (acfg->ginst_hash, klass))
4422 if (check_type_depth (&klass->byval_arg, 0))
4425 if (acfg->aot_opts.log_generics)
4426 aot_printf (acfg, "%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
4428 g_hash_table_insert (acfg->ginst_hash, klass, klass);
4431 * Use gsharedvt for generic collections with vtype arguments to avoid code blowup.
4432 * Enable this only for some classes since gsharedvt might not support all methods.
4434 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) &&
4435 (!strcmp (klass->name, "Dictionary`2") || !strcmp (klass->name, "List`1") || !strcmp (klass->name, "ReadOnlyCollection`1")))
4436 use_gsharedvt = TRUE;
4439 while ((method = mono_class_get_methods (klass, &iter))) {
4440 if ((acfg->opts & MONO_OPT_GSHAREDVT) && method->is_inflated && mono_method_get_context (method)->method_inst) {
4442 * This is partial sharing, and we can't handle it yet
4447 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, use_gsharedvt)) {
4449 add_types_from_method_header (acfg, method);
4453 if (method->is_generic)
4458 * FIXME: Instances which are referenced by these methods are not added,
4459 * for example Array.Resize<int> for List<int>.Add ().
4461 add_extra_method_with_depth (acfg, method, depth + 1);
4465 while ((field = mono_class_get_fields (klass, &iter))) {
4466 if (field->type->type == MONO_TYPE_GENERICINST)
4467 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
4470 if (klass->delegate) {
4471 method = mono_get_delegate_invoke (klass);
4473 method = mono_marshal_get_delegate_invoke (method, NULL);
4475 if (acfg->aot_opts.log_generics)
4476 aot_printf (acfg, "%*sAdding method %s.\n", depth, "", mono_method_get_full_name (method));
4478 add_method (acfg, method);
4481 /* Add superclasses */
4483 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
4486 * For ICollection<T>, add instances of the helper methods
4487 * in Array, since a T[] could be cast to ICollection<T>.
4489 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
4490 (!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"))) {
4491 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4492 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
4496 if (!strcmp (klass->name, "IEnumerator`1"))
4497 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
4499 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
4501 /* Add the T[]/InternalEnumerator class */
4502 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
4507 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
4508 if (!strcmp (nclass->name, "InternalEnumerator`1"))
4512 nclass = mono_class_inflate_generic_class_checked (nclass, mono_generic_class_get_context (klass->generic_class), &error);
4513 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4514 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
4518 while ((method = mono_class_get_methods (array_class, &iter))) {
4519 if (strstr (method->name, name_prefix)) {
4520 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
4522 add_extra_method_with_depth (acfg, m, depth);
4526 g_free (name_prefix);
4529 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
4530 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4532 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4533 MonoClass *icomparable, *gcomparer, *icomparable_inst;
4534 MonoGenericContext ctx;
4535 MonoType *args [16];
4537 memset (&ctx, 0, sizeof (ctx));
4539 icomparable = mono_class_load_from_name (mono_defaults.corlib, "System", "IComparable`1");
4541 args [0] = &tclass->byval_arg;
4542 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4544 icomparable_inst = mono_class_inflate_generic_class_checked (icomparable, &ctx, &error);
4545 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4547 if (mono_class_is_assignable_from (icomparable_inst, tclass)) {
4548 MonoClass *gcomparer_inst;
4549 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
4550 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4551 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4553 add_generic_class (acfg, gcomparer_inst, FALSE, "Comparer<T>");
4557 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
4558 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4560 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4561 MonoClass *iface, *gcomparer, *iface_inst;
4562 MonoGenericContext ctx;
4563 MonoType *args [16];
4565 memset (&ctx, 0, sizeof (ctx));
4567 iface = mono_class_load_from_name (mono_defaults.corlib, "System", "IEquatable`1");
4569 args [0] = &tclass->byval_arg;
4570 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4572 iface_inst = mono_class_inflate_generic_class_checked (iface, &ctx, &error);
4573 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4575 if (mono_class_is_assignable_from (iface_inst, tclass)) {
4576 MonoClass *gcomparer_inst;
4579 gcomparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
4580 gcomparer_inst = mono_class_inflate_generic_class_checked (gcomparer, &ctx, &error);
4581 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4582 add_generic_class (acfg, gcomparer_inst, FALSE, "EqualityComparer<T>");
4586 /* Add an instance of EnumComparer<T> which is created dynamically by EqualityComparer<T> for enums */
4587 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
4588 MonoClass *enum_comparer;
4589 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4590 MonoGenericContext ctx;
4591 MonoType *args [16];
4593 if (mono_class_is_enum (tclass)) {
4594 MonoClass *enum_comparer_inst;
4597 memset (&ctx, 0, sizeof (ctx));
4598 args [0] = &tclass->byval_arg;
4599 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4601 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4602 enum_comparer_inst = mono_class_inflate_generic_class_checked (enum_comparer, &ctx, &error);
4603 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4604 add_generic_class (acfg, enum_comparer_inst, FALSE, "EqualityComparer<T>");
4608 /* Add an instance of ObjectComparer<T> which is created dynamically by Comparer<T> for enums */
4609 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
4610 MonoClass *comparer;
4611 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
4612 MonoGenericContext ctx;
4613 MonoType *args [16];
4615 if (mono_class_is_enum (tclass)) {
4616 MonoClass *comparer_inst;
4619 memset (&ctx, 0, sizeof (ctx));
4620 args [0] = &tclass->byval_arg;
4621 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4623 comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ObjectComparer`1");
4624 comparer_inst = mono_class_inflate_generic_class_checked (comparer, &ctx, &error);
4625 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4626 add_generic_class (acfg, comparer_inst, FALSE, "Comparer<T>");
4632 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
4635 MonoGenericContext ctx;
4636 MonoType *args [16];
4638 if (acfg->aot_opts.no_instances)
4641 memset (&ctx, 0, sizeof (ctx));
4643 for (i = 0; i < ninsts; ++i) {
4645 MonoClass *generic_inst;
4646 args [0] = insts [i];
4647 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
4648 generic_inst = mono_class_inflate_generic_class_checked (klass, &ctx, &error);
4649 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
4650 add_generic_class (acfg, generic_inst, force, "");
4655 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
4658 MonoMethodHeader *header;
4659 MonoMethodSignature *sig;
4662 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4664 sig = mono_method_signature (method);
4667 for (j = 0; j < sig->param_count; ++j)
4668 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
4669 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
4672 header = mono_method_get_header_checked (method, &error);
4675 for (j = 0; j < header->num_locals; ++j)
4676 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
4677 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
4678 mono_metadata_free_mh (header);
4680 mono_error_cleanup (&error); /* FIXME report the error */
4686 * add_generic_instances:
4688 * Add instances referenced by the METHODSPEC/TYPESPEC table.
4691 add_generic_instances (MonoAotCompile *acfg)
4696 MonoGenericContext *context;
4698 if (acfg->aot_opts.no_instances)
4701 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
4703 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
4704 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
4707 aot_printerrf (acfg, "Failed to load methodspec 0x%x due to %s.\n", token, mono_error_get_message (&error));
4708 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
4709 mono_error_cleanup (&error);
4713 if (method->klass->image != acfg->image)
4716 context = mono_method_get_context (method);
4718 if (context && ((context->class_inst && context->class_inst->is_open)))
4722 * For open methods, create an instantiation which can be passed to the JIT.
4723 * FIXME: Handle class_inst as well.
4725 if (context && context->method_inst && context->method_inst->is_open) {
4727 MonoGenericContext shared_context;
4728 MonoGenericInst *inst;
4729 MonoType **type_argv;
4731 MonoMethod *declaring_method;
4732 gboolean supported = TRUE;
4734 /* Check that the context doesn't contain open constructed types */
4735 if (context->class_inst) {
4736 inst = context->class_inst;
4737 for (i = 0; i < inst->type_argc; ++i) {
4738 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)
4740 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4744 if (context->method_inst) {
4745 inst = context->method_inst;
4746 for (i = 0; i < inst->type_argc; ++i) {
4747 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)
4749 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
4757 memset (&shared_context, 0, sizeof (MonoGenericContext));
4759 inst = context->class_inst;
4761 type_argv = g_new0 (MonoType*, inst->type_argc);
4762 for (i = 0; i < inst->type_argc; ++i) {
4763 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)
4764 type_argv [i] = &mono_defaults.object_class->byval_arg;
4766 type_argv [i] = inst->type_argv [i];
4769 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4773 inst = context->method_inst;
4775 type_argv = g_new0 (MonoType*, inst->type_argc);
4776 for (i = 0; i < inst->type_argc; ++i) {
4777 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)
4778 type_argv [i] = &mono_defaults.object_class->byval_arg;
4780 type_argv [i] = inst->type_argv [i];
4783 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4787 if (method->is_generic || method->klass->generic_container)
4788 declaring_method = method;
4790 declaring_method = mono_method_get_declaring_generic_method (method);
4792 method = mono_class_inflate_generic_method_checked (declaring_method, &shared_context, &error);
4793 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4797 * If the method is fully sharable, it was already added in place of its
4798 * generic definition.
4800 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
4804 * FIXME: Partially shared methods are not shared here, so we end up with
4805 * many identical methods.
4807 add_extra_method (acfg, method);
4810 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4814 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4816 klass = mono_class_get_checked (acfg->image, token, &error);
4817 if (!klass || klass->rank) {
4818 mono_error_cleanup (&error);
4822 add_generic_class (acfg, klass, FALSE, "typespec");
4825 /* Add types of args/locals */
4826 for (i = 0; i < acfg->methods->len; ++i) {
4827 method = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
4828 add_types_from_method_header (acfg, method);
4831 if (acfg->image == mono_defaults.corlib) {
4833 MonoType *insts [256];
4836 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4837 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4838 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4839 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4840 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4841 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4842 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4843 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4844 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4845 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4846 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4847 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4849 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4850 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4852 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4853 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4855 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4857 /* Add instances of EnumEqualityComparer which are created by EqualityComparer<T> for enums */
4859 MonoClass *enum_comparer;
4860 MonoType *insts [16];
4864 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4865 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4866 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4867 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4868 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "EnumEqualityComparer`1");
4869 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4872 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4873 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "ShortEnumEqualityComparer`1");
4874 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4877 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4878 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "SByteEnumEqualityComparer`1");
4879 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4881 enum_comparer = mono_class_load_from_name (mono_defaults.corlib, "System.Collections.Generic", "LongEnumEqualityComparer`1");
4883 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4884 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4885 add_instances_of (acfg, enum_comparer, insts, ninsts, FALSE);
4888 /* Add instances of the array generic interfaces for primitive types */
4889 /* This will add instances of the InternalArray_ helper methods in Array too */
4890 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4892 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4894 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4896 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4898 klass = mono_class_try_load_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4900 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4903 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4904 * used for all instances of GetGenericValueImpl by the AOT runtime.
4907 MonoGenericContext ctx;
4908 MonoType *args [16];
4909 MonoMethod *get_method;
4910 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4912 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4916 memset (&ctx, 0, sizeof (ctx));
4917 args [0] = &mono_defaults.object_class->byval_arg;
4918 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4919 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (get_method, &ctx, &error), TRUE, TRUE));
4920 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4924 /* Same for CompareExchange<T>/Exchange<T> */
4926 MonoGenericContext ctx;
4927 MonoType *args [16];
4929 MonoClass *interlocked_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4930 gpointer iter = NULL;
4932 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4933 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4935 memset (&ctx, 0, sizeof (ctx));
4936 args [0] = &mono_defaults.object_class->byval_arg;
4937 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4938 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4939 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4944 /* Same for Volatile.Read/Write<T> */
4946 MonoGenericContext ctx;
4947 MonoType *args [16];
4949 MonoClass *volatile_klass = mono_class_try_load_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4950 gpointer iter = NULL;
4952 if (volatile_klass) {
4953 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4954 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4956 memset (&ctx, 0, sizeof (ctx));
4957 args [0] = &mono_defaults.object_class->byval_arg;
4958 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4959 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method_checked (m, &ctx, &error), TRUE, TRUE));
4960 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
4966 /* object[] accessor wrappers. */
4967 for (i = 1; i < 4; ++i) {
4968 MonoClass *obj_array_class = mono_array_class_get (mono_defaults.object_class, i);
4971 m = mono_class_get_method_from_name (obj_array_class, "Get", i);
4974 m = mono_marshal_get_array_accessor_wrapper (m);
4975 add_extra_method (acfg, m);
4977 m = mono_class_get_method_from_name (obj_array_class, "Address", i);
4980 m = mono_marshal_get_array_accessor_wrapper (m);
4981 add_extra_method (acfg, m);
4983 m = mono_class_get_method_from_name (obj_array_class, "Set", i + 1);
4986 m = mono_marshal_get_array_accessor_wrapper (m);
4987 add_extra_method (acfg, m);
4993 * is_direct_callable:
4995 * Return whenever the method identified by JI is directly callable without
4996 * going through the PLT.
4999 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
5001 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5002 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5004 gboolean direct_callable = TRUE;
5006 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
5007 direct_callable = FALSE;
5008 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
5009 // FIXME: Maybe call the wrapper directly ?
5010 direct_callable = FALSE;
5012 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
5013 /* Disable this so all calls go through load_method (), see the
5014 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
5015 * mono_debugger_agent_init ().
5017 direct_callable = FALSE;
5020 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_ALLOC)
5021 /* sgen does some initialization when the allocator method is created */
5022 direct_callable = FALSE;
5023 if (callee_cfg->method->wrapper_type == MONO_WRAPPER_WRITE_BARRIER)
5024 /* we don't know at compile time whether sgen is concurrent or not */
5025 direct_callable = FALSE;
5027 if (direct_callable)
5030 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5031 if (acfg->aot_opts.direct_pinvoke)
5033 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5034 if (acfg->aot_opts.direct_icalls)
5042 #ifdef MONO_ARCH_AOT_SUPPORTED
5044 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5046 MonoImage *image = method->klass->image;
5047 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
5048 MonoTableInfo *tables = image->tables;
5049 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
5050 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
5051 guint32 im_cols [MONO_IMPLMAP_SIZE];
5054 import = (char *)g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
5058 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
5061 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
5063 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
5066 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
5068 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
5074 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
5081 compare_lne (MonoDebugLineNumberEntry *a, MonoDebugLineNumberEntry *b)
5083 if (a->native_offset == b->native_offset)
5084 return a->il_offset - b->il_offset;
5086 return a->native_offset - b->native_offset;
5090 * compute_line_numbers:
5092 * Returns a sparse array of size CODE_SIZE containing MonoDebugSourceLocation* entries for the native offsets which have a corresponding line number
5095 static MonoDebugSourceLocation**
5096 compute_line_numbers (MonoMethod *method, int code_size, MonoDebugMethodJitInfo *debug_info)
5098 MonoDebugMethodInfo *minfo;
5099 MonoDebugLineNumberEntry *ln_array;
5100 MonoDebugSourceLocation *loc;
5101 int i, prev_line, prev_il_offset;
5102 int *native_to_il_offset = NULL;
5103 MonoDebugSourceLocation **res;
5106 minfo = mono_debug_lookup_method (method);
5109 // FIXME: This seems to happen when two methods have the same cfg->method_to_register
5110 if (debug_info->code_size != code_size)
5113 g_assert (code_size);
5115 /* Compute the native->IL offset mapping */
5117 ln_array = g_new0 (MonoDebugLineNumberEntry, debug_info->num_line_numbers);
5118 memcpy (ln_array, debug_info->line_numbers, debug_info->num_line_numbers * sizeof (MonoDebugLineNumberEntry));
5120 qsort (ln_array, debug_info->num_line_numbers, sizeof (MonoDebugLineNumberEntry), (int (*)(const void *, const void *))compare_lne);
5122 native_to_il_offset = g_new0 (int, code_size + 1);
5124 for (i = 0; i < debug_info->num_line_numbers; ++i) {
5126 MonoDebugLineNumberEntry *lne = &ln_array [i];
5129 for (j = 0; j < lne->native_offset; ++j)
5130 native_to_il_offset [j] = -1;
5133 if (i < debug_info->num_line_numbers - 1) {
5134 MonoDebugLineNumberEntry *lne_next = &ln_array [i + 1];
5136 for (j = lne->native_offset; j < lne_next->native_offset; ++j)
5137 native_to_il_offset [j] = lne->il_offset;
5139 for (j = lne->native_offset; j < code_size; ++j)
5140 native_to_il_offset [j] = lne->il_offset;
5145 /* Compute the native->line number mapping */
5146 res = g_new0 (MonoDebugSourceLocation*, code_size);
5147 prev_il_offset = -1;
5150 for (i = 0; i < code_size; ++i) {
5151 int il_offset = native_to_il_offset [i];
5153 if (il_offset == -1 || il_offset == prev_il_offset)
5155 prev_il_offset = il_offset;
5156 loc = mono_debug_symfile_lookup_location (minfo, il_offset);
5157 if (!(loc && loc->source_file))
5159 if (loc->row == prev_line) {
5160 mono_debug_symfile_free_location (loc);
5163 prev_line = loc->row;
5164 //printf ("D: %s:%d il=%x native=%x\n", loc->source_file, loc->row, il_offset, i);
5166 /* This will cover the prolog too */
5176 get_file_index (MonoAotCompile *acfg, const char *source_file)
5180 // FIXME: Free these
5181 if (!acfg->dwarf_ln_filenames)
5182 acfg->dwarf_ln_filenames = g_hash_table_new (g_str_hash, g_str_equal);
5183 findex = GPOINTER_TO_INT (g_hash_table_lookup (acfg->dwarf_ln_filenames, source_file));
5185 findex = g_hash_table_size (acfg->dwarf_ln_filenames) + 1;
5186 g_hash_table_insert (acfg->dwarf_ln_filenames, g_strdup (source_file), GINT_TO_POINTER (findex));
5187 emit_unset_mode (acfg);
5188 fprintf (acfg->fp, ".file %d \"%s\"\n", findex, mono_dwarf_escape_path (source_file));
5200 * emit_and_reloc_code:
5202 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
5203 * is true, calls are made through the GOT too. This is used for emitting trampolines
5204 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
5205 * since trampolines are needed to make PTL work.
5208 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only, MonoDebugMethodJitInfo *debug_info)
5210 int i, pindex, start_index;
5212 MonoJumpInfo *patch_info;
5213 MonoDebugSourceLocation **locs = NULL;
5214 gboolean skip, prologue_end = FALSE;
5215 #ifdef MONO_ARCH_AOT_SUPPORTED
5216 gboolean direct_call, external_call;
5218 const char *direct_call_target = 0;
5219 const char *direct_pinvoke;
5222 if (acfg->gas_line_numbers && method && debug_info) {
5223 locs = compute_line_numbers (method, code_len, debug_info);
5225 int findex = get_file_index (acfg, "<unknown>");
5226 emit_unset_mode (acfg);
5227 fprintf (acfg->fp, ".loc %d %d 0\n", findex, 1);
5231 /* Collect and sort relocations */
5232 patches = g_ptr_array_new ();
5233 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
5234 g_ptr_array_add (patches, patch_info);
5235 g_ptr_array_sort (patches, compare_patches);
5238 for (i = 0; i < code_len; i += INST_LEN) {
5240 for (pindex = start_index; pindex < patches->len; ++pindex) {
5241 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5242 if (patch_info->ip.i >= i)
5246 if (locs && locs [i]) {
5247 MonoDebugSourceLocation *loc = locs [i];
5249 const char *options;
5251 findex = get_file_index (acfg, loc->source_file);
5252 emit_unset_mode (acfg);
5254 options = " prologue_end";
5257 prologue_end = TRUE;
5258 fprintf (acfg->fp, ".loc %d %d 0%s\n", findex, loc->row, options);
5259 mono_debug_symfile_free_location (loc);
5263 #ifdef MONO_ARCH_AOT_SUPPORTED
5264 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
5265 start_index = pindex;
5267 switch (patch_info->type) {
5268 case MONO_PATCH_INFO_NONE:
5270 case MONO_PATCH_INFO_GOT_OFFSET: {
5273 arch_emit_got_offset (acfg, code + i, &code_size);
5274 i += code_size - INST_LEN;
5276 patch_info->type = MONO_PATCH_INFO_NONE;
5279 case MONO_PATCH_INFO_OBJC_SELECTOR_REF: {
5280 int code_size, index;
5281 char *selector = (char *)patch_info->data.target;
5283 if (!acfg->objc_selector_to_index)
5284 acfg->objc_selector_to_index = g_hash_table_new (g_str_hash, g_str_equal);
5285 if (!acfg->objc_selectors)
5286 acfg->objc_selectors = g_ptr_array_new ();
5287 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->objc_selector_to_index, selector));
5291 index = acfg->objc_selector_index;
5292 g_ptr_array_add (acfg->objc_selectors, (void*)patch_info->data.target);
5293 g_hash_table_insert (acfg->objc_selector_to_index, selector, GUINT_TO_POINTER (index + 1));
5294 acfg->objc_selector_index ++;
5297 arch_emit_objc_selector_ref (acfg, code + i, index, &code_size);
5298 i += code_size - INST_LEN;
5300 patch_info->type = MONO_PATCH_INFO_NONE;
5305 * If this patch is a call, try emitting a direct call instead of
5306 * through a PLT entry. This is possible if the called method is in
5307 * the same assembly and requires no initialization.
5309 direct_call = FALSE;
5310 external_call = FALSE;
5311 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
5312 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5313 MonoCompile *callee_cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
5314 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
5316 direct_call_target = callee_cfg->asm_symbol;
5317 patch_info->type = MONO_PATCH_INFO_NONE;
5318 acfg->stats.direct_calls ++;
5321 acfg->stats.all_calls ++;
5322 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
5323 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
5324 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5325 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
5327 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
5328 if (direct_pinvoke) {
5330 g_assert (strlen (direct_pinvoke) < 1000);
5331 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
5334 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
5335 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5336 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
5337 /* Call to a C function implementing a jit icall */
5339 external_call = TRUE;
5340 g_assert (strlen (sym) < 1000);
5341 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5343 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
5344 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
5345 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
5346 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
5347 /* Call to a jit icall without a wrapper */
5349 external_call = TRUE;
5350 g_assert (strlen (sym) < 1000);
5351 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
5356 patch_info->type = MONO_PATCH_INFO_NONE;
5357 acfg->stats.direct_calls ++;
5360 if (!got_only && !direct_call) {
5361 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
5363 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
5365 direct_call_target = plt_entry->symbol;
5367 /* Nullify the patch */
5368 patch_info->type = MONO_PATCH_INFO_NONE;
5369 plt_entry->jit_used = TRUE;
5376 arch_emit_direct_call (acfg, direct_call_target, external_call, FALSE, patch_info, &call_size);
5377 i += call_size - INST_LEN;
5381 got_slot = get_got_offset (acfg, FALSE, patch_info);
5383 arch_emit_got_access (acfg, acfg->got_symbol, code + i, got_slot, &code_size);
5384 i += code_size - INST_LEN;
5390 #endif /* MONO_ARCH_AOT_SUPPORTED */
5393 /* Find next patch */
5395 for (pindex = start_index; pindex < patches->len; ++pindex) {
5396 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5397 if (patch_info->ip.i >= i)
5401 /* Try to emit multiple bytes at once */
5402 if (pindex < patches->len && patch_info->ip.i > i) {
5405 for (limit = i + INST_LEN; limit < patch_info->ip.i; limit += INST_LEN) {
5406 if (locs && locs [limit])
5410 emit_code_bytes (acfg, code + i, limit - i);
5411 i = limit - INST_LEN;
5413 emit_code_bytes (acfg, code + i, INST_LEN);
5418 g_ptr_array_free (patches, TRUE);
5425 * Return a modified version of S which only includes characters permissible in symbols.
5428 sanitize_symbol (MonoAotCompile *acfg, char *s)
5430 gboolean process = FALSE;
5439 for (i = 0; i < len; ++i)
5440 if (!(s [i] <= 0x7f && (isalnum (s [i]) || s [i] == '_')))
5445 gs = g_string_sized_new (len);
5446 for (i = 0; i < len; ++i) {
5448 if (c <= 0x7f && (isalnum (c) || c == '_')) {
5449 g_string_append_c (gs, c);
5450 } else if (c > 0x7f) {
5451 /* multi-byte utf8 */
5452 g_string_append_printf (gs, "_0x%x", c);
5455 while (c >> 6 == 0x2) {
5456 g_string_append_printf (gs, "%x", c);
5460 g_string_append_printf (gs, "_");
5463 g_string_append_c (gs, '_');
5467 res = mono_mempool_strdup (acfg->mempool, gs->str);
5468 g_string_free (gs, TRUE);
5473 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
5475 char *name1, *name2, *cached;
5476 int i, j, len, count;
5477 MonoMethod *cached_method;
5479 name1 = mono_method_full_name (method, TRUE);
5482 // This is so that we don't accidentally create a local symbol (which starts with 'L')
5483 if ((!prefix || !*prefix) && name1 [0] == 'L')
5487 #if defined(TARGET_WIN32) && defined(TARGET_X86)
5488 char adjustedPrefix [MAX_SYMBOL_SIZE];
5489 prefix = mangle_symbol (prefix, adjustedPrefix, G_N_ELEMENTS (adjustedPrefix));
5492 len = strlen (name1);
5493 name2 = (char *)malloc (strlen (prefix) + len + 16);
5494 memcpy (name2, prefix, strlen (prefix));
5495 j = strlen (prefix);
5496 for (i = 0; i < len; ++i) {
5497 if (i == 0 && name1 [0] >= '0' && name1 [0] <= '9') {
5499 } else if (isalnum (name1 [i])) {
5500 name2 [j ++] = name1 [i];
5501 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
5503 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
5506 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
5516 cached_method = (MonoMethod *)g_hash_table_lookup (cache, name2);
5517 if (!(cached_method && cached_method != method))
5519 sprintf (name2 + j, "_%d", count);
5523 cached = g_strdup (name2);
5524 g_hash_table_insert (cache, cached, method);
5530 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
5535 char *debug_sym = NULL;
5536 char *symbol = NULL;
5537 int func_alignment = AOT_FUNC_ALIGNMENT;
5540 method = cfg->orig_method;
5541 code = cfg->native_code;
5543 method_index = get_method_index (acfg, method);
5544 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
5546 /* Make the labels local */
5547 emit_section_change (acfg, ".text", 0);
5548 emit_alignment_code (acfg, func_alignment);
5550 if (acfg->global_symbols && acfg->need_no_dead_strip)
5551 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
5553 emit_label (acfg, cfg->asm_symbol);
5555 if (acfg->aot_opts.write_symbols && !acfg->global_symbols && !acfg->llvm) {
5557 * Write a C style symbol for every method, this has two uses:
5558 * - it works on platforms where the dwarf debugging info is not
5560 * - it allows the setting of breakpoints of aot-ed methods.
5562 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
5563 cfg->asm_debug_symbol = g_strdup (debug_sym);
5565 if (acfg->need_no_dead_strip)
5566 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5567 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
5568 emit_label (acfg, debug_sym);
5571 export_name = (char *)g_hash_table_lookup (acfg->export_names, method);
5573 /* Emit a global symbol for the method */
5574 emit_global_inner (acfg, export_name, TRUE);
5575 emit_label (acfg, export_name);
5578 if (cfg->verbose_level > 0)
5579 g_print ("Method %s emitted as %s\n", mono_method_get_full_name (method), cfg->asm_symbol);
5581 acfg->stats.code_size += cfg->code_len;
5583 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
5585 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 ()));
5589 if (acfg->aot_opts.write_symbols) {
5591 emit_symbol_size (acfg, debug_sym, ".");
5593 emit_symbol_size (acfg, cfg->asm_symbol, ".");
5597 emit_label (acfg, symbol);
5604 * Encode PATCH_INFO into its disk representation.
5607 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
5611 switch (patch_info->type) {
5612 case MONO_PATCH_INFO_NONE:
5614 case MONO_PATCH_INFO_IMAGE:
5615 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
5617 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
5618 case MONO_PATCH_INFO_JIT_TLS_ID:
5619 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5620 case MONO_PATCH_INFO_GC_NURSERY_START:
5621 case MONO_PATCH_INFO_GC_NURSERY_BITS:
5623 case MONO_PATCH_INFO_CASTCLASS_CACHE:
5624 encode_value (patch_info->data.index, p, &p);
5626 case MONO_PATCH_INFO_METHOD_REL:
5627 encode_value ((gint)patch_info->data.offset, p, &p);
5629 case MONO_PATCH_INFO_SWITCH: {
5630 gpointer *table = (gpointer *)patch_info->data.table->table;
5633 encode_value (patch_info->data.table->table_size, p, &p);
5634 for (k = 0; k < patch_info->data.table->table_size; k++)
5635 encode_value ((int)(gssize)table [k], p, &p);
5638 case MONO_PATCH_INFO_METHODCONST:
5639 case MONO_PATCH_INFO_METHOD:
5640 case MONO_PATCH_INFO_METHOD_JUMP:
5641 case MONO_PATCH_INFO_ICALL_ADDR:
5642 case MONO_PATCH_INFO_ICALL_ADDR_CALL:
5643 case MONO_PATCH_INFO_METHOD_RGCTX:
5644 case MONO_PATCH_INFO_METHOD_CODE_SLOT:
5645 encode_method_ref (acfg, patch_info->data.method, p, &p);
5647 case MONO_PATCH_INFO_AOT_JIT_INFO:
5648 encode_value (patch_info->data.index, p, &p);
5650 case MONO_PATCH_INFO_INTERNAL_METHOD:
5651 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
5652 guint32 len = strlen (patch_info->data.name);
5654 encode_value (len, p, &p);
5656 memcpy (p, patch_info->data.name, len);
5661 case MONO_PATCH_INFO_LDSTR: {
5662 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
5663 guint32 token = patch_info->data.token->token;
5664 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
5665 encode_value (image_index, p, &p);
5666 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
5669 case MONO_PATCH_INFO_RVA:
5670 case MONO_PATCH_INFO_DECLSEC:
5671 case MONO_PATCH_INFO_LDTOKEN:
5672 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
5673 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
5674 encode_value (patch_info->data.token->token, p, &p);
5675 encode_value (patch_info->data.token->has_context, p, &p);
5676 if (patch_info->data.token->has_context)
5677 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
5679 case MONO_PATCH_INFO_EXC_NAME: {
5680 MonoClass *ex_class;
5683 mono_class_load_from_name (mono_defaults.exception_class->image,
5684 "System", (const char *)patch_info->data.target);
5685 encode_klass_ref (acfg, ex_class, p, &p);
5688 case MONO_PATCH_INFO_R4:
5689 encode_value (*((guint32 *)patch_info->data.target), p, &p);
5691 case MONO_PATCH_INFO_R8:
5692 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
5693 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
5695 case MONO_PATCH_INFO_VTABLE:
5696 case MONO_PATCH_INFO_CLASS:
5697 case MONO_PATCH_INFO_IID:
5698 case MONO_PATCH_INFO_ADJUSTED_IID:
5699 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
5701 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5702 encode_klass_ref (acfg, patch_info->data.del_tramp->klass, p, &p);
5703 if (patch_info->data.del_tramp->method) {
5704 encode_value (1, p, &p);
5705 encode_method_ref (acfg, patch_info->data.del_tramp->method, p, &p);
5707 encode_value (0, p, &p);
5709 encode_value (patch_info->data.del_tramp->is_virtual, p, &p);
5711 case MONO_PATCH_INFO_FIELD:
5712 case MONO_PATCH_INFO_SFLDA:
5713 encode_field_info (acfg, patch_info->data.field, p, &p);
5715 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
5717 case MONO_PATCH_INFO_RGCTX_FETCH:
5718 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
5719 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5724 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
5725 * reference the same method, so encode the method only once.
5727 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
5729 buf2 = (guint8 *)g_malloc (1024);
5732 encode_method_ref (acfg, entry->method, p2, &p2);
5733 g_assert (p2 - buf2 < 1024);
5735 offset = add_to_blob (acfg, buf2, p2 - buf2);
5738 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
5743 encode_value (offset, p, &p);
5744 g_assert ((int)entry->info_type < 256);
5745 g_assert (entry->data->type < 256);
5746 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
5747 encode_patch (acfg, entry->data, p, &p);
5750 case MONO_PATCH_INFO_SEQ_POINT_INFO:
5751 case MONO_PATCH_INFO_AOT_MODULE:
5753 case MONO_PATCH_INFO_SIGNATURE:
5754 case MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER:
5755 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
5757 case MONO_PATCH_INFO_TLS_OFFSET:
5758 encode_value (GPOINTER_TO_INT (patch_info->data.target), p, &p);
5760 case MONO_PATCH_INFO_GSHAREDVT_CALL:
5761 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
5762 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
5764 case MONO_PATCH_INFO_GSHAREDVT_METHOD: {
5765 MonoGSharedVtMethodInfo *info = patch_info->data.gsharedvt_method;
5768 encode_method_ref (acfg, info->method, p, &p);
5769 encode_value (info->num_entries, p, &p);
5770 for (i = 0; i < info->num_entries; ++i) {
5771 MonoRuntimeGenericContextInfoTemplate *template_ = &info->entries [i];
5773 encode_value (template_->info_type, p, &p);
5774 switch (mini_rgctx_info_type_to_patch_info_type (template_->info_type)) {
5775 case MONO_PATCH_INFO_CLASS:
5776 encode_klass_ref (acfg, mono_class_from_mono_type ((MonoType *)template_->data), p, &p);
5778 case MONO_PATCH_INFO_FIELD:
5779 encode_field_info (acfg, (MonoClassField *)template_->data, p, &p);
5782 g_assert_not_reached ();
5788 case MONO_PATCH_INFO_LDSTR_LIT: {
5789 const char *s = (const char *)patch_info->data.target;
5790 int len = strlen (s);
5792 encode_value (len, p, &p);
5793 memcpy (p, s, len + 1);
5797 case MONO_PATCH_INFO_VIRT_METHOD:
5798 encode_klass_ref (acfg, patch_info->data.virt_method->klass, p, &p);
5799 encode_method_ref (acfg, patch_info->data.virt_method->method, p, &p);
5801 case MONO_PATCH_INFO_GC_SAFE_POINT_FLAG:
5804 g_warning ("unable to handle jump info %d", patch_info->type);
5805 g_assert_not_reached ();
5812 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, gboolean llvm, int first_got_offset, guint8 *buf, guint8 **endbuf)
5815 guint32 pindex, offset;
5816 MonoJumpInfo *patch_info;
5818 encode_value (n_patches, p, &p);
5820 for (pindex = 0; pindex < patches->len; ++pindex) {
5821 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5823 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
5827 offset = get_got_offset (acfg, llvm, patch_info);
5828 encode_value (offset, p, &p);
5835 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
5838 int pindex, buf_size, n_patches;
5840 MonoJumpInfo *patch_info;
5841 guint32 method_index;
5843 guint32 first_got_offset;
5845 method = cfg->orig_method;
5847 method_index = get_method_index (acfg, method);
5849 /* Sort relocations */
5850 patches = g_ptr_array_new ();
5851 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
5852 g_ptr_array_add (patches, patch_info);
5853 g_ptr_array_sort (patches, compare_patches);
5855 first_got_offset = acfg->cfgs [method_index]->got_offset;
5857 /**********************/
5858 /* Encode method info */
5859 /**********************/
5861 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
5862 p = buf = (guint8 *)g_malloc (buf_size);
5864 if (mono_class_get_cctor (method->klass)) {
5865 encode_value (1, p, &p);
5866 encode_klass_ref (acfg, method->klass, p, &p);
5868 /* Not needed when loading the method */
5869 encode_value (0, p, &p);
5872 g_assert (!(cfg->opt & MONO_OPT_SHARED));
5875 for (pindex = 0; pindex < patches->len; ++pindex) {
5876 patch_info = (MonoJumpInfo *)g_ptr_array_index (patches, pindex);
5878 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
5879 (patch_info->type == MONO_PATCH_INFO_NONE)) {
5880 patch_info->type = MONO_PATCH_INFO_NONE;
5885 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
5886 /* Stored in a GOT slot initialized at module load time */
5887 patch_info->type = MONO_PATCH_INFO_NONE;
5891 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR ||
5892 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_START ||
5893 patch_info->type == MONO_PATCH_INFO_GC_NURSERY_BITS ||
5894 patch_info->type == MONO_PATCH_INFO_AOT_MODULE) {
5895 /* Stored in a GOT slot initialized at module load time */
5896 patch_info->type = MONO_PATCH_INFO_NONE;
5900 if (is_plt_patch (patch_info) && !(cfg->compile_llvm && acfg->aot_opts.llvm_only)) {
5901 /* Calls are made through the PLT */
5902 patch_info->type = MONO_PATCH_INFO_NONE;
5910 g_assert (cfg->has_got_slots);
5912 encode_patch_list (acfg, patches, n_patches, cfg->compile_llvm, first_got_offset, p, &p);
5914 g_ptr_array_free (patches, TRUE);
5916 acfg->stats.info_size += p - buf;
5918 g_assert (p - buf < buf_size);
5920 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
5925 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
5927 guint32 cache_index;
5930 /* Reuse the unwind module to canonize and store unwind info entries */
5931 cache_index = mono_cache_unwind_info (encoded, encoded_len);
5933 /* Use +/- 1 to distinguish 0s from missing entries */
5934 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
5942 * It would be easier to use assembler symbols, but the caller needs an
5945 offset = acfg->unwind_info_offset;
5946 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
5947 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
5950 encode_value (encoded_len, p, &p);
5952 acfg->unwind_info_offset += encoded_len + (p - buf);
5958 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg, gboolean store_seq_points)
5961 guint32 debug_info_size, seq_points_size;
5963 MonoMethodHeader *header;
5964 guint8 *p, *buf, *debug_info;
5965 MonoJitInfo *jinfo = cfg->jit_info;
5967 gboolean use_unwind_ops = FALSE;
5968 MonoSeqPointInfo *seq_points;
5970 code = cfg->native_code;
5971 header = cfg->header;
5973 if (!acfg->aot_opts.nodebug) {
5974 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
5977 debug_info_size = 0;
5980 seq_points = cfg->seq_point_info;
5981 seq_points_size = (store_seq_points)? mono_seq_point_info_get_write_size (seq_points) : 0;
5983 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + seq_points_size + cfg->gc_map_size;
5985 p = buf = (guint8 *)g_malloc (buf_size);
5987 use_unwind_ops = cfg->unwind_ops != NULL;
5989 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);
5991 encode_value (flags, p, &p);
5993 if (use_unwind_ops) {
5994 guint32 encoded_len;
5996 guint32 unwind_desc;
5998 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
6000 unwind_desc = get_unwind_info_offset (acfg, encoded, encoded_len);
6001 encode_value (unwind_desc, p, &p);
6005 encode_value (jinfo->unwind_info, p, &p);
6008 /*Encode the number of holes before the number of clauses to make decoding easier*/
6009 if (jinfo->has_try_block_holes) {
6010 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6011 encode_value (table->num_holes, p, &p);
6014 if (jinfo->has_arch_eh_info) {
6016 * In AOT mode, the code length is calculated from the address of the previous method,
6017 * which could include alignment padding, so calculating the start of the epilog as
6018 * code_len - epilog_size is correct any more. Save the real code len as a workaround.
6020 encode_value (jinfo->code_size, p, &p);
6023 /* Exception table */
6024 if (cfg->compile_llvm) {
6026 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
6027 * since the information is only available to llc. Instead, we let llc save the data
6028 * into the LSDA, and read it from there at runtime.
6030 /* The assembly might be CIL stripped so emit the data ourselves */
6031 if (header->num_clauses)
6032 encode_value (header->num_clauses, p, &p);
6034 for (k = 0; k < header->num_clauses; ++k) {
6035 MonoExceptionClause *clause;
6037 clause = &header->clauses [k];
6039 encode_value (clause->flags, p, &p);
6040 if (clause->data.catch_class) {
6041 encode_value (1, p, &p);
6042 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
6044 encode_value (0, p, &p);
6047 /* Emit the IL ranges too, since they might not be available at runtime */
6048 encode_value (clause->try_offset, p, &p);
6049 encode_value (clause->try_len, p, &p);
6050 encode_value (clause->handler_offset, p, &p);
6051 encode_value (clause->handler_len, p, &p);
6053 /* Emit a list of nesting clauses */
6054 for (i = 0; i < header->num_clauses; ++i) {
6056 MonoExceptionClause *clause1 = &header->clauses [cindex1];
6058 MonoExceptionClause *clause2 = &header->clauses [cindex2];
6060 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
6061 encode_value (i, p, &p);
6063 encode_value (-1, p, &p);
6066 if (jinfo->num_clauses)
6067 encode_value (jinfo->num_clauses, p, &p);
6069 for (k = 0; k < jinfo->num_clauses; ++k) {
6070 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
6072 encode_value (ei->flags, p, &p);
6073 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
6074 /* Not used for catch clauses */
6075 if (ei->flags != MONO_EXCEPTION_CLAUSE_NONE)
6076 encode_value (ei->exvar_offset, p, &p);
6078 encode_value (ei->exvar_offset, p, &p);
6081 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
6082 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
6084 if (ei->data.catch_class) {
6088 buf2 = (guint8 *)g_malloc (4096);
6090 encode_klass_ref (acfg, ei->data.catch_class, p2, &p2);
6092 g_assert (len < 4096);
6093 encode_value (len, p, &p);
6094 memcpy (p, buf2, len);
6098 encode_value (0, p, &p);
6102 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
6103 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
6104 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
6108 if (jinfo->has_try_block_holes) {
6109 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
6110 for (i = 0; i < table->num_holes; ++i) {
6111 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
6112 encode_value (hole->clause, p, &p);
6113 encode_value (hole->length, p, &p);
6114 encode_value (hole->offset, p, &p);
6118 if (jinfo->has_arch_eh_info) {
6119 MonoArchEHJitInfo *eh_info;
6121 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
6122 encode_value (eh_info->stack_size, p, &p);
6123 encode_value (eh_info->epilog_size, p, &p);
6126 if (jinfo->has_generic_jit_info) {
6127 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
6128 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
6132 encode_value (gi->nlocs, p, &p);
6134 for (i = 0; i < gi->nlocs; ++i) {
6135 MonoDwarfLocListEntry *entry = &gi->locations [i];
6137 encode_value (entry->is_reg ? 1 : 0, p, &p);
6138 encode_value (entry->reg, p, &p);
6140 encode_value (entry->offset, p, &p);
6142 g_assert (entry->from == 0);
6144 encode_value (entry->from, p, &p);
6145 encode_value (entry->to, p, &p);
6148 if (!cfg->compile_llvm) {
6149 encode_value (gi->has_this ? 1 : 0, p, &p);
6150 encode_value (gi->this_reg, p, &p);
6151 encode_value (gi->this_offset, p, &p);
6156 * Need to encode jinfo->method too, since it is not equal to 'method'
6157 * when using generic sharing.
6159 buf2 = (guint8 *)g_malloc (4096);
6161 encode_method_ref (acfg, jinfo->d.method, p2, &p2);
6163 g_assert (len < 4096);
6164 encode_value (len, p, &p);
6165 memcpy (p, buf2, len);
6169 if (gsctx && gsctx->is_gsharedvt) {
6170 encode_value (1, p, &p);
6172 encode_value (0, p, &p);
6176 if (seq_points_size)
6177 p += mono_seq_point_info_write (seq_points, p);
6179 g_assert (debug_info_size < buf_size);
6181 encode_value (debug_info_size, p, &p);
6182 if (debug_info_size) {
6183 memcpy (p, debug_info, debug_info_size);
6184 p += debug_info_size;
6185 g_free (debug_info);
6190 encode_value (cfg->gc_map_size, p, &p);
6191 /* The GC map requires 4 bytes of alignment */
6192 while ((gsize)p % 4)
6194 memcpy (p, cfg->gc_map, cfg->gc_map_size);
6195 p += cfg->gc_map_size;
6198 acfg->stats.ex_info_size += p - buf;
6200 g_assert (p - buf < buf_size);
6203 /* The GC Map requires 4 byte alignment */
6204 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
6209 emit_klass_info (MonoAotCompile *acfg, guint32 token)
6212 MonoClass *klass = mono_class_get_checked (acfg->image, token, &error);
6214 int i, buf_size, res;
6215 gboolean no_special_static, cant_encode;
6216 gpointer iter = NULL;
6219 mono_error_cleanup (&error);
6223 p = buf = (guint8 *)g_malloc (buf_size);
6225 /* Mark as unusable */
6226 encode_value (-1, p, &p);
6228 res = add_to_blob (acfg, buf, p - buf);
6234 buf_size = 10240 + (klass->vtable_size * 16);
6235 p = buf = (guint8 *)g_malloc (buf_size);
6239 mono_class_init (klass);
6241 mono_class_get_nested_types (klass, &iter);
6242 g_assert (klass->nested_classes_inited);
6244 mono_class_setup_vtable (klass);
6247 * Emit all the information which is required for creating vtables so
6248 * the runtime does not need to create the MonoMethod structures which
6249 * take up a lot of space.
6252 no_special_static = !mono_class_has_special_static_fields (klass);
6254 /* Check whenever we have enough info to encode the vtable */
6255 cant_encode = FALSE;
6256 for (i = 0; i < klass->vtable_size; ++i) {
6257 MonoMethod *cm = klass->vtable [i];
6259 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
6263 mono_class_has_finalizer (klass);
6265 if (klass->generic_container || cant_encode) {
6266 encode_value (-1, p, &p);
6268 encode_value (klass->vtable_size, p, &p);
6269 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);
6270 if (klass->has_cctor)
6271 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
6272 if (klass->has_finalize)
6273 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
6275 encode_value (klass->instance_size, p, &p);
6276 encode_value (mono_class_data_size (klass), p, &p);
6277 encode_value (klass->packing_size, p, &p);
6278 encode_value (klass->min_align, p, &p);
6280 for (i = 0; i < klass->vtable_size; ++i) {
6281 MonoMethod *cm = klass->vtable [i];
6284 encode_method_ref (acfg, cm, p, &p);
6286 encode_value (0, p, &p);
6290 acfg->stats.class_info_size += p - buf;
6292 g_assert (p - buf < buf_size);
6293 res = add_to_blob (acfg, buf, p - buf);
6300 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
6302 char *debug_sym = NULL;
6305 if (acfg->llvm && llvm_acfg->aot_opts.static_link) {
6306 /* Need to add a prefix to create unique symbols */
6307 prefix = g_strdup_printf ("plt_%s_", acfg->assembly_name_sym);
6309 #if defined(TARGET_WIN32) && defined(TARGET_X86)
6310 prefix = mangle_symbol_alloc ("plt_");
6312 prefix = g_strdup ("plt_");
6317 case MONO_PATCH_INFO_METHOD:
6318 debug_sym = get_debug_sym (ji->data.method, prefix, cache);
6320 case MONO_PATCH_INFO_INTERNAL_METHOD:
6321 debug_sym = g_strdup_printf ("%s_jit_icall_%s", prefix, ji->data.name);
6323 case MONO_PATCH_INFO_RGCTX_FETCH:
6324 debug_sym = g_strdup_printf ("%s_rgctx_fetch_%d", prefix, acfg->label_generator ++);
6326 case MONO_PATCH_INFO_ICALL_ADDR:
6327 case MONO_PATCH_INFO_ICALL_ADDR_CALL: {
6328 char *s = get_debug_sym (ji->data.method, "", cache);
6330 debug_sym = g_strdup_printf ("%s_icall_native_%s", prefix, s);
6334 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
6335 debug_sym = g_strdup_printf ("%s_jit_icall_native_%s", prefix, ji->data.name);
6343 return sanitize_symbol (acfg, debug_sym);
6347 * Calls made from AOTed code are routed through a table of jumps similar to the
6348 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
6349 * control to the AOT runtime through a trampoline.
6352 emit_plt (MonoAotCompile *acfg)
6356 if (acfg->aot_opts.llvm_only) {
6357 g_assert (acfg->plt_offset == 1);
6363 emit_section_change (acfg, ".text", 0);
6364 emit_alignment_code (acfg, 16);
6365 emit_info_symbol (acfg, "plt");
6366 emit_label (acfg, acfg->plt_symbol);
6368 for (i = 0; i < acfg->plt_offset; ++i) {
6369 char *debug_sym = NULL;
6370 MonoPltEntry *plt_entry = NULL;
6374 * The first plt entry is unused.
6378 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6380 debug_sym = plt_entry->debug_sym;
6382 if (acfg->thumb_mixed && !plt_entry->jit_used)
6383 /* Emit only a thumb version */
6386 /* Skip plt entries not actually called */
6387 if (!plt_entry->jit_used && !plt_entry->llvm_used)
6390 if (acfg->llvm && !acfg->thumb_mixed) {
6391 emit_label (acfg, plt_entry->llvm_symbol);
6393 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6394 #if defined(TARGET_MACH)
6395 fprintf (acfg->fp, ".private_extern %s\n", plt_entry->llvm_symbol);
6401 if (acfg->need_no_dead_strip) {
6402 emit_unset_mode (acfg);
6403 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6405 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6406 emit_label (acfg, debug_sym);
6409 emit_label (acfg, plt_entry->symbol);
6411 arch_emit_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6414 emit_symbol_size (acfg, debug_sym, ".");
6417 if (acfg->thumb_mixed) {
6418 /* Make sure the ARM symbols don't alias the thumb ones */
6419 emit_zero_bytes (acfg, 16);
6422 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
6425 for (i = 0; i < acfg->plt_offset; ++i) {
6426 char *debug_sym = NULL;
6427 MonoPltEntry *plt_entry = NULL;
6432 plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6434 /* Skip plt entries not actually called by LLVM code */
6435 if (!plt_entry->llvm_used)
6438 if (acfg->aot_opts.write_symbols) {
6439 if (plt_entry->debug_sym)
6440 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
6444 #if defined(TARGET_MACH)
6445 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
6446 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
6448 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
6449 emit_label (acfg, debug_sym);
6451 fprintf (acfg->fp, "\n.thumb_func\n");
6453 emit_label (acfg, plt_entry->llvm_symbol);
6456 emit_global_inner (acfg, plt_entry->llvm_symbol, TRUE);
6458 arch_emit_llvm_plt_entry (acfg, acfg->got_symbol, (acfg->plt_got_offset_base + i) * sizeof (gpointer), acfg->plt_got_info_offsets [i]);
6461 emit_symbol_size (acfg, debug_sym, ".");
6467 emit_symbol_size (acfg, acfg->plt_symbol, ".");
6469 emit_info_symbol (acfg, "plt_end");
6473 * emit_trampoline_full:
6475 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
6476 * create_jit_info_for_trampoline ().
6478 static G_GNUC_UNUSED void
6479 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
6481 char start_symbol [MAX_SYMBOL_SIZE];
6482 char end_symbol [MAX_SYMBOL_SIZE];
6483 char symbol [MAX_SYMBOL_SIZE];
6484 guint32 buf_size, info_offset;
6485 MonoJumpInfo *patch_info;
6498 code_size = info->code_size;
6500 unwind_ops = info->unwind_ops;
6504 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
6506 emit_section_change (acfg, ".text", 0);
6507 emit_global (acfg, start_symbol, TRUE);
6508 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6509 emit_label (acfg, start_symbol);
6511 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
6512 emit_label (acfg, symbol);
6515 * The code should access everything through the GOT, so we pass
6518 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE, NULL);
6520 emit_symbol_size (acfg, start_symbol, ".");
6523 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
6524 emit_label (acfg, end_symbol);
6529 /* Sort relocations */
6530 patches = g_ptr_array_new ();
6531 for (patch_info = ji; patch_info; patch_info = patch_info->next)
6532 if (patch_info->type != MONO_PATCH_INFO_NONE)
6533 g_ptr_array_add (patches, patch_info);
6534 g_ptr_array_sort (patches, compare_patches);
6536 buf_size = patches->len * 128 + 128;
6537 buf = (guint8 *)g_malloc (buf_size);
6540 encode_patch_list (acfg, patches, patches->len, FALSE, got_offset, p, &p);
6541 g_assert (p - buf < buf_size);
6542 g_ptr_array_free (patches, TRUE);
6544 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
6546 info_offset = add_to_blob (acfg, buf, p - buf);
6548 emit_section_change (acfg, RODATA_SECT, 0);
6549 emit_global (acfg, symbol, FALSE);
6550 emit_label (acfg, symbol);
6552 emit_int32 (acfg, info_offset);
6556 guint32 encoded_len;
6560 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
6562 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
6563 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
6566 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
6567 emit_int32 (acfg, uw_offset);
6570 /* Emit debug info */
6572 char symbol2 [MAX_SYMBOL_SIZE];
6574 sprintf (symbol, "%s", name);
6575 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
6578 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
6584 static G_GNUC_UNUSED void
6585 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
6587 emit_trampoline_full (acfg, got_offset, info, TRUE);
6591 emit_trampolines (MonoAotCompile *acfg)
6593 char symbol [MAX_SYMBOL_SIZE];
6594 char end_symbol [MAX_SYMBOL_SIZE];
6595 int i, tramp_got_offset;
6597 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6601 if (!mono_aot_mode_is_full (&acfg->aot_opts) || acfg->aot_opts.llvm_only)
6604 g_assert (acfg->image->assembly);
6606 /* Currently, we emit most trampolines into the mscorlib AOT image. */
6607 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6608 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6609 MonoTrampInfo *info;
6612 * Emit the generic trampolines.
6614 * We could save some code by treating the generic trampolines as a wrapper
6615 * method, but that approach has its own complexities, so we choose the simpler
6618 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
6619 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
6620 #ifdef DISABLE_REMOTING
6621 if (tramp_type == MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING)
6624 #ifndef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD
6625 if (tramp_type == MONO_TRAMPOLINE_HANDLER_BLOCK_GUARD)
6628 mono_arch_create_generic_trampoline ((MonoTrampolineType)tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
6629 emit_trampoline (acfg, acfg->got_offset, info);
6632 /* Emit the exception related code pieces */
6633 mono_arch_get_restore_context (&info, TRUE);
6634 emit_trampoline (acfg, acfg->got_offset, info);
6635 mono_arch_get_call_filter (&info, TRUE);
6636 emit_trampoline (acfg, acfg->got_offset, info);
6637 mono_arch_get_throw_exception (&info, TRUE);
6638 emit_trampoline (acfg, acfg->got_offset, info);
6639 mono_arch_get_rethrow_exception (&info, TRUE);
6640 emit_trampoline (acfg, acfg->got_offset, info);
6641 mono_arch_get_throw_corlib_exception (&info, TRUE);
6642 emit_trampoline (acfg, acfg->got_offset, info);
6644 #ifdef MONO_ARCH_HAVE_SDB_TRAMPOLINES
6645 mono_arch_create_sdb_trampoline (TRUE, &info, TRUE);
6646 emit_trampoline (acfg, acfg->got_offset, info);
6647 mono_arch_create_sdb_trampoline (FALSE, &info, TRUE);
6648 emit_trampoline (acfg, acfg->got_offset, info);
6651 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
6652 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
6654 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6656 /* Create a separate out trampoline for more information in stack traces */
6657 info->name = g_strdup ("gsharedvt_out_trampoline");
6658 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
6662 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
6664 GSList *l = mono_arch_get_trampolines (TRUE);
6667 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6669 emit_trampoline (acfg, acfg->got_offset, info);
6675 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
6678 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
6679 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6680 emit_trampoline (acfg, acfg->got_offset, info);
6683 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
6684 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
6685 emit_trampoline (acfg, acfg->got_offset, info);
6689 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
6690 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
6691 emit_trampoline (acfg, acfg->got_offset, info);
6697 /* delegate_invoke_impl trampolines */
6698 l = mono_arch_get_delegate_invoke_impls ();
6700 MonoTrampInfo *info = (MonoTrampInfo *)l->data;
6702 emit_trampoline (acfg, acfg->got_offset, info);
6707 #ifdef MONO_ARCH_HAVE_HANDLER_BLOCK_GUARD_AOT
6708 mono_arch_create_handler_block_trampoline (&info, TRUE);
6709 emit_trampoline (acfg, acfg->got_offset, info);
6712 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
6714 /* Emit trampolines which are numerous */
6717 * These include the following:
6718 * - specific trampolines
6719 * - static rgctx invoke trampolines
6721 * These trampolines have the same code, they are parameterized by GOT
6723 * They are defined in this file, in the arch_... routines instead of
6724 * in tramp-<ARCH>.c, since it is easier to do it this way.
6728 * When running in aot-only mode, we can't create specific trampolines at
6729 * runtime, so we create a few, and save them in the AOT file.
6730 * Normal trampolines embed their argument as a literal inside the
6731 * trampoline code, we can't do that here, so instead we embed an offset
6732 * which needs to be added to the trampoline address to get the address of
6733 * the GOT slot which contains the argument value.
6734 * The generated trampolines jump to the generic trampolines using another
6735 * GOT slot, which will be setup by the AOT loader to point to the
6736 * generic trampoline code of the given type.
6740 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
6744 emit_section_change (acfg, ".text", 0);
6746 tramp_got_offset = acfg->got_offset;
6748 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
6750 case MONO_AOT_TRAMP_SPECIFIC:
6751 sprintf (symbol, "specific_trampolines");
6753 case MONO_AOT_TRAMP_STATIC_RGCTX:
6754 sprintf (symbol, "static_rgctx_trampolines");
6756 case MONO_AOT_TRAMP_IMT:
6757 sprintf (symbol, "imt_trampolines");
6759 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6760 sprintf (symbol, "gsharedvt_arg_trampolines");
6763 g_assert_not_reached ();
6766 sprintf (end_symbol, "%s_e", symbol);
6768 if (acfg->aot_opts.write_symbols)
6769 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
6771 emit_alignment_code (acfg, AOT_FUNC_ALIGNMENT);
6772 emit_info_symbol (acfg, symbol);
6774 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
6776 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
6780 case MONO_AOT_TRAMP_SPECIFIC:
6781 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
6782 tramp_got_offset += 2;
6784 case MONO_AOT_TRAMP_STATIC_RGCTX:
6785 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
6786 tramp_got_offset += 2;
6788 case MONO_AOT_TRAMP_IMT:
6789 arch_emit_imt_trampoline (acfg, tramp_got_offset, &tramp_size);
6790 tramp_got_offset += 1;
6792 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
6793 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
6794 tramp_got_offset += 2;
6797 g_assert_not_reached ();
6799 if (!acfg->trampoline_size [ntype]) {
6800 g_assert (tramp_size);
6801 acfg->trampoline_size [ntype] = tramp_size;
6805 emit_label (acfg, end_symbol);
6806 emit_int32 (acfg, 0);
6809 arch_emit_specific_trampoline_pages (acfg);
6811 /* Reserve some entries at the end of the GOT for our use */
6812 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
6815 acfg->got_offset += acfg->num_trampoline_got_entries;
6819 str_begins_with (const char *str1, const char *str2)
6821 int len = strlen (str2);
6822 return strncmp (str1, str2, len) == 0;
6826 mono_aot_readonly_field_override (MonoClassField *field)
6829 for (rdv = readonly_values; rdv; rdv = rdv->next) {
6830 char *p = rdv->name;
6832 len = strlen (field->parent->name_space);
6833 if (strncmp (p, field->parent->name_space, len))
6838 len = strlen (field->parent->name);
6839 if (strncmp (p, field->parent->name, len))
6844 if (strcmp (p, field->name))
6846 switch (rdv->type) {
6848 return &rdv->value.i1;
6850 return &rdv->value.i2;
6852 return &rdv->value.i4;
6861 add_readonly_value (MonoAotOptions *opts, const char *val)
6866 /* the format of val is:
6867 * namespace.typename.fieldname=type/value
6868 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
6870 fval = strrchr (val, '/');
6872 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
6875 tval = strrchr (val, '=');
6877 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
6880 rdv = g_new0 (ReadOnlyValue, 1);
6881 rdv->name = (char *)g_malloc0 (tval - val + 1);
6882 memcpy (rdv->name, val, tval - val);
6885 if (strncmp (tval, "i1", 2) == 0) {
6886 rdv->value.i1 = atoi (fval);
6887 rdv->type = MONO_TYPE_I1;
6888 } else if (strncmp (tval, "i2", 2) == 0) {
6889 rdv->value.i2 = atoi (fval);
6890 rdv->type = MONO_TYPE_I2;
6891 } else if (strncmp (tval, "i4", 2) == 0) {
6892 rdv->value.i4 = atoi (fval);
6893 rdv->type = MONO_TYPE_I4;
6895 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
6898 rdv->next = readonly_values;
6899 readonly_values = rdv;
6903 clean_path (gchar * path)
6908 if (g_str_has_suffix (path, G_DIR_SEPARATOR_S))
6911 gchar *clean = g_strconcat (path, G_DIR_SEPARATOR_S, NULL);
6918 wrap_path (gchar * path)
6924 // If the string contains no spaces, just return the original string.
6925 if (strstr (path, " ") == NULL)
6928 // If the string is already wrapped in quotes, return it.
6929 len = strlen (path);
6930 if (len >= 2 && path[0] == '\"' && path[len-1] == '\"')
6933 // If the string contains spaces, then wrap it in quotes.
6934 gchar *clean = g_strdup_printf ("\"%s\"", path);
6939 // Duplicate a char range and add it to a ptrarray, but only if it is nonempty
6941 ptr_array_add_range_if_nonempty(GPtrArray *args, gchar const *start, gchar const *end)
6943 ptrdiff_t len = end-start;
6945 g_ptr_array_add (args, g_strndup (start, len));
6949 mono_aot_split_options (const char *aot_options)
6951 enum MonoAotOptionState {
6952 MONO_AOT_OPTION_STATE_DEFAULT,
6953 MONO_AOT_OPTION_STATE_STRING,
6954 MONO_AOT_OPTION_STATE_ESCAPE,
6957 GPtrArray *args = g_ptr_array_new ();
6958 enum MonoAotOptionState state = MONO_AOT_OPTION_STATE_DEFAULT;
6959 gchar const *opt_start = aot_options;
6960 gboolean end_of_string = FALSE;
6963 g_return_val_if_fail (aot_options != NULL, NULL);
6965 while ((cur = *aot_options) != '\0') {
6966 if (state == MONO_AOT_OPTION_STATE_ESCAPE)
6971 // If we find a quote, then if we're in the default case then
6972 // it means we've found the start of a string, if not then it
6973 // means we've found the end of the string and should switch
6974 // back to the default case.
6976 case MONO_AOT_OPTION_STATE_DEFAULT:
6977 state = MONO_AOT_OPTION_STATE_STRING;
6979 case MONO_AOT_OPTION_STATE_STRING:
6980 state = MONO_AOT_OPTION_STATE_DEFAULT;
6982 case MONO_AOT_OPTION_STATE_ESCAPE:
6983 g_assert_not_reached ();
6988 // If we've found an escaping operator, then this means we
6989 // should not process the next character if inside a string.
6990 if (state == MONO_AOT_OPTION_STATE_STRING)
6991 state = MONO_AOT_OPTION_STATE_ESCAPE;
6994 // If we're in the default state then this means we've found
6995 // an option, store it for later processing.
6996 if (state == MONO_AOT_OPTION_STATE_DEFAULT)
7004 // If the next character is end of string, then process the last option.
7005 if (*(aot_options) == '\0') {
7006 end_of_string = TRUE;
7012 ptr_array_add_range_if_nonempty (args, opt_start, aot_options);
7013 opt_start = ++aot_options;
7016 goto restart; // Check for null and continue loop
7023 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
7027 args = mono_aot_split_options (aot_options ? aot_options : "");
7028 for (int i = 0; i < args->len; ++i) {
7029 const char *arg = (const char *)g_ptr_array_index (args, i);
7031 if (str_begins_with (arg, "outfile=")) {
7032 opts->outfile = g_strdup (arg + strlen ("outfile="));
7033 } else if (str_begins_with (arg, "llvm-outfile=")) {
7034 opts->llvm_outfile = g_strdup (arg + strlen ("llvm-outfile="));
7035 } else if (str_begins_with (arg, "temp-path=")) {
7036 opts->temp_path = clean_path (g_strdup (arg + strlen ("temp-path=")));
7037 } else if (str_begins_with (arg, "save-temps")) {
7038 opts->save_temps = TRUE;
7039 } else if (str_begins_with (arg, "keep-temps")) {
7040 opts->save_temps = TRUE;
7041 } else if (str_begins_with (arg, "write-symbols")) {
7042 opts->write_symbols = TRUE;
7043 } else if (str_begins_with (arg, "no-write-symbols")) {
7044 opts->write_symbols = FALSE;
7045 } else if (str_begins_with (arg, "metadata-only")) {
7046 opts->metadata_only = TRUE;
7047 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
7048 opts->bind_to_runtime_version = TRUE;
7049 } else if (str_begins_with (arg, "full")) {
7050 opts->mode = MONO_AOT_MODE_FULL;
7051 } else if (str_begins_with (arg, "hybrid")) {
7052 opts->mode = MONO_AOT_MODE_HYBRID;
7053 } else if (str_begins_with (arg, "threads=")) {
7054 opts->nthreads = atoi (arg + strlen ("threads="));
7055 } else if (str_begins_with (arg, "static")) {
7056 opts->static_link = TRUE;
7057 opts->no_dlsym = TRUE;
7058 } else if (str_begins_with (arg, "asmonly")) {
7059 opts->asm_only = TRUE;
7060 } else if (str_begins_with (arg, "asmwriter")) {
7061 opts->asm_writer = TRUE;
7062 } else if (str_begins_with (arg, "nodebug")) {
7063 opts->nodebug = TRUE;
7064 } else if (str_begins_with (arg, "dwarfdebug")) {
7065 opts->dwarf_debug = TRUE;
7066 } else if (str_begins_with (arg, "nopagetrampolines")) {
7067 opts->use_trampolines_page = FALSE;
7068 } else if (str_begins_with (arg, "ntrampolines=")) {
7069 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
7070 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
7071 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
7072 } else if (str_begins_with (arg, "nrgctx-fetch-trampolines=")) {
7073 opts->nrgctx_fetch_trampolines = atoi (arg + strlen ("nrgctx-fetch-trampolines="));
7074 } else if (str_begins_with (arg, "nimt-trampolines=")) {
7075 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
7076 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
7077 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
7078 } else if (str_begins_with (arg, "tool-prefix=")) {
7079 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
7080 } else if (str_begins_with (arg, "ld-flags=")) {
7081 opts->ld_flags = g_strdup (arg + strlen ("ld-flags="));
7082 } else if (str_begins_with (arg, "soft-debug")) {
7083 opts->soft_debug = TRUE;
7084 } else if (str_begins_with (arg, "gen-seq-points-file=")) {
7085 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file= is deprecated.\n");
7086 } else if (str_begins_with (arg, "gen-seq-points-file")) {
7087 fprintf (stderr, "Mono Warning: aot option gen-seq-points-file is deprecated.\n");
7088 } else if (str_begins_with (arg, "msym-dir=")) {
7089 debug_options.no_seq_points_compact_data = FALSE;
7090 opts->gen_msym_dir = TRUE;
7091 opts->gen_msym_dir_path = g_strdup (arg + strlen ("msym_dir="));;
7092 } else if (str_begins_with (arg, "direct-pinvoke")) {
7093 opts->direct_pinvoke = TRUE;
7094 } else if (str_begins_with (arg, "direct-icalls")) {
7095 opts->direct_icalls = TRUE;
7096 } else if (str_begins_with (arg, "no-direct-calls")) {
7097 opts->no_direct_calls = TRUE;
7098 } else if (str_begins_with (arg, "print-skipped")) {
7099 opts->print_skipped_methods = TRUE;
7100 } else if (str_begins_with (arg, "stats")) {
7102 } else if (str_begins_with (arg, "no-instances")) {
7103 opts->no_instances = TRUE;
7104 } else if (str_begins_with (arg, "log-generics")) {
7105 opts->log_generics = TRUE;
7106 } else if (str_begins_with (arg, "log-instances=")) {
7107 opts->log_instances = TRUE;
7108 opts->instances_logfile_path = g_strdup (arg + strlen ("log-instances="));
7109 } else if (str_begins_with (arg, "log-instances")) {
7110 opts->log_instances = TRUE;
7111 } else if (str_begins_with (arg, "internal-logfile=")) {
7112 opts->logfile = g_strdup (arg + strlen ("internal-logfile="));
7113 } else if (str_begins_with (arg, "mtriple=")) {
7114 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
7115 } else if (str_begins_with (arg, "llvm-path=")) {
7116 opts->llvm_path = clean_path (g_strdup (arg + strlen ("llvm-path=")));
7117 } else if (!strcmp (arg, "llvm")) {
7119 } else if (str_begins_with (arg, "readonly-value=")) {
7120 add_readonly_value (opts, arg + strlen ("readonly-value="));
7121 } else if (str_begins_with (arg, "info")) {
7122 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
7124 } else if (str_begins_with (arg, "gc-maps")) {
7125 mini_gc_enable_gc_maps_for_aot ();
7126 } else if (str_begins_with (arg, "dump")) {
7127 opts->dump_json = TRUE;
7128 } else if (str_begins_with (arg, "llvmonly")) {
7129 opts->mode = MONO_AOT_MODE_FULL;
7131 opts->llvm_only = TRUE;
7132 } else if (str_begins_with (arg, "data-outfile=")) {
7133 opts->data_outfile = g_strdup (arg + strlen ("data-outfile="));
7134 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
7135 printf ("Supported options for --aot:\n");
7136 printf (" outfile=\n");
7137 printf (" llvm-outfile=\n");
7138 printf (" llvm-path=\n");
7139 printf (" temp-path=\n");
7140 printf (" save-temps\n");
7141 printf (" keep-temps\n");
7142 printf (" write-symbols\n");
7143 printf (" metadata-only\n");
7144 printf (" bind-to-runtime-version\n");
7146 printf (" threads=\n");
7147 printf (" static\n");
7148 printf (" asmonly\n");
7149 printf (" asmwriter\n");
7150 printf (" nodebug\n");
7151 printf (" dwarfdebug\n");
7152 printf (" ntrampolines=\n");
7153 printf (" nrgctx-trampolines=\n");
7154 printf (" nimt-trampolines=\n");
7155 printf (" ngsharedvt-trampolines=\n");
7156 printf (" tool-prefix=\n");
7157 printf (" readonly-value=\n");
7158 printf (" soft-debug\n");
7159 printf (" msym-dir=\n");
7160 printf (" gc-maps\n");
7161 printf (" print-skipped\n");
7162 printf (" no-instances\n");
7163 printf (" stats\n");
7166 printf (" help/?\n");
7169 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
7173 g_free ((gpointer) arg);
7176 if (opts->use_trampolines_page) {
7177 opts->ntrampolines = 0;
7178 opts->nrgctx_trampolines = 0;
7179 opts->nimt_trampolines = 0;
7180 opts->ngsharedvt_arg_trampolines = 0;
7183 g_ptr_array_free (args, /*free_seg=*/TRUE);
7187 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
7189 MonoMethod *method = (MonoMethod*)key;
7190 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
7191 MonoAotCompile *acfg = (MonoAotCompile *)user_data;
7192 MonoJumpInfoToken *new_ji;
7194 new_ji = (MonoJumpInfoToken *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfoToken));
7195 new_ji->image = ji->image;
7196 new_ji->token = ji->token;
7197 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
7201 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
7203 if (klass->type_token)
7205 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
7208 return can_encode_class (acfg, klass->element_class);
7213 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
7215 if (method->wrapper_type) {
7216 switch (method->wrapper_type) {
7217 case MONO_WRAPPER_NONE:
7218 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
7219 case MONO_WRAPPER_XDOMAIN_INVOKE:
7220 case MONO_WRAPPER_STFLD:
7221 case MONO_WRAPPER_LDFLD:
7222 case MONO_WRAPPER_LDFLDA:
7223 case MONO_WRAPPER_STELEMREF:
7224 case MONO_WRAPPER_ISINST:
7225 case MONO_WRAPPER_PROXY_ISINST:
7226 case MONO_WRAPPER_ALLOC:
7227 case MONO_WRAPPER_REMOTING_INVOKE:
7228 case MONO_WRAPPER_UNKNOWN:
7229 case MONO_WRAPPER_WRITE_BARRIER:
7230 case MONO_WRAPPER_DELEGATE_INVOKE:
7231 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
7232 case MONO_WRAPPER_DELEGATE_END_INVOKE:
7233 case MONO_WRAPPER_SYNCHRONIZED:
7235 case MONO_WRAPPER_MANAGED_TO_MANAGED:
7236 case MONO_WRAPPER_CASTCLASS: {
7237 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
7246 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
7250 if (!method->token) {
7251 /* The method is part of a constructed type like Int[,].Set (). */
7252 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
7253 if (method->klass->rank)
7263 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
7265 switch (patch_info->type) {
7266 case MONO_PATCH_INFO_METHOD:
7267 case MONO_PATCH_INFO_METHODCONST:
7268 case MONO_PATCH_INFO_METHOD_CODE_SLOT: {
7269 MonoMethod *method = patch_info->data.method;
7271 return can_encode_method (acfg, method);
7273 case MONO_PATCH_INFO_VTABLE:
7274 case MONO_PATCH_INFO_CLASS:
7275 case MONO_PATCH_INFO_IID:
7276 case MONO_PATCH_INFO_ADJUSTED_IID:
7277 if (!can_encode_class (acfg, patch_info->data.klass)) {
7278 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7282 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE: {
7283 if (!can_encode_class (acfg, patch_info->data.del_tramp->klass)) {
7284 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
7289 case MONO_PATCH_INFO_RGCTX_FETCH:
7290 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX: {
7291 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
7293 if (!can_encode_method (acfg, entry->method))
7295 if (!can_encode_patch (acfg, entry->data))
7307 is_concrete_type (MonoType *t)
7312 if (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR)
7314 if (t->type == MONO_TYPE_GENERICINST) {
7315 MonoGenericContext *orig_ctx;
7316 MonoGenericInst *inst;
7319 if (!MONO_TYPE_ISSTRUCT (t))
7321 klass = mono_class_from_mono_type (t);
7322 orig_ctx = &klass->generic_class->context;
7324 inst = orig_ctx->class_inst;
7326 for (i = 0; i < inst->type_argc; ++i) {
7327 arg = mini_get_underlying_type (inst->type_argv [i]);
7328 if (!is_concrete_type (arg))
7332 inst = orig_ctx->method_inst;
7334 for (i = 0; i < inst->type_argc; ++i) {
7335 arg = mini_get_underlying_type (inst->type_argv [i]);
7336 if (!is_concrete_type (arg))
7344 /* LOCKING: Assumes the loader lock is held */
7346 add_gsharedvt_wrappers (MonoAotCompile *acfg, MonoMethodSignature *sig, gboolean gsharedvt_in, gboolean gsharedvt_out)
7348 MonoMethod *wrapper;
7349 gboolean concrete = TRUE;
7350 gboolean add_in = gsharedvt_in;
7351 gboolean add_out = gsharedvt_out;
7353 if (gsharedvt_in && g_hash_table_lookup (acfg->gsharedvt_in_signatures, sig))
7355 if (gsharedvt_out && g_hash_table_lookup (acfg->gsharedvt_out_signatures, sig))
7358 if (!add_in && !add_out)
7361 if (mini_is_gsharedvt_variable_signature (sig))
7365 g_hash_table_insert (acfg->gsharedvt_in_signatures, sig, sig);
7367 g_hash_table_insert (acfg->gsharedvt_out_signatures, sig, sig);
7369 if (!sig->has_type_parameters) {
7370 //printf ("%s\n", mono_signature_full_name (sig));
7373 wrapper = mini_get_gsharedvt_in_sig_wrapper (sig);
7374 add_extra_method (acfg, wrapper);
7376 if (gsharedvt_out) {
7377 wrapper = mini_get_gsharedvt_out_sig_wrapper (sig);
7378 add_extra_method (acfg, wrapper);
7381 /* For signatures creared during generic sharing, convert them to a concrete signature if possible */
7382 MonoMethodSignature *copy = mono_metadata_signature_dup (sig);
7385 //printf ("%s\n", mono_signature_full_name (sig));
7387 copy->ret = mini_get_underlying_type (sig->ret);
7388 if (!is_concrete_type (copy->ret))
7390 for (i = 0; i < sig->param_count; ++i) {
7391 copy->params [i] = mini_get_underlying_type (sig->params [i]);
7392 if (!is_concrete_type (copy->params [i]))
7396 copy->has_type_parameters = 0;
7399 wrapper = mini_get_gsharedvt_in_sig_wrapper (copy);
7400 add_extra_method (acfg, wrapper);
7403 if (gsharedvt_out) {
7404 wrapper = mini_get_gsharedvt_out_sig_wrapper (copy);
7405 add_extra_method (acfg, wrapper);
7408 //printf ("%s\n", mono_method_full_name (wrapper, 1));
7416 * AOT compile a given method.
7417 * This function might be called by multiple threads, so it must be thread-safe.
7420 compile_method (MonoAotCompile *acfg, MonoMethod *method)
7423 MonoJumpInfo *patch_info;
7426 MonoMethod *wrapped;
7430 if (acfg->aot_opts.metadata_only)
7433 mono_acfg_lock (acfg);
7434 index = get_method_index (acfg, method);
7435 mono_acfg_unlock (acfg);
7437 /* fixme: maybe we can also precompile wrapper methods */
7438 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7439 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7440 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
7441 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
7445 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7448 wrapped = mono_marshal_method_from_wrapper (method);
7449 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
7450 // FIXME: The wrapper should be generic too, but it is not
7453 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
7456 InterlockedIncrement (&acfg->stats.mcount);
7459 if (method->is_generic || method->klass->generic_container) {
7460 InterlockedIncrement (&acfg->stats.genericcount);
7465 //acfg->aot_opts.print_skipped_methods = TRUE;
7468 * Since these methods are the only ones which are compiled with
7469 * AOT support, and they are not used by runtime startup/shutdown code,
7470 * the runtime will not see AOT methods during AOT compilation,so it
7471 * does not need to support them by creating a fake GOT etc.
7473 flags = JIT_FLAG_AOT;
7474 if (mono_aot_mode_is_full (&acfg->aot_opts))
7475 flags = (JitFlags)(flags | JIT_FLAG_FULL_AOT);
7477 flags = (JitFlags)(flags | JIT_FLAG_LLVM);
7478 if (acfg->aot_opts.llvm_only)
7479 flags = (JitFlags)(flags | JIT_FLAG_LLVM_ONLY | JIT_FLAG_EXPLICIT_NULL_CHECKS);
7480 if (acfg->aot_opts.no_direct_calls)
7481 flags = (JitFlags)(flags | JIT_FLAG_NO_DIRECT_ICALLS);
7483 jit_timer = mono_time_track_start ();
7484 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), flags, 0, index);
7485 mono_time_track_end (&mono_jit_stats.jit_time, jit_timer);
7487 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
7488 if (acfg->aot_opts.print_skipped_methods)
7489 printf ("Skip (gshared failure): %s (%s)\n", mono_method_get_full_name (method), cfg->exception_message);
7490 InterlockedIncrement (&acfg->stats.genericcount);
7493 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
7494 if (acfg->aot_opts.print_skipped_methods)
7495 printf ("Skip (JIT failure): %s\n", mono_method_get_full_name (method));
7496 /* Let the exception happen at runtime */
7500 if (cfg->disable_aot) {
7501 if (acfg->aot_opts.print_skipped_methods)
7502 printf ("Skip (disabled): %s\n", mono_method_get_full_name (method));
7503 InterlockedIncrement (&acfg->stats.ocount);
7506 cfg->method_index = index;
7508 /* Nullify patches which need no aot processing */
7509 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7510 switch (patch_info->type) {
7511 case MONO_PATCH_INFO_LABEL:
7512 case MONO_PATCH_INFO_BB:
7513 patch_info->type = MONO_PATCH_INFO_NONE;
7520 /* Collect method->token associations from the cfg */
7521 mono_acfg_lock (acfg);
7522 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
7523 mono_acfg_unlock (acfg);
7524 g_hash_table_destroy (cfg->token_info_hash);
7525 cfg->token_info_hash = NULL;
7528 * Check for absolute addresses.
7531 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7532 switch (patch_info->type) {
7533 case MONO_PATCH_INFO_ABS:
7534 /* unable to handle this */
7543 if (acfg->aot_opts.print_skipped_methods)
7544 printf ("Skip (abs call): %s\n", mono_method_get_full_name (method));
7545 InterlockedIncrement (&acfg->stats.abscount);
7549 /* Lock for the rest of the code */
7550 mono_acfg_lock (acfg);
7553 acfg->stats.method_categories [METHOD_CAT_GSHAREDVT] ++;
7554 else if (cfg->gshared)
7555 acfg->stats.method_categories [METHOD_CAT_INST] ++;
7556 else if (cfg->method->wrapper_type)
7557 acfg->stats.method_categories [METHOD_CAT_WRAPPER] ++;
7559 acfg->stats.method_categories [METHOD_CAT_NORMAL] ++;
7562 * Check for methods/klasses we can't encode.
7565 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7566 if (!can_encode_patch (acfg, patch_info))
7571 if (acfg->aot_opts.print_skipped_methods)
7572 printf ("Skip (patches): %s\n", mono_method_get_full_name (method));
7573 acfg->stats.ocount++;
7574 mono_acfg_unlock (acfg);
7578 if (!cfg->compile_llvm)
7579 acfg->has_jitted_code = TRUE;
7581 if (method->is_inflated && acfg->aot_opts.log_instances) {
7582 if (acfg->instances_logfile)
7583 fprintf (acfg->instances_logfile, "%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7585 printf ("%s ### %d\n", mono_method_get_full_name (method), cfg->code_size);
7588 /* Adds generic instances referenced by this method */
7590 * The depth is used to avoid infinite loops when generic virtual recursion is
7593 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
7594 if (!acfg->aot_opts.no_instances && depth < 32) {
7595 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7596 switch (patch_info->type) {
7597 case MONO_PATCH_INFO_RGCTX_FETCH:
7598 case MONO_PATCH_INFO_RGCTX_SLOT_INDEX:
7599 case MONO_PATCH_INFO_METHOD: {
7600 MonoMethod *m = NULL;
7602 if (patch_info->type == MONO_PATCH_INFO_RGCTX_FETCH || patch_info->type == MONO_PATCH_INFO_RGCTX_SLOT_INDEX) {
7603 MonoJumpInfoRgctxEntry *e = patch_info->data.rgctx_entry;
7605 if (e->info_type == MONO_RGCTX_INFO_GENERIC_METHOD_CODE)
7606 m = e->data->data.method;
7608 m = patch_info->data.method;
7613 if (m->is_inflated) {
7614 if (!(mono_class_generic_sharing_enabled (m->klass) &&
7615 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
7616 (!method_has_type_vars (m) || mono_method_is_generic_sharable_full (m, TRUE, TRUE, FALSE))) {
7617 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7618 if (mono_aot_mode_is_full (&acfg->aot_opts) && !method_has_type_vars (m))
7619 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
7621 add_extra_method_with_depth (acfg, m, depth + 1);
7622 add_types_from_method_header (acfg, m);
7625 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
7627 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
7628 WrapperInfo *info = mono_marshal_get_wrapper_info (m);
7630 if (info && info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR)
7631 add_extra_method_with_depth (acfg, m, depth + 1);
7635 case MONO_PATCH_INFO_VTABLE: {
7636 MonoClass *klass = patch_info->data.klass;
7638 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
7639 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
7642 case MONO_PATCH_INFO_SFLDA: {
7643 MonoClass *klass = patch_info->data.field->parent;
7645 /* The .cctor needs to run at runtime. */
7646 if (klass->generic_class && !mono_generic_context_is_sharable_full (&klass->generic_class->context, FALSE, FALSE) && mono_class_get_cctor (klass))
7647 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
7656 /* Determine whenever the method has GOT slots */
7657 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7658 switch (patch_info->type) {
7659 case MONO_PATCH_INFO_GOT_OFFSET:
7660 case MONO_PATCH_INFO_NONE:
7661 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
7662 case MONO_PATCH_INFO_GC_NURSERY_START:
7663 case MONO_PATCH_INFO_GC_NURSERY_BITS:
7665 case MONO_PATCH_INFO_IMAGE:
7666 /* The assembly is stored in GOT slot 0 */
7667 if (patch_info->data.image != acfg->image)
7668 cfg->has_got_slots = TRUE;
7671 if (!is_plt_patch (patch_info) || (cfg->compile_llvm && acfg->aot_opts.llvm_only))
7672 cfg->has_got_slots = TRUE;
7677 if (!cfg->has_got_slots)
7678 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
7680 /* Add gsharedvt wrappers for signatures used by the method */
7681 if (acfg->aot_opts.llvm_only) {
7684 if (!cfg->method->wrapper_type || cfg->method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE)
7685 /* These only need out wrappers */
7686 add_gsharedvt_wrappers (acfg, mono_method_signature (cfg->method), FALSE, TRUE);
7688 for (l = cfg->signatures; l; l = l->next) {
7689 MonoMethodSignature *sig = mono_metadata_signature_dup ((MonoMethodSignature*)l->data);
7691 /* These only need in wrappers */
7692 add_gsharedvt_wrappers (acfg, sig, TRUE, FALSE);
7697 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
7699 /* Make a copy of the patch info which is in the mempool */
7701 MonoJumpInfo *patches = NULL, *patches_end = NULL;
7703 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7704 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
7707 patches = new_patch_info;
7709 patches_end->next = new_patch_info;
7710 patches_end = new_patch_info;
7712 cfg->patch_info = patches;
7714 /* Make a copy of the unwind info */
7716 GSList *l, *unwind_ops;
7720 for (l = cfg->unwind_ops; l; l = l->next) {
7721 op = (MonoUnwindOp *)mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
7722 memcpy (op, l->data, sizeof (MonoUnwindOp));
7723 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
7725 cfg->unwind_ops = g_slist_reverse (unwind_ops);
7727 /* Make a copy of the argument/local info */
7730 MonoInst **args, **locals;
7731 MonoMethodSignature *sig;
7732 MonoMethodHeader *header;
7735 sig = mono_method_signature (method);
7736 args = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
7737 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
7738 args [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7739 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
7743 header = mono_method_get_header_checked (method, &error);
7744 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
7745 locals = (MonoInst **)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
7746 for (i = 0; i < header->num_locals; ++i) {
7747 locals [i] = (MonoInst *)mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
7748 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
7750 mono_metadata_free_mh (header);
7751 cfg->locals = locals;
7754 /* Free some fields used by cfg to conserve memory */
7755 mono_empty_compile (cfg);
7757 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
7759 while (index >= acfg->cfgs_size) {
7760 MonoCompile **new_cfgs;
7763 new_size = acfg->cfgs_size * 2;
7764 new_cfgs = g_new0 (MonoCompile*, new_size);
7765 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
7766 g_free (acfg->cfgs);
7767 acfg->cfgs = new_cfgs;
7768 acfg->cfgs_size = new_size;
7770 acfg->cfgs [index] = cfg;
7772 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
7774 mono_update_jit_stats (cfg);
7777 if (cfg->orig_method->wrapper_type)
7778 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
7781 mono_acfg_unlock (acfg);
7783 InterlockedIncrement (&acfg->stats.ccount);
7787 compile_thread_main (gpointer user_data)
7789 MonoDomain *domain = ((MonoDomain **)user_data) [0];
7790 MonoAotCompile *acfg = ((MonoAotCompile **)user_data) [1];
7791 GPtrArray *methods = ((GPtrArray **)user_data) [2];
7795 MonoThread *thread = mono_thread_attach (domain);
7796 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "AOT compiler"), TRUE, &error);
7797 mono_error_assert_ok (&error);
7799 for (i = 0; i < methods->len; ++i)
7800 compile_method (acfg, (MonoMethod *)g_ptr_array_index (methods, i));
7806 load_profile_files (MonoAotCompile *acfg)
7810 int file_index, res, method_index, i;
7813 GList *unordered, *l;
7818 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
7820 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
7825 infile = fopen (tmp, "r");
7828 printf ("Using profile data file '%s'\n", tmp);
7833 res = fscanf (infile, "%32s\n", ver);
7834 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
7835 printf ("Profile file has wrong version or invalid.\n");
7842 MonoMethodDesc *desc;
7845 if (fgets (name, 1023, infile) == NULL)
7848 /* Kill the newline */
7849 if (strlen (name) > 0)
7850 name [strlen (name) - 1] = '\0';
7852 desc = mono_method_desc_new (name, TRUE);
7854 method = mono_method_desc_search_in_image (desc, acfg->image);
7856 if (method && mono_method_get_token (method)) {
7857 token = mono_method_get_token (method);
7858 method_index = mono_metadata_token_index (token) - 1;
7861 for (i = 0; i < acfg->method_order->len; ++i) {
7862 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7868 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
7870 //printf ("No method found matching '%s'.\n", name);
7876 /* Add missing methods */
7878 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
7880 for (i = 0; i < acfg->method_order->len; ++i) {
7881 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
7887 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
7889 unordered = g_list_reverse (unordered);
7890 for (l = unordered; l; l = l->next)
7891 g_ptr_array_add (acfg->method_order, l->data);
7894 /* Used by the LLVM backend */
7896 mono_aot_get_got_offset (MonoJumpInfo *ji)
7898 return get_got_offset (llvm_acfg, TRUE, ji);
7902 * mono_aot_is_shared_got_offset:
7904 * Return whenever OFFSET refers to a GOT slot which is preinitialized
7905 * when the AOT image is loaded.
7908 mono_aot_is_shared_got_offset (int offset)
7910 return offset < llvm_acfg->nshared_got_entries;
7914 mono_aot_get_method_name (MonoCompile *cfg)
7916 if (llvm_acfg->aot_opts.static_link)
7917 /* Include the assembly name too to avoid duplicate symbol errors */
7918 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
7920 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
7924 * mono_aot_is_linkonce_method:
7926 * Return whenever METHOD should be emitted with linkonce linkage,
7927 * eliminating duplicate copies when compiling in static mode.
7930 mono_aot_is_linkonce_method (MonoMethod *method)
7936 // FIXME: Add more cases
7937 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
7939 info = mono_marshal_get_wrapper_info (method);
7940 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
7947 append_mangled_type (GString *s, MonoType *t)
7950 g_string_append_printf (s, "b");
7952 case MONO_TYPE_VOID:
7953 g_string_append_printf (s, "void_");
7956 g_string_append_printf (s, "i1");
7959 g_string_append_printf (s, "u1");
7962 g_string_append_printf (s, "i2");
7965 g_string_append_printf (s, "u2");
7968 g_string_append_printf (s, "i4");
7971 g_string_append_printf (s, "u4");
7974 g_string_append_printf (s, "i8");
7977 g_string_append_printf (s, "u8");
7980 g_string_append_printf (s, "ii");
7983 g_string_append_printf (s, "ui");
7986 g_string_append_printf (s, "fl");
7989 g_string_append_printf (s, "do");
7992 char *fullname = mono_type_full_name (t);
7998 * Have to create a mangled name which is:
8002 temp = g_string_new ("");
8003 len = strlen (fullname);
8004 for (i = 0; i < len; ++i) {
8005 char c = fullname [i];
8007 g_string_append_c (temp, c);
8008 } else if (c == '_') {
8009 g_string_append_c (temp, '_');
8010 g_string_append_c (temp, '_');
8012 g_string_append_c (temp, '_');
8013 g_string_append_printf (temp, "%x", (int)c);
8016 temps = g_string_free (temp, FALSE);
8017 /* Include the length to avoid different length type names aliasing each other */
8018 g_string_append_printf (s, "cl%x_%s_", strlen (temps), temps);
8027 append_mangled_signature (GString *s, MonoMethodSignature *sig)
8032 supported = append_mangled_type (s, sig->ret);
8036 g_string_append_printf (s, "this_");
8037 for (i = 0; i < sig->param_count; ++i) {
8038 supported = append_mangled_type (s, sig->params [i]);
8047 * mono_aot_get_mangled_method_name:
8049 * Return a unique mangled name for METHOD, or NULL.
8052 mono_aot_get_mangled_method_name (MonoMethod *method)
8058 // FIXME: Add more cases
8059 if (method->wrapper_type != MONO_WRAPPER_UNKNOWN)
8061 info = mono_marshal_get_wrapper_info (method);
8062 if (!(info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG)))
8065 s = g_string_new ("");
8067 g_string_append_printf (s, "aot_method_w_");
8069 switch (info->subtype) {
8070 case WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG:
8071 g_string_append_printf (s, "gsharedvt_in_");
8073 case WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG:
8074 g_string_append_printf (s, "gsharedvt_out_");
8077 g_assert_not_reached ();
8081 supported = append_mangled_signature (s, info->d.gsharedvt.sig);
8083 g_string_free (s, TRUE);
8087 return g_string_free (s, FALSE);
8091 mono_aot_is_direct_callable (MonoJumpInfo *patch_info)
8093 return is_direct_callable (llvm_acfg, NULL, patch_info);
8097 mono_aot_mark_unused_llvm_plt_entry (MonoJumpInfo *patch_info)
8099 MonoPltEntry *plt_entry;
8101 plt_entry = get_plt_entry (llvm_acfg, patch_info);
8102 plt_entry->llvm_used = FALSE;
8106 mono_aot_get_direct_call_symbol (MonoJumpInfoType type, gconstpointer data)
8108 const char *sym = NULL;
8110 if (llvm_acfg->aot_opts.direct_icalls) {
8111 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8112 /* Call to a C function implementing a jit icall */
8113 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8114 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8115 MonoMethod *method = (MonoMethod *)data;
8116 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8117 sym = mono_lookup_icall_symbol (method);
8118 else if (llvm_acfg->aot_opts.direct_pinvoke)
8119 sym = get_pinvoke_import (llvm_acfg, method);
8122 return g_strdup (sym);
8128 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
8130 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
8131 MonoPltEntry *plt_entry;
8132 const char *sym = NULL;
8135 ji->data.target = data;
8137 if (!can_encode_patch (llvm_acfg, ji))
8140 if (llvm_acfg->aot_opts.direct_icalls) {
8141 if (type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8142 /* Call to a C function implementing a jit icall */
8143 sym = mono_lookup_jit_icall_symbol ((const char *)data);
8144 } else if (type == MONO_PATCH_INFO_ICALL_ADDR_CALL) {
8145 MonoMethod *method = (MonoMethod *)data;
8146 if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
8147 sym = mono_lookup_icall_symbol (method);
8150 return g_strdup (sym);
8153 plt_entry = get_plt_entry (llvm_acfg, ji);
8154 plt_entry->llvm_used = TRUE;
8156 #if defined(TARGET_MACH)
8157 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
8159 return g_strdup_printf (plt_entry->llvm_symbol);
8164 mono_aot_get_method_index (MonoMethod *method)
8166 g_assert (llvm_acfg);
8167 return get_method_index (llvm_acfg, method);
8171 mono_aot_patch_info_dup (MonoJumpInfo* ji)
8175 mono_acfg_lock (llvm_acfg);
8176 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
8177 mono_acfg_unlock (llvm_acfg);
8183 execute_system (const char * command)
8188 // We need an extra set of quotes around the whole command to properly handle commands
8189 // with spaces since internally the command is called through "cmd /c.
8190 command = g_strdup_printf ("\"%s\"", command);
8192 int size = MultiByteToWideChar (CP_UTF8, 0 , command , -1, NULL , 0);
8193 wchar_t* wstr = g_malloc (sizeof (wchar_t) * size);
8194 MultiByteToWideChar (CP_UTF8, 0, command, -1, wstr , size);
8195 status = _wsystem (wstr);
8199 #elif defined (HAVE_SYSTEM)
8200 status = system (command);
8202 g_assert_not_reached ();
8213 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
8217 emit_llvm_file (MonoAotCompile *acfg)
8219 char *command, *opts, *tempbc, *optbc, *output_fname;
8221 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only) {
8222 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8223 optbc = g_strdup (acfg->aot_opts.llvm_outfile);
8225 tempbc = g_strdup_printf ("%s.bc", acfg->tmpbasename);
8226 optbc = g_strdup_printf ("%s.opt.bc", acfg->tmpbasename);
8229 mono_llvm_emit_aot_module (tempbc, g_path_get_basename (acfg->image->name));
8232 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
8233 * a lot of time, and doesn't seem to save much space.
8234 * The following optimizations cannot be enabled:
8236 * - 'jump-threading' changes our blockaddress references to int constants.
8237 * - 'basiccg' fails because it contains:
8238 * if (CS && !isa<IntrinsicInst>(II)) {
8239 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
8240 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
8241 * The opt list below was produced by taking the output of:
8242 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
8243 * then removing tailcallelim + the global opts.
8244 * strip-dead-prototypes deletes unused intrinsics definitions.
8246 /* The dse pass is disabled because of #13734 and #17616 */
8248 * The dse bug is in DeadStoreElimination.cpp:isOverwrite ():
8249 * // If we have no DataLayout information around, then the size of the store
8250 * // is inferrable from the pointee type. If they are the same type, then
8251 * // we know that the store is safe.
8252 * if (AA.getDataLayout() == 0 &&
8253 * Later.Ptr->getType() == Earlier.Ptr->getType()) {
8254 * return OverwriteComplete;
8255 * Here, if 'Earlier' refers to a memset, and Later has no size info, it mistakenly thinks the memset is redundant.
8257 if (acfg->aot_opts.llvm_only)
8258 // FIXME: This doesn't work yet
8259 opts = g_strdup ("");
8261 #if LLVM_API_VERSION > 100
8262 opts = g_strdup ("-O2 -disable-tail-calls");
8264 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");
8266 command = g_strdup_printf ("\"%sopt\" -f %s -o \"%s\" \"%s\"", acfg->aot_opts.llvm_path, opts, optbc, tempbc);
8267 aot_printf (acfg, "Executing opt: %s\n", command);
8268 if (execute_system (command) != 0)
8272 if (acfg->aot_opts.llvm_only && acfg->aot_opts.asm_only)
8273 /* Nothing else to do */
8276 if (acfg->aot_opts.llvm_only) {
8277 /* Use the stock clang from xcode */
8279 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);
8281 aot_printf (acfg, "Executing clang: %s\n", command);
8282 if (execute_system (command) != 0)
8287 if (!acfg->llc_args)
8288 acfg->llc_args = g_string_new ("");
8290 /* Verbose asm slows down llc greatly */
8291 g_string_append (acfg->llc_args, " -asm-verbose=false");
8293 if (acfg->aot_opts.mtriple)
8294 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
8296 g_string_append (acfg->llc_args, " -disable-gnu-eh-frame -enable-mono-eh-frame");
8298 g_string_append_printf (acfg->llc_args, " -mono-eh-frame-symbol=%s%s", acfg->user_symbol_prefix, acfg->llvm_eh_frame_symbol);
8300 #if LLVM_API_VERSION > 100
8301 g_string_append_printf (acfg->llc_args, " -disable-tail-calls");
8304 #if defined(TARGET_MACH) && defined(TARGET_ARM)
8305 /* ios requires PIC code now */
8306 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8308 if (llvm_acfg->aot_opts.static_link)
8309 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
8311 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
8314 if (acfg->llvm_owriter) {
8315 /* Emit an object file directly */
8316 output_fname = g_strdup_printf ("%s", acfg->llvm_ofile);
8317 g_string_append_printf (acfg->llc_args, " -filetype=obj");
8319 output_fname = g_strdup_printf ("%s", acfg->llvm_sfile);
8321 command = g_strdup_printf ("\"%sllc\" %s -o \"%s\" \"%s.opt.bc\"", acfg->aot_opts.llvm_path, acfg->llc_args->str, output_fname, acfg->tmpbasename);
8322 g_free (output_fname);
8324 aot_printf (acfg, "Executing llc: %s\n", command);
8326 if (execute_system (command) != 0)
8333 emit_code (MonoAotCompile *acfg)
8335 int oindex, i, prev_index;
8336 gboolean saved_unbox_info = FALSE;
8337 char symbol [MAX_SYMBOL_SIZE];
8339 if (acfg->aot_opts.llvm_only)
8342 #if defined(TARGET_POWERPC64)
8343 sprintf (symbol, ".Lgot_addr");
8344 emit_section_change (acfg, ".text", 0);
8345 emit_alignment (acfg, 8);
8346 emit_label (acfg, symbol);
8347 emit_pointer (acfg, acfg->got_symbol);
8351 * This global symbol is used to compute the address of each method using the
8352 * code_offsets array. It is also used to compute the memory ranges occupied by
8353 * AOT code, so it must be equal to the address of the first emitted method.
8355 emit_section_change (acfg, ".text", 0);
8356 emit_alignment_code (acfg, 8);
8357 emit_info_symbol (acfg, "jit_code_start");
8360 * Emit some padding so the local symbol for the first method doesn't have the
8361 * same address as 'methods'.
8363 emit_padding (acfg, 16);
8365 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8369 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8371 cfg = acfg->cfgs [i];
8376 method = cfg->orig_method;
8378 /* Emit unbox trampoline */
8379 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8380 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
8382 emit_section_change (acfg, ".text", 0);
8384 if (acfg->thumb_mixed && cfg->compile_llvm) {
8385 emit_set_thumb_mode (acfg);
8386 fprintf (acfg->fp, "\n.thumb_func\n");
8389 emit_label (acfg, symbol);
8391 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
8393 if (acfg->thumb_mixed && cfg->compile_llvm)
8394 emit_set_arm_mode (acfg);
8396 if (!saved_unbox_info) {
8397 char user_symbol [128];
8399 sprintf (user_symbol, "%sunbox_trampoline_p", acfg->user_symbol_prefix);
8401 emit_label (acfg, "ut_end");
8403 unwind_ops = mono_unwind_get_cie_program ();
8404 save_unwind_info (acfg, user_symbol, unwind_ops);
8405 mono_free_unwind_info (unwind_ops);
8407 /* Save the unbox trampoline size */
8408 emit_symbol_diff (acfg, "ut_end", symbol, 0);
8410 saved_unbox_info = TRUE;
8414 if (cfg->compile_llvm)
8415 acfg->stats.llvm_count ++;
8417 emit_method_code (acfg, cfg);
8420 emit_section_change (acfg, ".text", 0);
8421 emit_alignment_code (acfg, 8);
8422 emit_info_symbol (acfg, "jit_code_end");
8424 /* To distinguish it from the next symbol */
8425 emit_padding (acfg, 4);
8428 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
8429 * from optimizing them away, since it doesn't see that code_offsets references them.
8430 * JITted methods don't need this since they are referenced using assembler local
8432 * FIXME: This is why write-symbols doesn't work on OSX ?
8434 if (acfg->llvm && acfg->need_no_dead_strip) {
8435 fprintf (acfg->fp, "\n");
8436 for (i = 0; i < acfg->nmethods; ++i) {
8437 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
8438 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
8443 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
8444 * This is PIE code, and the linker can update it if needed.
8447 sprintf (symbol, "method_addresses");
8448 emit_section_change (acfg, ".text", 1);
8449 emit_alignment_code (acfg, 8);
8450 emit_info_symbol (acfg, symbol);
8451 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
8452 emit_unset_mode (acfg);
8453 if (acfg->need_no_dead_strip)
8454 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
8456 for (i = 0; i < acfg->nmethods; ++i) {
8457 #ifdef MONO_ARCH_AOT_SUPPORTED
8460 if (acfg->cfgs [i]) {
8461 arch_emit_direct_call (acfg, acfg->cfgs [i]->asm_symbol, FALSE, acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm, NULL, &call_size);
8463 arch_emit_direct_call (acfg, symbol, FALSE, FALSE, NULL, &call_size);
8468 sprintf (symbol, "method_addresses_end");
8469 emit_label (acfg, symbol);
8472 /* Emit a sorted table mapping methods to the index of their unbox trampolines */
8473 sprintf (symbol, "unbox_trampolines");
8474 emit_section_change (acfg, RODATA_SECT, 0);
8475 emit_alignment (acfg, 8);
8476 emit_info_symbol (acfg, symbol);
8479 for (i = 0; i < acfg->nmethods; ++i) {
8484 cfg = acfg->cfgs [i];
8488 method = cfg->orig_method;
8490 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8491 index = get_method_index (acfg, method);
8493 emit_int32 (acfg, index);
8494 /* Make sure the table is sorted by index */
8495 g_assert (index > prev_index);
8499 sprintf (symbol, "unbox_trampolines_end");
8500 emit_info_symbol (acfg, symbol);
8501 emit_int32 (acfg, 0);
8503 /* Emit a separate table with the trampoline addresses/offsets */
8504 sprintf (symbol, "unbox_trampoline_addresses");
8505 emit_section_change (acfg, ".text", 0);
8506 emit_alignment_code (acfg, 8);
8507 emit_info_symbol (acfg, symbol);
8509 for (i = 0; i < acfg->nmethods; ++i) {
8514 cfg = acfg->cfgs [i];
8518 method = cfg->orig_method;
8520 if (mono_aot_mode_is_full (&acfg->aot_opts) && cfg->orig_method->klass->valuetype) {
8521 #ifdef MONO_ARCH_AOT_SUPPORTED
8524 index = get_method_index (acfg, method);
8525 sprintf (symbol, "ut_%d", index);
8527 arch_emit_direct_call (acfg, symbol, FALSE, acfg->thumb_mixed && cfg->compile_llvm, NULL, &call_size);
8531 emit_int32 (acfg, 0);
8535 emit_info (MonoAotCompile *acfg)
8540 offsets = g_new0 (gint32, acfg->nmethods);
8542 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
8543 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
8545 if (acfg->cfgs [i]) {
8546 emit_method_info (acfg, acfg->cfgs [i]);
8547 offsets [i] = acfg->cfgs [i]->method_info_offset;
8553 acfg->stats.offsets_size += emit_offset_table (acfg, "method_info_offsets", MONO_AOT_TABLE_METHOD_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8558 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
8560 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
8561 #define mix(a,b,c) { \
8562 a -= c; a ^= rot(c, 4); c += b; \
8563 b -= a; b ^= rot(a, 6); a += c; \
8564 c -= b; c ^= rot(b, 8); b += a; \
8565 a -= c; a ^= rot(c,16); c += b; \
8566 b -= a; b ^= rot(a,19); a += c; \
8567 c -= b; c ^= rot(b, 4); b += a; \
8569 #define final(a,b,c) { \
8570 c ^= b; c -= rot(b,14); \
8571 a ^= c; a -= rot(c,11); \
8572 b ^= a; b -= rot(a,25); \
8573 c ^= b; c -= rot(b,16); \
8574 a ^= c; a -= rot(c,4); \
8575 b ^= a; b -= rot(a,14); \
8576 c ^= b; c -= rot(b,24); \
8580 mono_aot_type_hash (MonoType *t1)
8582 guint hash = t1->type;
8584 hash |= t1->byref << 6; /* do not collide with t1->type values */
8586 case MONO_TYPE_VALUETYPE:
8587 case MONO_TYPE_CLASS:
8588 case MONO_TYPE_SZARRAY:
8589 /* check if the distribution is good enough */
8590 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
8592 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
8593 case MONO_TYPE_ARRAY:
8594 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
8595 case MONO_TYPE_GENERICINST:
8596 return ((hash << 5) - hash) ^ 0;
8603 * mono_aot_method_hash:
8605 * Return a hash code for methods which only depends on metadata.
8608 mono_aot_method_hash (MonoMethod *method)
8610 MonoMethodSignature *sig;
8614 guint32 *hashes_start, *hashes;
8616 MonoGenericInst *class_ginst = NULL;
8617 MonoGenericInst *ginst = NULL;
8619 /* Similar to the hash in mono_method_get_imt_slot () */
8621 sig = mono_method_signature (method);
8623 if (method->klass->generic_class)
8624 class_ginst = method->klass->generic_class->context.class_inst;
8625 if (method->is_inflated)
8626 ginst = ((MonoMethodInflated*)method)->context.method_inst;
8628 hashes_count = sig->param_count + 5 + (class_ginst ? class_ginst->type_argc : 0) + (ginst ? ginst->type_argc : 0);
8629 hashes_start = (guint32 *)g_malloc0 (hashes_count * sizeof (guint32));
8630 hashes = hashes_start;
8632 /* Some wrappers are assigned to random classes */
8633 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
8634 klass = method->klass;
8636 klass = mono_defaults.object_class;
8638 if (!method->wrapper_type) {
8641 if (klass->generic_class)
8642 full_name = mono_type_full_name (&klass->generic_class->container_class->byval_arg);
8644 full_name = mono_type_full_name (&klass->byval_arg);
8646 hashes [0] = mono_metadata_str_hash (full_name);
8650 hashes [0] = mono_metadata_str_hash (klass->name);
8651 hashes [1] = mono_metadata_str_hash (klass->name_space);
8653 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
8654 /* The method name includes a stringified pointer */
8657 hashes [2] = mono_metadata_str_hash (method->name);
8658 hashes [3] = method->wrapper_type;
8659 hashes [4] = mono_aot_type_hash (sig->ret);
8661 for (i = 0; i < sig->param_count; i++) {
8662 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
8665 for (i = 0; i < class_ginst->type_argc; ++i)
8666 hashes [hindex ++] = mono_aot_type_hash (class_ginst->type_argv [i]);
8669 for (i = 0; i < ginst->type_argc; ++i)
8670 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
8672 g_assert (hindex == hashes_count);
8674 /* Setup internal state */
8675 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
8677 /* Handle most of the hashes */
8678 while (hashes_count > 3) {
8687 /* Handle the last 3 hashes (all the case statements fall through) */
8688 switch (hashes_count) {
8689 case 3 : c += hashes [2];
8690 case 2 : b += hashes [1];
8691 case 1 : a += hashes [0];
8693 case 0: /* nothing left to add */
8697 g_free (hashes_start);
8706 * mono_aot_get_array_helper_from_wrapper;
8708 * Get the helper method in Array called by an array wrapper method.
8711 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
8715 MonoGenericContext ctx;
8716 MonoType *args [16];
8717 char *mname, *iname, *s, *s2, *helper_name = NULL;
8719 prefix = "System.Collections.Generic";
8720 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
8721 s2 = strstr (s, "`1.");
8727 //printf ("X: %s %s\n", iname, mname);
8729 if (!strcmp (iname, "IList"))
8730 helper_name = g_strdup_printf ("InternalArray__%s", mname);
8732 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
8733 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
8735 g_free (helper_name);
8738 if (m->is_generic) {
8740 memset (&ctx, 0, sizeof (ctx));
8741 args [0] = &method->klass->element_class->byval_arg;
8742 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
8743 m = mono_class_inflate_generic_method_checked (m, &ctx, &error);
8744 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8750 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
8752 typedef struct HashEntry {
8753 guint32 key, value, index;
8754 struct HashEntry *next;
8758 * emit_extra_methods:
8760 * Emit methods which are not in the METHOD table, like wrappers.
8763 emit_extra_methods (MonoAotCompile *acfg)
8765 int i, table_size, buf_size;
8767 guint32 *info_offsets;
8770 HashEntry *entry, *new_entry;
8771 int nmethods, max_chain_length;
8774 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
8776 /* Emit method info */
8778 for (i = 0; i < acfg->extra_methods->len; ++i) {
8779 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8780 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8786 p = buf = (guint8 *)g_malloc (buf_size);
8790 method = cfg->method_to_register;
8792 encode_method_ref (acfg, method, p, &p);
8794 g_assert ((p - buf) < buf_size);
8796 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
8801 * Construct a chained hash table for mapping indexes in extra_method_info to
8804 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
8805 table = g_ptr_array_sized_new (table_size);
8806 for (i = 0; i < table_size; ++i)
8807 g_ptr_array_add (table, NULL);
8808 chain_lengths = g_new0 (int, table_size);
8809 max_chain_length = 0;
8810 for (i = 0; i < acfg->extra_methods->len; ++i) {
8811 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8812 MonoCompile *cfg = (MonoCompile *)g_hash_table_lookup (acfg->method_to_cfg, method);
8818 key = info_offsets [i];
8819 value = get_method_index (acfg, method);
8821 hash = mono_aot_method_hash (method) % table_size;
8822 //printf ("X: %s %x\n", mono_method_get_full_name (method), mono_aot_method_hash (method));
8824 chain_lengths [hash] ++;
8825 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
8827 new_entry = (HashEntry *)mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
8828 new_entry->key = key;
8829 new_entry->value = value;
8831 entry = (HashEntry *)g_ptr_array_index (table, hash);
8832 if (entry == NULL) {
8833 new_entry->index = hash;
8834 g_ptr_array_index (table, hash) = new_entry;
8837 entry = entry->next;
8839 entry->next = new_entry;
8840 new_entry->index = table->len;
8841 g_ptr_array_add (table, new_entry);
8844 g_free (chain_lengths);
8846 //printf ("MAX: %d\n", max_chain_length);
8848 buf_size = table->len * 12 + 4;
8849 p = buf = (guint8 *)g_malloc (buf_size);
8850 encode_int (table_size, p, &p);
8852 for (i = 0; i < table->len; ++i) {
8853 HashEntry *entry = (HashEntry *)g_ptr_array_index (table, i);
8855 if (entry == NULL) {
8856 encode_int (0, p, &p);
8857 encode_int (0, p, &p);
8858 encode_int (0, p, &p);
8860 //g_assert (entry->key > 0);
8861 encode_int (entry->key, p, &p);
8862 encode_int (entry->value, p, &p);
8864 encode_int (entry->next->index, p, &p);
8866 encode_int (0, p, &p);
8869 g_assert (p - buf <= buf_size);
8871 /* Emit the table */
8872 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_TABLE, "extra_method_table", buf, p - buf);
8877 * Emit a table reverse mapping method indexes to their index in extra_method_info.
8878 * This is used by mono_aot_find_jit_info ().
8880 buf_size = acfg->extra_methods->len * 8 + 4;
8881 p = buf = (guint8 *)g_malloc (buf_size);
8882 encode_int (acfg->extra_methods->len, p, &p);
8883 for (i = 0; i < acfg->extra_methods->len; ++i) {
8884 MonoMethod *method = (MonoMethod *)g_ptr_array_index (acfg->extra_methods, i);
8886 encode_int (get_method_index (acfg, method), p, &p);
8887 encode_int (info_offsets [i], p, &p);
8889 emit_aot_data (acfg, MONO_AOT_TABLE_EXTRA_METHOD_INFO_OFFSETS, "extra_method_info_offsets", buf, p - buf);
8892 g_free (info_offsets);
8893 g_ptr_array_free (table, TRUE);
8897 generate_aotid (guint8* aotid)
8899 gpointer rand_handle;
8903 rand_handle = mono_rand_init (NULL, 0);
8905 mono_rand_try_get_bytes (&rand_handle, aotid, 16, &error);
8906 mono_error_assert_ok (&error);
8908 mono_rand_close (rand_handle);
8912 emit_exception_info (MonoAotCompile *acfg)
8916 SeqPointData sp_data;
8917 gboolean seq_points_to_file = FALSE;
8919 offsets = g_new0 (gint32, acfg->nmethods);
8920 for (i = 0; i < acfg->nmethods; ++i) {
8921 if (acfg->cfgs [i]) {
8922 MonoCompile *cfg = acfg->cfgs [i];
8924 // By design aot-runtime decode_exception_debug_info is not able to load sequence point debug data from a file.
8925 // As it is not possible to load debug data from a file its is also not possible to store it in a file.
8926 gboolean method_seq_points_to_file = acfg->aot_opts.gen_msym_dir &&
8927 cfg->gen_seq_points && !cfg->gen_sdb_seq_points;
8928 gboolean method_seq_points_to_binary = cfg->gen_seq_points && !method_seq_points_to_file;
8930 emit_exception_debug_info (acfg, cfg, method_seq_points_to_binary);
8931 offsets [i] = cfg->ex_info_offset;
8933 if (method_seq_points_to_file) {
8934 if (!seq_points_to_file) {
8935 mono_seq_point_data_init (&sp_data, acfg->nmethods);
8936 seq_points_to_file = TRUE;
8938 mono_seq_point_data_add (&sp_data, cfg->method->token, cfg->method_index, cfg->seq_point_info);
8945 if (seq_points_to_file) {
8946 char *aotid = mono_guid_to_string_minimal (acfg->image->aotid);
8947 char *dir = g_build_filename (acfg->aot_opts.gen_msym_dir_path, aotid, NULL);
8948 char *image_basename = g_path_get_basename (acfg->image->name);
8949 char *aot_file = g_strdup_printf("%s%s", image_basename, SEQ_POINT_AOT_EXT);
8950 char *aot_file_path = g_build_filename (dir, aot_file, NULL);
8952 if (g_ensure_directory_exists (aot_file_path) == FALSE) {
8953 fprintf (stderr, "AOT : failed to create msym directory: %s\n", aot_file_path);
8957 mono_seq_point_data_write (&sp_data, aot_file_path);
8958 mono_seq_point_data_free (&sp_data);
8962 g_free (image_basename);
8964 g_free (aot_file_path);
8967 acfg->stats.offsets_size += emit_offset_table (acfg, "ex_info_offsets", MONO_AOT_TABLE_EX_INFO_OFFSETS, acfg->nmethods, 10, offsets);
8972 emit_unwind_info (MonoAotCompile *acfg)
8977 if (acfg->aot_opts.llvm_only) {
8978 g_assert (acfg->unwind_ops->len == 0);
8983 * The unwind info contains a lot of duplicates so we emit each unique
8984 * entry once, and only store the offset from the start of the table in the
8988 sprintf (symbol, "unwind_info");
8989 emit_section_change (acfg, RODATA_SECT, 1);
8990 emit_alignment (acfg, 8);
8991 emit_info_symbol (acfg, symbol);
8993 for (i = 0; i < acfg->unwind_ops->len; ++i) {
8994 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
8995 guint8 *unwind_info;
8996 guint32 unwind_info_len;
9000 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
9003 encode_value (unwind_info_len, p, &p);
9004 emit_bytes (acfg, buf, p - buf);
9005 emit_bytes (acfg, unwind_info, unwind_info_len);
9007 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
9012 emit_class_info (MonoAotCompile *acfg)
9017 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
9018 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
9019 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
9021 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);
9025 typedef struct ClassNameTableEntry {
9026 guint32 token, index;
9027 struct ClassNameTableEntry *next;
9028 } ClassNameTableEntry;
9031 emit_class_name_table (MonoAotCompile *acfg)
9033 int i, table_size, buf_size;
9034 guint32 token, hash;
9039 ClassNameTableEntry *entry, *new_entry;
9042 * Construct a chained hash table for mapping class names to typedef tokens.
9044 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
9045 table = g_ptr_array_sized_new (table_size);
9046 for (i = 0; i < table_size; ++i)
9047 g_ptr_array_add (table, NULL);
9048 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
9050 token = MONO_TOKEN_TYPE_DEF | (i + 1);
9051 klass = mono_class_get_checked (acfg->image, token, &error);
9053 mono_error_cleanup (&error);
9056 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
9057 hash = mono_metadata_str_hash (full_name) % table_size;
9060 /* FIXME: Allocate from the mempool */
9061 new_entry = g_new0 (ClassNameTableEntry, 1);
9062 new_entry->token = token;
9064 entry = (ClassNameTableEntry *)g_ptr_array_index (table, hash);
9065 if (entry == NULL) {
9066 new_entry->index = hash;
9067 g_ptr_array_index (table, hash) = new_entry;
9070 entry = entry->next;
9072 entry->next = new_entry;
9073 new_entry->index = table->len;
9074 g_ptr_array_add (table, new_entry);
9078 /* Emit the table */
9079 buf_size = table->len * 4 + 4;
9080 p = buf = (guint8 *)g_malloc0 (buf_size);
9082 /* FIXME: Optimize memory usage */
9083 g_assert (table_size < 65000);
9084 encode_int16 (table_size, p, &p);
9085 g_assert (table->len < 65000);
9086 for (i = 0; i < table->len; ++i) {
9087 ClassNameTableEntry *entry = (ClassNameTableEntry *)g_ptr_array_index (table, i);
9089 if (entry == NULL) {
9090 encode_int16 (0, p, &p);
9091 encode_int16 (0, p, &p);
9093 encode_int16 (mono_metadata_token_index (entry->token), p, &p);
9095 encode_int16 (entry->next->index, p, &p);
9097 encode_int16 (0, p, &p);
9101 g_assert (p - buf <= buf_size);
9102 g_ptr_array_free (table, TRUE);
9104 emit_aot_data (acfg, MONO_AOT_TABLE_CLASS_NAME, "class_name_table", buf, p - buf);
9110 emit_image_table (MonoAotCompile *acfg)
9116 * The image table is small but referenced in a lot of places.
9117 * So we emit it at once, and reference its elements by an index.
9119 buf_size = acfg->image_table->len * 28 + 4;
9120 for (i = 0; i < acfg->image_table->len; i++) {
9121 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9122 MonoAssemblyName *aname = &image->assembly->aname;
9124 buf_size += strlen (image->assembly_name) + strlen (image->guid) + (aname->culture ? strlen (aname->culture) : 1) + strlen ((char*)aname->public_key_token) + 4;
9127 buf = p = (guint8 *)g_malloc0 (buf_size);
9128 encode_int (acfg->image_table->len, p, &p);
9129 for (i = 0; i < acfg->image_table->len; i++) {
9130 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
9131 MonoAssemblyName *aname = &image->assembly->aname;
9133 /* FIXME: Support multi-module assemblies */
9134 g_assert (image->assembly->image == image);
9136 encode_string (image->assembly_name, p, &p);
9137 encode_string (image->guid, p, &p);
9138 encode_string (aname->culture ? aname->culture : "", p, &p);
9139 encode_string ((const char*)aname->public_key_token, p, &p);
9141 while (GPOINTER_TO_UINT (p) % 8 != 0)
9144 encode_int (aname->flags, p, &p);
9145 encode_int (aname->major, p, &p);
9146 encode_int (aname->minor, p, &p);
9147 encode_int (aname->build, p, &p);
9148 encode_int (aname->revision, p, &p);
9150 g_assert (p - buf <= buf_size);
9152 emit_aot_data (acfg, MONO_AOT_TABLE_IMAGE_TABLE, "image_table", buf, p - buf);
9158 emit_got_info (MonoAotCompile *acfg, gboolean llvm)
9160 int i, first_plt_got_patch = 0, buf_size;
9162 guint32 *got_info_offsets;
9163 GotInfo *info = llvm ? &acfg->llvm_got_info : &acfg->got_info;
9165 /* Add the patches needed by the PLT to the GOT */
9167 acfg->plt_got_offset_base = acfg->got_offset;
9168 first_plt_got_patch = info->got_patches->len;
9169 for (i = 1; i < acfg->plt_offset; ++i) {
9170 MonoPltEntry *plt_entry = (MonoPltEntry *)g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
9172 g_ptr_array_add (info->got_patches, plt_entry->ji);
9174 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
9177 acfg->got_offset += acfg->plt_offset;
9182 * - optimize offsets table.
9183 * - reduce number of exported symbols.
9184 * - emit info for a klass only once.
9185 * - determine when a method uses a GOT slot which is guaranteed to be already
9187 * - clean up and document the code.
9188 * - use String.Empty in class libs.
9191 /* Encode info required to decode shared GOT entries */
9192 buf_size = info->got_patches->len * 128;
9193 p = buf = (guint8 *)mono_mempool_alloc (acfg->mempool, buf_size);
9194 got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, info->got_patches->len * sizeof (guint32));
9196 acfg->plt_got_info_offsets = (guint32 *)mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
9198 if (acfg->plt_offset)
9199 acfg->plt_got_info_offsets [0] = 0;
9201 for (i = 0; i < info->got_patches->len; ++i) {
9202 MonoJumpInfo *ji = (MonoJumpInfo *)g_ptr_array_index (info->got_patches, i);
9207 encode_value (ji->type, p, &p);
9209 encode_patch (acfg, ji, p, &p);
9210 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
9211 g_assert (p - buf <= buf_size);
9212 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
9214 if (!llvm && i >= first_plt_got_patch)
9215 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
9216 acfg->stats.got_info_size += p - buf;
9219 /* Emit got_info_offsets table */
9221 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
9222 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);
9226 emit_got (MonoAotCompile *acfg)
9228 char symbol [MAX_SYMBOL_SIZE];
9230 if (acfg->aot_opts.llvm_only)
9233 /* Don't make GOT global so accesses to it don't need relocations */
9234 sprintf (symbol, "%s", acfg->got_symbol);
9237 emit_unset_mode (acfg);
9238 fprintf (acfg->fp, ".section __DATA, __bss\n");
9239 emit_alignment (acfg, 8);
9241 emit_info_symbol (acfg, "jit_got");
9242 fprintf (acfg->fp, ".lcomm %s, %d\n", acfg->got_symbol, (int)(acfg->got_offset * sizeof (gpointer)));
9244 emit_section_change (acfg, ".bss", 0);
9245 emit_alignment (acfg, 8);
9246 emit_local_symbol (acfg, symbol, "got_end", FALSE);
9247 emit_label (acfg, symbol);
9249 emit_info_symbol (acfg, "jit_got");
9250 if (acfg->got_offset > 0)
9251 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
9254 sprintf (symbol, "got_end");
9255 emit_label (acfg, symbol);
9258 typedef struct GlobalsTableEntry {
9259 guint32 value, index;
9260 struct GlobalsTableEntry *next;
9261 } GlobalsTableEntry;
9264 emit_globals (MonoAotCompile *acfg)
9270 GlobalsTableEntry *entry, *new_entry;
9272 if (!acfg->aot_opts.static_link)
9274 if (acfg->aot_opts.llvm_only) {
9275 g_assert (acfg->globals->len == 0);
9280 * When static linking, we emit a table containing our globals.
9284 * Construct a chained hash table for mapping global names to their index in
9285 * the globals table.
9287 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
9288 table = g_ptr_array_sized_new (table_size);
9289 for (i = 0; i < table_size; ++i)
9290 g_ptr_array_add (table, NULL);
9291 for (i = 0; i < acfg->globals->len; ++i) {
9292 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9294 hash = mono_metadata_str_hash (name) % table_size;
9296 /* FIXME: Allocate from the mempool */
9297 new_entry = g_new0 (GlobalsTableEntry, 1);
9298 new_entry->value = i;
9300 entry = (GlobalsTableEntry *)g_ptr_array_index (table, hash);
9301 if (entry == NULL) {
9302 new_entry->index = hash;
9303 g_ptr_array_index (table, hash) = new_entry;
9306 entry = entry->next;
9308 entry->next = new_entry;
9309 new_entry->index = table->len;
9310 g_ptr_array_add (table, new_entry);
9314 /* Emit the table */
9315 sprintf (symbol, ".Lglobals_hash");
9316 emit_section_change (acfg, RODATA_SECT, 0);
9317 emit_alignment (acfg, 8);
9318 emit_label (acfg, symbol);
9320 /* FIXME: Optimize memory usage */
9321 g_assert (table_size < 65000);
9322 emit_int16 (acfg, table_size);
9323 for (i = 0; i < table->len; ++i) {
9324 GlobalsTableEntry *entry = (GlobalsTableEntry *)g_ptr_array_index (table, i);
9326 if (entry == NULL) {
9327 emit_int16 (acfg, 0);
9328 emit_int16 (acfg, 0);
9330 emit_int16 (acfg, entry->value + 1);
9332 emit_int16 (acfg, entry->next->index);
9334 emit_int16 (acfg, 0);
9338 /* Emit the names */
9339 for (i = 0; i < acfg->globals->len; ++i) {
9340 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9342 sprintf (symbol, "name_%d", i);
9343 emit_section_change (acfg, RODATA_SECT, 1);
9345 emit_alignment (acfg, 4);
9347 emit_label (acfg, symbol);
9348 emit_string (acfg, name);
9351 /* Emit the globals table */
9352 sprintf (symbol, "globals");
9353 emit_section_change (acfg, ".data", 0);
9354 /* This is not a global, since it is accessed by the init function */
9355 emit_alignment (acfg, 8);
9356 emit_info_symbol (acfg, symbol);
9358 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
9359 emit_pointer (acfg, symbol);
9361 for (i = 0; i < acfg->globals->len; ++i) {
9362 char *name = (char *)g_ptr_array_index (acfg->globals, i);
9364 sprintf (symbol, "name_%d", i);
9365 emit_pointer (acfg, symbol);
9367 g_assert (strlen (name) < sizeof (symbol));
9368 sprintf (symbol, "%s", name);
9369 emit_pointer (acfg, symbol);
9371 /* Null terminate the table */
9372 emit_int32 (acfg, 0);
9373 emit_int32 (acfg, 0);
9377 emit_mem_end (MonoAotCompile *acfg)
9381 if (acfg->aot_opts.llvm_only)
9384 sprintf (symbol, "mem_end");
9385 emit_section_change (acfg, ".text", 1);
9386 emit_alignment_code (acfg, 8);
9387 emit_label (acfg, symbol);
9391 init_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9395 info->version = MONO_AOT_FILE_VERSION;
9396 info->plt_got_offset_base = acfg->plt_got_offset_base;
9397 info->got_size = acfg->got_offset * sizeof (gpointer);
9398 info->plt_size = acfg->plt_offset;
9399 info->nmethods = acfg->nmethods;
9400 info->flags = acfg->flags;
9401 info->opts = acfg->opts;
9402 info->simd_opts = acfg->simd_opts;
9403 info->gc_name_index = acfg->gc_name_offset;
9404 info->datafile_size = acfg->datafile_offset;
9405 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9406 info->table_offsets [i] = acfg->table_offsets [i];
9407 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9408 info->num_trampolines [i] = acfg->num_trampolines [i];
9409 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9410 info->trampoline_got_offset_base [i] = acfg->trampoline_got_offset_base [i];
9411 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9412 info->trampoline_size [i] = acfg->trampoline_size [i];
9413 info->num_rgctx_fetch_trampolines = acfg->aot_opts.nrgctx_fetch_trampolines;
9415 info->double_align = MONO_ABI_ALIGNOF (double);
9416 info->long_align = MONO_ABI_ALIGNOF (gint64);
9417 info->generic_tramp_num = MONO_TRAMPOLINE_NUM;
9418 info->tramp_page_size = acfg->tramp_page_size;
9419 info->nshared_got_entries = acfg->nshared_got_entries;
9420 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9421 info->tramp_page_code_offsets [i] = acfg->tramp_page_code_offsets [i];
9423 memcpy(&info->aotid, acfg->image->aotid, 16);
9427 emit_aot_file_info (MonoAotCompile *acfg, MonoAotFileInfo *info)
9429 char symbol [MAX_SYMBOL_SIZE];
9431 const char **symbols;
9433 symbols = g_new0 (const char *, MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9435 symbols [sindex ++] = acfg->got_symbol;
9437 symbols [sindex ++] = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, acfg->llvm_got_symbol);
9438 symbols [sindex ++] = acfg->llvm_eh_frame_symbol;
9440 symbols [sindex ++] = NULL;
9441 symbols [sindex ++] = NULL;
9443 /* llvm_get_method */
9444 symbols [sindex ++] = NULL;
9445 /* llvm_get_unbox_tramp */
9446 symbols [sindex ++] = NULL;
9447 if (!acfg->aot_opts.llvm_only) {
9448 symbols [sindex ++] = "jit_code_start";
9449 symbols [sindex ++] = "jit_code_end";
9450 symbols [sindex ++] = "method_addresses";
9452 symbols [sindex ++] = NULL;
9453 symbols [sindex ++] = NULL;
9454 symbols [sindex ++] = NULL;
9456 if (acfg->data_outfile) {
9457 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9458 symbols [sindex ++] = NULL;
9460 symbols [sindex ++] = "blob";
9461 symbols [sindex ++] = "class_name_table";
9462 symbols [sindex ++] = "class_info_offsets";
9463 symbols [sindex ++] = "method_info_offsets";
9464 symbols [sindex ++] = "ex_info_offsets";
9465 symbols [sindex ++] = "extra_method_info_offsets";
9466 symbols [sindex ++] = "extra_method_table";
9467 symbols [sindex ++] = "got_info_offsets";
9469 symbols [sindex ++] = "llvm_got_info_offsets";
9471 symbols [sindex ++] = NULL;
9472 symbols [sindex ++] = "image_table";
9474 symbols [sindex ++] = "mem_end";
9475 symbols [sindex ++] = "assembly_guid";
9476 symbols [sindex ++] = "runtime_version";
9477 if (acfg->num_trampoline_got_entries) {
9478 symbols [sindex ++] = "specific_trampolines";
9479 symbols [sindex ++] = "static_rgctx_trampolines";
9480 symbols [sindex ++] = "imt_trampolines";
9481 symbols [sindex ++] = "gsharedvt_arg_trampolines";
9483 symbols [sindex ++] = NULL;
9484 symbols [sindex ++] = NULL;
9485 symbols [sindex ++] = NULL;
9486 symbols [sindex ++] = NULL;
9488 if (acfg->aot_opts.static_link) {
9489 symbols [sindex ++] = "globals";
9491 symbols [sindex ++] = NULL;
9493 symbols [sindex ++] = "assembly_name";
9494 symbols [sindex ++] = "plt";
9495 symbols [sindex ++] = "plt_end";
9496 symbols [sindex ++] = "unwind_info";
9497 if (!acfg->aot_opts.llvm_only) {
9498 symbols [sindex ++] = "unbox_trampolines";
9499 symbols [sindex ++] = "unbox_trampolines_end";
9500 symbols [sindex ++] = "unbox_trampoline_addresses";
9502 symbols [sindex ++] = NULL;
9503 symbols [sindex ++] = NULL;
9504 symbols [sindex ++] = NULL;
9507 g_assert (sindex == MONO_AOT_FILE_INFO_NUM_SYMBOLS);
9509 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
9510 emit_section_change (acfg, ".data", 0);
9511 emit_alignment (acfg, 8);
9512 emit_label (acfg, symbol);
9513 if (!acfg->aot_opts.static_link)
9514 emit_global (acfg, symbol, FALSE);
9516 /* The data emitted here must match MonoAotFileInfo. */
9518 emit_int32 (acfg, info->version);
9519 emit_int32 (acfg, info->dummy);
9522 * We emit pointers to our data structures instead of emitting global symbols which
9523 * point to them, to reduce the number of globals, and because using globals leads to
9524 * various problems (i.e. arm/thumb).
9526 for (i = 0; i < MONO_AOT_FILE_INFO_NUM_SYMBOLS; ++i)
9527 emit_pointer (acfg, symbols [i]);
9529 emit_int32 (acfg, info->plt_got_offset_base);
9530 emit_int32 (acfg, info->got_size);
9531 emit_int32 (acfg, info->plt_size);
9532 emit_int32 (acfg, info->nmethods);
9533 emit_int32 (acfg, info->flags);
9534 emit_int32 (acfg, info->opts);
9535 emit_int32 (acfg, info->simd_opts);
9536 emit_int32 (acfg, info->gc_name_index);
9537 emit_int32 (acfg, info->num_rgctx_fetch_trampolines);
9538 emit_int32 (acfg, info->double_align);
9539 emit_int32 (acfg, info->long_align);
9540 emit_int32 (acfg, info->generic_tramp_num);
9541 emit_int32 (acfg, info->tramp_page_size);
9542 emit_int32 (acfg, info->nshared_got_entries);
9543 emit_int32 (acfg, info->datafile_size);
9545 for (i = 0; i < MONO_AOT_TABLE_NUM; ++i)
9546 emit_int32 (acfg, info->table_offsets [i]);
9547 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9548 emit_int32 (acfg, info->num_trampolines [i]);
9549 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9550 emit_int32 (acfg, info->trampoline_got_offset_base [i]);
9551 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9552 emit_int32 (acfg, info->trampoline_size [i]);
9553 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
9554 emit_int32 (acfg, info->tramp_page_code_offsets [i]);
9556 emit_bytes (acfg, info->aotid, 16);
9558 if (acfg->aot_opts.static_link) {
9559 emit_global_inner (acfg, acfg->static_linking_symbol, FALSE);
9560 emit_alignment (acfg, sizeof (gpointer));
9561 emit_label (acfg, acfg->static_linking_symbol);
9562 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
9567 * Emit a structure containing all the information not stored elsewhere.
9570 emit_file_info (MonoAotCompile *acfg)
9573 MonoAotFileInfo *info;
9575 if (acfg->aot_opts.bind_to_runtime_version) {
9576 build_info = mono_get_runtime_build_info ();
9577 emit_string_symbol (acfg, "runtime_version", build_info);
9578 g_free (build_info);
9580 emit_string_symbol (acfg, "runtime_version", "");
9583 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
9585 /* Emit a string holding the assembly name */
9586 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
9588 info = g_new0 (MonoAotFileInfo, 1);
9589 init_aot_file_info (acfg, info);
9591 if (acfg->aot_opts.static_link) {
9592 char symbol [MAX_SYMBOL_SIZE];
9596 * Emit a global symbol which can be passed by an embedding app to
9597 * mono_aot_register_module (). The symbol points to a pointer to the the file info
9600 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
9602 /* Get rid of characters which cannot occur in symbols */
9604 for (p = symbol; *p; ++p) {
9605 if (!(isalnum (*p) || *p == '_'))
9608 acfg->static_linking_symbol = g_strdup (symbol);
9612 mono_llvm_emit_aot_file_info (info, acfg->has_jitted_code);
9614 emit_aot_file_info (acfg, info);
9618 emit_blob (MonoAotCompile *acfg)
9620 acfg->blob_closed = TRUE;
9622 emit_aot_data (acfg, MONO_AOT_TABLE_BLOB, "blob", (guint8*)acfg->blob.data, acfg->blob.index);
9626 emit_objc_selectors (MonoAotCompile *acfg)
9631 if (!acfg->objc_selectors || acfg->objc_selectors->len == 0)
9636 * cat > foo.m << EOF
9639 * return @selector(print:);
9644 mono_img_writer_emit_unset_mode (acfg->w);
9645 g_assert (acfg->fp);
9646 fprintf (acfg->fp, ".section __DATA,__objc_selrefs,literal_pointers,no_dead_strip\n");
9647 fprintf (acfg->fp, ".align 3\n");
9648 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9649 sprintf (symbol, "L_OBJC_SELECTOR_REFERENCES_%d", i);
9650 emit_label (acfg, symbol);
9651 sprintf (symbol, "L_OBJC_METH_VAR_NAME_%d", i);
9652 emit_pointer (acfg, symbol);
9655 fprintf (acfg->fp, ".section __TEXT,__cstring,cstring_literals\n");
9656 for (i = 0; i < acfg->objc_selectors->len; ++i) {
9657 fprintf (acfg->fp, "L_OBJC_METH_VAR_NAME_%d:\n", i);
9658 fprintf (acfg->fp, ".asciz \"%s\"\n", (char*)g_ptr_array_index (acfg->objc_selectors, i));
9661 fprintf (acfg->fp, ".section __DATA,__objc_imageinfo,regular,no_dead_strip\n");
9662 fprintf (acfg->fp, ".align 3\n");
9663 fprintf (acfg->fp, "L_OBJC_IMAGE_INFO:\n");
9664 fprintf (acfg->fp, ".long 0\n");
9665 fprintf (acfg->fp, ".long 16\n");
9669 emit_dwarf_info (MonoAotCompile *acfg)
9671 #ifdef EMIT_DWARF_INFO
9675 /* DIEs for methods */
9676 for (i = 0; i < acfg->nmethods; ++i) {
9677 MonoCompile *cfg = acfg->cfgs [i];
9682 // FIXME: LLVM doesn't define .Lme_...
9683 if (cfg->compile_llvm)
9686 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
9688 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 ()));
9694 collect_methods (MonoAotCompile *acfg)
9697 MonoImage *image = acfg->image;
9699 /* Collect methods */
9700 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
9703 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
9705 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9708 aot_printerrf (acfg, "Failed to load method 0x%x from '%s' due to %s.\n", token, image->name, mono_error_get_message (&error));
9709 aot_printerrf (acfg, "Run with MONO_LOG_LEVEL=debug for more information.\n");
9710 mono_error_cleanup (&error);
9714 /* Load all methods eagerly to skip the slower lazy loading code */
9715 mono_class_setup_methods (method->klass);
9717 if (mono_aot_mode_is_full (&acfg->aot_opts) && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
9718 /* Compile the wrapper instead */
9719 /* We do this here instead of add_wrappers () because it is easy to do it here */
9720 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, TRUE, TRUE);
9724 /* FIXME: Some mscorlib methods don't have debug info */
9726 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
9727 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
9728 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
9729 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
9730 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
9731 if (!mono_debug_lookup_method (method)) {
9732 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_get_full_name (method));
9739 if (method->is_generic || method->klass->generic_container)
9740 /* Compile the ref shared version instead */
9741 method = mini_get_shared_method (method);
9743 /* Since we add the normal methods first, their index will be equal to their zero based token index */
9744 add_method_with_index (acfg, method, i, FALSE);
9745 acfg->method_index ++;
9748 /* gsharedvt methods */
9749 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
9752 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
9754 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
9757 method = mono_get_method_checked (acfg->image, token, NULL, NULL, &error);
9758 report_loader_error (acfg, &error, "Failed to load method token 0x%x due to %s\n", i, mono_error_get_message (&error));
9760 if (method->is_generic || method->klass->generic_container) {
9761 MonoMethod *gshared;
9763 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
9764 add_extra_method (acfg, gshared);
9768 add_generic_instances (acfg);
9770 if (mono_aot_mode_is_full (&acfg->aot_opts))
9771 add_wrappers (acfg);
9776 compile_methods (MonoAotCompile *acfg)
9780 if (acfg->aot_opts.nthreads > 0) {
9785 gpointer *user_data;
9786 MonoMethod **methods;
9788 methods_len = acfg->methods->len;
9790 len = acfg->methods->len / acfg->aot_opts.nthreads;
9793 * Partition the list of methods into fragments, and hand it to threads to
9796 threads = g_ptr_array_new ();
9797 /* Make a copy since acfg->methods is modified by compile_method () */
9798 methods = g_new0 (MonoMethod*, methods_len);
9799 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
9800 for (i = 0; i < methods_len; ++i)
9801 methods [i] = (MonoMethod *)g_ptr_array_index (acfg->methods, i);
9803 while (i < methods_len) {
9804 frag = g_ptr_array_new ();
9805 for (j = 0; j < len; ++j) {
9806 if (i < methods_len) {
9807 g_ptr_array_add (frag, methods [i]);
9812 user_data = g_new0 (gpointer, 3);
9813 user_data [0] = mono_domain_get ();
9814 user_data [1] = acfg;
9815 user_data [2] = frag;
9817 handle = mono_threads_create_thread (compile_thread_main, (gpointer) user_data, NULL, NULL);
9818 g_ptr_array_add (threads, handle);
9822 for (i = 0; i < threads->len; ++i) {
9823 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
9824 mono_threads_close_thread_handle (g_ptr_array_index (threads, i));
9830 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
9831 for (i = methods_len; i < acfg->methods->len; ++i) {
9832 /* This can new methods to acfg->methods */
9833 compile_method (acfg, (MonoMethod *)g_ptr_array_index (acfg->methods, i));
9838 compile_asm (MonoAotCompile *acfg)
9840 char *command, *objfile;
9841 char *outfile_name, *tmp_outfile_name, *llvm_ofile;
9842 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
9843 char *ld_flags = acfg->aot_opts.ld_flags ? acfg->aot_opts.ld_flags : g_strdup("");
9845 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
9846 #define AS_OPTIONS "--64"
9847 #elif defined(TARGET_POWERPC64)
9848 #define AS_OPTIONS "-a64 -mppc64"
9849 #elif defined(sparc) && SIZEOF_VOID_P == 8
9850 #define AS_OPTIONS "-xarch=v9"
9851 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9852 #define AS_OPTIONS "-arch i386"
9854 #define AS_OPTIONS ""
9857 #ifdef __native_client_codegen__
9858 #if defined(TARGET_AMD64)
9859 #define AS_NAME "nacl64-as"
9861 #define AS_NAME "nacl-as"
9863 #elif defined(TARGET_OSX)
9864 #define AS_NAME "clang"
9866 #define AS_NAME "as"
9870 #define LD_NAME "ld"
9871 #define LD_OPTIONS "-shared -G"
9872 #elif defined(__ppc__) && defined(TARGET_MACH)
9873 #define LD_NAME "gcc"
9874 #define LD_OPTIONS "-dynamiclib"
9875 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
9876 #define LD_NAME "clang"
9877 #define LD_OPTIONS "--shared"
9878 #elif defined(TARGET_WIN32) && !defined(TARGET_ANDROID)
9879 #define LD_NAME "gcc"
9880 #define LD_OPTIONS "-shared"
9881 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
9882 #define LD_NAME "clang"
9883 #define LD_OPTIONS "-m32 -dynamiclib"
9884 #elif defined(TARGET_ARM) && !defined(TARGET_ANDROID)
9885 #define LD_NAME "gcc"
9886 #define LD_OPTIONS "--shared"
9887 #elif defined(TARGET_POWERPC64)
9888 #define LD_OPTIONS "-m elf64ppc"
9892 #define LD_OPTIONS ""
9895 if (acfg->aot_opts.asm_only) {
9896 aot_printf (acfg, "Output file: '%s'.\n", acfg->tmpfname);
9897 if (acfg->aot_opts.static_link)
9898 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9900 aot_printf (acfg, "LLVM output file: '%s'.\n", acfg->llvm_sfile);
9904 if (acfg->aot_opts.static_link) {
9905 if (acfg->aot_opts.outfile)
9906 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9908 objfile = g_strdup_printf ("%s.o", acfg->image->name);
9910 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
9914 g_string_append (acfg->as_args, "-c -x assembler");
9917 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9918 acfg->as_args ? acfg->as_args->str : "",
9919 wrap_path (objfile), wrap_path (acfg->tmpfname));
9920 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9921 if (execute_system (command) != 0) {
9927 if (acfg->llvm && !acfg->llvm_owriter) {
9928 command = g_strdup_printf ("\"%s%s\" %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS,
9929 acfg->as_args ? acfg->as_args->str : "",
9930 wrap_path (acfg->llvm_ofile), wrap_path (acfg->llvm_sfile));
9931 aot_printf (acfg, "Executing the native assembler: %s\n", command);
9932 if (execute_system (command) != 0) {
9941 if (acfg->aot_opts.static_link) {
9942 aot_printf (acfg, "Output file: '%s'.\n", objfile);
9943 aot_printf (acfg, "Linking symbol: '%s'.\n", acfg->static_linking_symbol);
9948 if (acfg->aot_opts.outfile)
9949 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
9951 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, MONO_SOLIB_EXT);
9953 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
9956 llvm_ofile = g_strdup_printf ("\"%s\"", acfg->llvm_ofile);
9958 llvm_ofile = g_strdup ("");
9961 /* replace the ; flags separators with spaces */
9962 g_strdelimit (ld_flags, ";", ' ');
9964 if (acfg->aot_opts.llvm_only)
9965 ld_flags = g_strdup_printf ("%s %s", ld_flags, "-lstdc++");
9968 command = g_strdup_printf ("%s%s %s -o %s %s %s %s", tool_prefix, LD_NAME, LD_OPTIONS,
9969 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9970 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9973 if (acfg->aot_opts.tool_prefix) {
9974 /* Cross compiling */
9975 command = g_strdup_printf ("\"%sld\" %s -shared -o %s %s %s %s", tool_prefix, LD_OPTIONS,
9976 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9977 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9979 char *args = g_strdup_printf ("%s -shared -o %s %s %s %s", LD_OPTIONS,
9980 wrap_path (tmp_outfile_name), wrap_path (llvm_ofile),
9981 wrap_path (g_strdup_printf ("%s.o", acfg->tmpfname)), ld_flags);
9984 command = g_strdup_printf ("clang++ %s", args);
9986 command = g_strdup_printf ("\"%sld\" %s", tool_prefix, args);
9992 aot_printf (acfg, "Executing the native linker: %s\n", command);
9993 if (execute_system (command) != 0) {
9994 g_free (tmp_outfile_name);
9995 g_free (outfile_name);
10004 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, MONO_SOLIB_EXT);
10005 printf ("Stripping the binary: %s\n", com);
10006 execute_system (com);
10009 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
10011 * gas generates 'mapping symbols' each time code and data is mixed, which
10012 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
10014 command = g_strdup_printf ("\"%sstrip\" --strip-symbol=\\$a --strip-symbol=\\$d %s", wrap_path(tool_prefix), wrap_path(tmp_outfile_name));
10015 aot_printf (acfg, "Stripping the binary: %s\n", command);
10016 if (execute_system (command) != 0) {
10017 g_free (tmp_outfile_name);
10018 g_free (outfile_name);
10025 if (0 != rename (tmp_outfile_name, outfile_name)) {
10026 if (G_FILE_ERROR_EXIST == g_file_error_from_errno (errno)) {
10027 /* Since we are rebuilding the module we need to be able to replace any old copies. Remove old file and retry rename operation. */
10028 unlink (outfile_name);
10029 rename (tmp_outfile_name, outfile_name);
10033 #if defined(TARGET_MACH)
10034 command = g_strdup_printf ("dsymutil \"%s\"", outfile_name);
10035 aot_printf (acfg, "Executing dsymutil: %s\n", command);
10036 if (execute_system (command) != 0) {
10041 if (!acfg->aot_opts.save_temps)
10044 g_free (tmp_outfile_name);
10045 g_free (outfile_name);
10048 if (acfg->aot_opts.save_temps)
10049 aot_printf (acfg, "Retained input file.\n");
10051 unlink (acfg->tmpfname);
10056 static void init_got_info (GotInfo *info)
10060 info->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10061 info->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10062 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10063 info->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
10064 info->got_patches = g_ptr_array_new ();
10067 static MonoAotCompile*
10068 acfg_create (MonoAssembly *ass, guint32 opts)
10070 MonoImage *image = ass->image;
10071 MonoAotCompile *acfg;
10073 acfg = g_new0 (MonoAotCompile, 1);
10074 acfg->methods = g_ptr_array_new ();
10075 acfg->method_indexes = g_hash_table_new (NULL, NULL);
10076 acfg->method_depth = g_hash_table_new (NULL, NULL);
10077 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
10078 acfg->patch_to_plt_entry = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
10079 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
10080 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, NULL);
10081 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
10082 acfg->image_hash = g_hash_table_new (NULL, NULL);
10083 acfg->image_table = g_ptr_array_new ();
10084 acfg->globals = g_ptr_array_new ();
10085 acfg->image = image;
10087 /* TODO: Write out set of SIMD instructions used, rather than just those available */
10088 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
10089 acfg->mempool = mono_mempool_new ();
10090 acfg->extra_methods = g_ptr_array_new ();
10091 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
10092 acfg->unwind_ops = g_ptr_array_new ();
10093 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10094 acfg->method_order = g_ptr_array_new ();
10095 acfg->export_names = g_hash_table_new (NULL, NULL);
10096 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
10097 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
10098 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
10099 acfg->gsharedvt_in_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10100 acfg->gsharedvt_out_signatures = g_hash_table_new ((GHashFunc)mono_signature_hash, (GEqualFunc)mono_metadata_signature_equal);
10101 mono_os_mutex_init_recursive (&acfg->mutex);
10103 init_got_info (&acfg->got_info);
10104 init_got_info (&acfg->llvm_got_info);
10110 got_info_free (GotInfo *info)
10114 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10115 g_hash_table_destroy (info->patch_to_got_offset_by_type [i]);
10116 g_free (info->patch_to_got_offset_by_type);
10117 g_hash_table_destroy (info->patch_to_got_offset);
10118 g_ptr_array_free (info->got_patches, TRUE);
10122 acfg_free (MonoAotCompile *acfg)
10126 mono_img_writer_destroy (acfg->w);
10127 for (i = 0; i < acfg->nmethods; ++i)
10128 if (acfg->cfgs [i])
10129 mono_destroy_compile (acfg->cfgs [i]);
10131 g_free (acfg->cfgs);
10133 g_free (acfg->static_linking_symbol);
10134 g_free (acfg->got_symbol);
10135 g_free (acfg->plt_symbol);
10136 g_ptr_array_free (acfg->methods, TRUE);
10137 g_ptr_array_free (acfg->image_table, TRUE);
10138 g_ptr_array_free (acfg->globals, TRUE);
10139 g_ptr_array_free (acfg->unwind_ops, TRUE);
10140 g_hash_table_destroy (acfg->method_indexes);
10141 g_hash_table_destroy (acfg->method_depth);
10142 g_hash_table_destroy (acfg->plt_offset_to_entry);
10143 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i) {
10144 if (acfg->patch_to_plt_entry [i])
10145 g_hash_table_destroy (acfg->patch_to_plt_entry [i]);
10147 g_free (acfg->patch_to_plt_entry);
10148 g_hash_table_destroy (acfg->method_to_cfg);
10149 g_hash_table_destroy (acfg->token_info_hash);
10150 g_hash_table_destroy (acfg->method_to_pinvoke_import);
10151 g_hash_table_destroy (acfg->image_hash);
10152 g_hash_table_destroy (acfg->unwind_info_offsets);
10153 g_hash_table_destroy (acfg->method_label_hash);
10154 if (acfg->typespec_classes)
10155 g_hash_table_destroy (acfg->typespec_classes);
10156 g_hash_table_destroy (acfg->export_names);
10157 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
10158 g_hash_table_destroy (acfg->klass_blob_hash);
10159 g_hash_table_destroy (acfg->method_blob_hash);
10160 got_info_free (&acfg->got_info);
10161 got_info_free (&acfg->llvm_got_info);
10162 mono_mempool_destroy (acfg->mempool);
10166 #define WRAPPER(e,n) n,
10167 static const char* const
10168 wrapper_type_names [MONO_WRAPPER_NUM + 1] = {
10169 #include "mono/metadata/wrapper-types.h"
10173 static G_GNUC_UNUSED const char*
10174 get_wrapper_type_name (int type)
10176 return wrapper_type_names [type];
10182 static void aot_dump (MonoAotCompile *acfg)
10188 mono_json_writer_init (&writer);
10190 mono_json_writer_object_begin(&writer);
10193 mono_json_writer_indent (&writer);
10194 mono_json_writer_object_key(&writer, "methods");
10195 mono_json_writer_array_begin (&writer);
10198 for (i = 0; i < acfg->nmethods; ++i) {
10200 MonoMethod *method;
10203 cfg = acfg->cfgs [i];
10207 method = cfg->orig_method;
10209 mono_json_writer_indent (&writer);
10210 mono_json_writer_object_begin(&writer);
10212 mono_json_writer_indent (&writer);
10213 mono_json_writer_object_key(&writer, "name");
10214 mono_json_writer_printf (&writer, "\"%s\",\n", method->name);
10216 mono_json_writer_indent (&writer);
10217 mono_json_writer_object_key(&writer, "signature");
10218 mono_json_writer_printf (&writer, "\"%s\",\n", mono_method_get_full_name (method));
10220 mono_json_writer_indent (&writer);
10221 mono_json_writer_object_key(&writer, "code_size");
10222 mono_json_writer_printf (&writer, "\"%d\",\n", cfg->code_size);
10224 klass = method->klass;
10226 mono_json_writer_indent (&writer);
10227 mono_json_writer_object_key(&writer, "class");
10228 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name);
10230 mono_json_writer_indent (&writer);
10231 mono_json_writer_object_key(&writer, "namespace");
10232 mono_json_writer_printf (&writer, "\"%s\",\n", klass->name_space);
10234 mono_json_writer_indent (&writer);
10235 mono_json_writer_object_key(&writer, "wrapper_type");
10236 mono_json_writer_printf (&writer, "\"%s\",\n", get_wrapper_type_name(method->wrapper_type));
10238 mono_json_writer_indent_pop (&writer);
10239 mono_json_writer_indent (&writer);
10240 mono_json_writer_object_end (&writer);
10241 mono_json_writer_printf (&writer, ",\n");
10244 mono_json_writer_indent_pop (&writer);
10245 mono_json_writer_indent (&writer);
10246 mono_json_writer_array_end (&writer);
10247 mono_json_writer_printf (&writer, ",\n");
10251 mono_json_writer_indent_push (&writer);
10252 mono_json_writer_indent (&writer);
10253 mono_json_writer_object_key(&writer, "plt");
10254 mono_json_writer_array_begin (&writer);
10256 for (i = 0; i < acfg->plt_offset; ++i) {
10257 MonoPltEntry *plt_entry = NULL;
10262 * The first plt entry is unused.
10266 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
10267 ji = plt_entry->ji;
10269 mono_json_writer_indent (&writer);
10270 mono_json_writer_printf (&writer, "{ ");
10271 mono_json_writer_object_key(&writer, "symbol");
10272 mono_json_writer_printf (&writer, "\"%s\" },\n", plt_entry->symbol);
10275 mono_json_writer_indent_pop (&writer);
10276 mono_json_writer_indent (&writer);
10277 mono_json_writer_array_end (&writer);
10278 mono_json_writer_printf (&writer, ",\n");
10283 mono_json_writer_indent_push (&writer);
10284 mono_json_writer_indent (&writer);
10285 mono_json_writer_object_key(&writer, "got");
10286 mono_json_writer_array_begin (&writer);
10288 mono_json_writer_indent_push (&writer);
10289 for (i = 0; i < acfg->got_info.got_patches->len; ++i) {
10290 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_info.got_patches, i);
10292 mono_json_writer_indent (&writer);
10293 mono_json_writer_printf (&writer, "{ ");
10294 mono_json_writer_object_key(&writer, "patch_name");
10295 mono_json_writer_printf (&writer, "\"%s\" },\n", get_patch_name (ji->type));
10298 mono_json_writer_indent_pop (&writer);
10299 mono_json_writer_indent (&writer);
10300 mono_json_writer_array_end (&writer);
10301 mono_json_writer_printf (&writer, ",\n");
10304 mono_json_writer_indent_pop (&writer);
10305 mono_json_writer_indent (&writer);
10306 mono_json_writer_object_end (&writer);
10308 dumpname = g_strdup_printf ("%s.json", g_path_get_basename (acfg->image->name));
10309 dumpfile = fopen (dumpname, "w+");
10312 fprintf (dumpfile, "%s", writer.text->str);
10315 mono_json_writer_destroy (&writer);
10318 static const char *preinited_jit_icalls[] = {
10319 "mono_aot_init_llvm_method",
10320 "mono_aot_init_gshared_method_this",
10321 "mono_aot_init_gshared_method_mrgctx",
10322 "mono_aot_init_gshared_method_vtable",
10323 "mono_llvm_throw_corlib_exception",
10324 "mono_init_vtable_slot",
10325 "mono_helper_ldstr_mscorlib"
10329 add_preinit_got_slots (MonoAotCompile *acfg)
10335 * Allocate the first few GOT entries to information which is needed frequently, or it is needed
10336 * during method initialization etc.
10339 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10340 ji->type = MONO_PATCH_INFO_IMAGE;
10341 ji->data.image = acfg->image;
10342 get_got_offset (acfg, FALSE, ji);
10343 get_got_offset (acfg, TRUE, ji);
10345 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10346 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
10347 get_got_offset (acfg, FALSE, ji);
10348 get_got_offset (acfg, TRUE, ji);
10350 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10351 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
10352 get_got_offset (acfg, FALSE, ji);
10353 get_got_offset (acfg, TRUE, ji);
10355 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10356 ji->type = MONO_PATCH_INFO_GC_NURSERY_START;
10357 get_got_offset (acfg, FALSE, ji);
10358 get_got_offset (acfg, TRUE, ji);
10360 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10361 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
10362 get_got_offset (acfg, FALSE, ji);
10363 get_got_offset (acfg, TRUE, ji);
10365 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10366 ji->type = MONO_PATCH_INFO_AOT_MODULE;
10367 get_got_offset (acfg, FALSE, ji);
10368 get_got_offset (acfg, TRUE, ji);
10370 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoJumpInfo));
10371 ji->type = MONO_PATCH_INFO_GC_NURSERY_BITS;
10372 get_got_offset (acfg, FALSE, ji);
10373 get_got_offset (acfg, TRUE, ji);
10375 for (i = 0; i < sizeof (preinited_jit_icalls) / sizeof (char*); ++i) {
10376 ji = (MonoJumpInfo *)mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
10377 ji->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10378 ji->data.name = preinited_jit_icalls [i];
10379 get_got_offset (acfg, FALSE, ji);
10380 get_got_offset (acfg, TRUE, ji);
10383 acfg->nshared_got_entries = acfg->got_offset;
10387 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10389 MonoImage *image = ass->image;
10392 MonoAotCompile *acfg;
10393 char *outfile_name, *tmp_outfile_name, *p;
10394 char llvm_stats_msg [256];
10398 acfg = acfg_create (ass, opts);
10400 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
10401 acfg->aot_opts.write_symbols = TRUE;
10402 acfg->aot_opts.ntrampolines = 4096;
10403 acfg->aot_opts.nrgctx_trampolines = 4096;
10404 acfg->aot_opts.nimt_trampolines = 512;
10405 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
10406 acfg->aot_opts.ngsharedvt_arg_trampolines = 512;
10407 acfg->aot_opts.llvm_path = g_strdup ("");
10408 acfg->aot_opts.temp_path = g_strdup ("");
10410 acfg->aot_opts.use_trampolines_page = TRUE;
10413 mono_aot_parse_options (aot_options, &acfg->aot_opts);
10415 if (acfg->aot_opts.logfile) {
10416 acfg->logfile = fopen (acfg->aot_opts.logfile, "a+");
10419 if (acfg->aot_opts.data_outfile) {
10420 acfg->data_outfile = fopen (acfg->aot_opts.data_outfile, "w+");
10421 if (!acfg->data_outfile) {
10422 aot_printerrf (acfg, "Unable to create file '%s': %s\n", acfg->aot_opts.data_outfile, strerror (errno));
10425 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SEPARATE_DATA);
10428 //acfg->aot_opts.print_skipped_methods = TRUE;
10430 #if !defined(MONO_ARCH_GSHAREDVT_SUPPORTED)
10431 if (acfg->opts & MONO_OPT_GSHAREDVT) {
10432 aot_printerrf (acfg, "-O=gsharedvt not supported on this platform.\n");
10435 if (acfg->aot_opts.llvm_only) {
10436 aot_printerrf (acfg, "--aot=llvmonly requires a runtime that supports gsharedvt.\n");
10440 if (acfg->aot_opts.llvm_only || mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10441 acfg->opts |= MONO_OPT_GSHAREDVT;
10444 #if !defined(ENABLE_LLVM)
10445 if (acfg->aot_opts.llvm_only) {
10446 aot_printerrf (acfg, "--aot=llvmonly requires a runtime compiled with llvm support.\n");
10451 if (acfg->opts & MONO_OPT_GSHAREDVT)
10452 mono_set_generic_sharing_vt_supported (TRUE);
10454 aot_printf (acfg, "Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
10456 generate_aotid ((guint8*) &acfg->image->aotid);
10458 char *aotid = mono_guid_to_string (acfg->image->aotid);
10459 aot_printf (acfg, "AOTID %s\n", aotid);
10462 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
10463 if (mono_aot_mode_is_full (&acfg->aot_opts)) {
10464 aot_printerrf (acfg, "--aot=full is not supported on this platform.\n");
10469 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
10470 aot_printerrf (acfg, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
10474 if (acfg->aot_opts.static_link)
10475 acfg->aot_opts.asm_writer = TRUE;
10477 if (acfg->aot_opts.soft_debug) {
10478 MonoDebugOptions *opt = mini_get_debug_options ();
10480 opt->mdb_optimizations = TRUE;
10481 opt->gen_sdb_seq_points = TRUE;
10483 if (!mono_debug_enabled ()) {
10484 aot_printerrf (acfg, "The soft-debug AOT option requires the --debug option.\n");
10487 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_DEBUG);
10490 if (mono_use_llvm || acfg->aot_opts.llvm) {
10492 acfg->aot_opts.asm_writer = TRUE;
10493 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_WITH_LLVM);
10495 if (acfg->aot_opts.soft_debug) {
10496 aot_printerrf (acfg, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
10502 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_outfile) {
10503 aot_printerrf (acfg, "Compiling with LLVM and the asm-only option requires the llvm-outputfile= option.");
10508 if (mono_aot_mode_is_full (&acfg->aot_opts))
10509 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_FULL_AOT);
10511 if (mono_threads_is_coop_enabled ())
10512 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_SAFEPOINTS);
10514 if (acfg->aot_opts.instances_logfile_path) {
10515 acfg->instances_logfile = fopen (acfg->aot_opts.instances_logfile_path, "w");
10516 if (!acfg->instances_logfile) {
10517 aot_printerrf (acfg, "Unable to create logfile: '%s'.\n", acfg->aot_opts.instances_logfile_path);
10522 load_profile_files (acfg);
10524 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ntrampolines : 0;
10525 #ifdef MONO_ARCH_GSHARED_SUPPORTED
10526 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nrgctx_trampolines : 0;
10528 acfg->num_trampolines [MONO_AOT_TRAMP_IMT] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.nimt_trampolines : 0;
10529 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
10530 if (acfg->opts & MONO_OPT_GSHAREDVT)
10531 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = mono_aot_mode_is_full (&acfg->aot_opts) ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
10534 acfg->temp_prefix = mono_img_writer_get_temp_label_prefix (NULL);
10538 if (mono_use_llvm || acfg->aot_opts.llvm) {
10541 * Emit all LLVM code into a separate assembly/object file and link with it
10544 if (!acfg->aot_opts.asm_only && acfg->llvm_owriter_supported) {
10545 acfg->llvm_owriter = TRUE;
10546 } else if (acfg->aot_opts.llvm_outfile) {
10547 int len = strlen (acfg->aot_opts.llvm_outfile);
10549 if (len >= 2 && acfg->aot_opts.llvm_outfile [len - 2] == '.' && acfg->aot_opts.llvm_outfile [len - 1] == 'o')
10550 acfg->llvm_owriter = TRUE;
10554 if (acfg->llvm && acfg->thumb_mixed)
10555 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_THUMB);
10556 if (acfg->aot_opts.llvm_only)
10557 acfg->flags = (MonoAotFileFlags)(acfg->flags | MONO_AOT_FILE_FLAG_LLVM_ONLY);
10559 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
10560 /* Get rid of characters which cannot occur in symbols */
10561 for (p = acfg->assembly_name_sym; *p; ++p) {
10562 if (!(isalnum (*p) || *p == '_'))
10566 acfg->global_prefix = g_strdup_printf ("mono_aot_%s", acfg->assembly_name_sym);
10567 acfg->plt_symbol = g_strdup_printf ("%s_plt", acfg->global_prefix);
10568 acfg->got_symbol = g_strdup_printf ("%s_got", acfg->global_prefix);
10570 acfg->llvm_got_symbol = g_strdup_printf ("%s_llvm_got", acfg->global_prefix);
10571 acfg->llvm_eh_frame_symbol = g_strdup_printf ("%s_eh_frame", acfg->global_prefix);
10574 acfg->method_index = 1;
10576 if (mono_aot_mode_is_full (&acfg->aot_opts) || mono_aot_mode_is_hybrid (&acfg->aot_opts))
10577 mono_set_partial_sharing_supported (TRUE);
10579 res = collect_methods (acfg);
10583 acfg->cfgs_size = acfg->methods->len + 32;
10584 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
10586 /* PLT offset 0 is reserved for the PLT trampoline */
10587 acfg->plt_offset = 1;
10588 add_preinit_got_slots (acfg);
10593 mono_llvm_create_aot_module (acfg->image->assembly, acfg->global_prefix, TRUE, acfg->aot_opts.static_link, acfg->aot_opts.llvm_only);
10599 compile_methods (acfg);
10603 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
10609 if (acfg->aot_opts.asm_only) {
10610 if (acfg->aot_opts.outfile) {
10611 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10612 acfg->tmpbasename = g_strdup (acfg->tmpfname);
10614 acfg->tmpbasename = g_strdup_printf ("%s", acfg->image->name);
10615 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10617 g_assert (acfg->aot_opts.llvm_outfile);
10618 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10619 if (acfg->llvm_owriter)
10620 acfg->llvm_ofile = g_strdup (acfg->aot_opts.llvm_outfile);
10622 acfg->llvm_sfile = g_strdup (acfg->aot_opts.llvm_outfile);
10624 acfg->tmpbasename = (strcmp (acfg->aot_opts.temp_path, "") == 0) ?
10625 g_strdup_printf ("%s", "temp") :
10626 g_build_filename (acfg->aot_opts.temp_path, "temp", NULL);
10628 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->tmpbasename);
10629 acfg->llvm_sfile = g_strdup_printf ("%s-llvm.s", acfg->tmpbasename);
10630 acfg->llvm_ofile = g_strdup_printf ("%s-llvm.o", acfg->tmpbasename);
10635 if (acfg->aot_opts.asm_only && !acfg->aot_opts.llvm_only) {
10636 if (acfg->aot_opts.outfile)
10637 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
10639 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
10640 acfg->fp = fopen (acfg->tmpfname, "w+");
10642 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
10643 acfg->fp = fdopen (i, "w+");
10645 if (acfg->fp == 0 && !acfg->aot_opts.llvm_only) {
10646 aot_printerrf (acfg, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
10650 acfg->w = mono_img_writer_create (acfg->fp, FALSE);
10652 tmp_outfile_name = NULL;
10653 outfile_name = NULL;
10655 /* Compute symbols for methods */
10656 for (i = 0; i < acfg->nmethods; ++i) {
10657 if (acfg->cfgs [i]) {
10658 MonoCompile *cfg = acfg->cfgs [i];
10659 int method_index = get_method_index (acfg, cfg->orig_method);
10661 if (COMPILE_LLVM (cfg))
10662 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
10663 else if (acfg->global_symbols || acfg->llvm)
10664 cfg->asm_symbol = get_debug_sym (cfg->orig_method, "", acfg->method_label_hash);
10666 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
10667 cfg->asm_debug_symbol = cfg->asm_symbol;
10671 if (acfg->aot_opts.dwarf_debug && acfg->aot_opts.gnu_asm) {
10673 * CLANG supports GAS .file/.loc directives, so emit line number information this way
10675 acfg->gas_line_numbers = TRUE;
10678 if ((!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) && acfg->has_jitted_code) {
10679 if (acfg->aot_opts.dwarf_debug && !mono_debug_enabled ()) {
10680 aot_printerrf (acfg, "The dwarf AOT option requires the --debug option.\n");
10683 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, !acfg->gas_line_numbers);
10687 mono_img_writer_emit_start (acfg->w);
10690 mono_dwarf_writer_emit_base_info (acfg->dwarf, g_path_get_basename (acfg->image->name), mono_unwind_get_cie_program ());
10696 emit_extra_methods (acfg);
10698 emit_trampolines (acfg);
10700 emit_class_name_table (acfg);
10702 emit_got_info (acfg, FALSE);
10704 emit_got_info (acfg, TRUE);
10706 emit_exception_info (acfg);
10708 emit_unwind_info (acfg);
10710 emit_class_info (acfg);
10714 emit_image_table (acfg);
10720 * The managed allocators are GC specific, so can't use an AOT image created by one GC
10723 const char *gc_name = mono_gc_get_gc_name ();
10724 acfg->gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
10729 emit_objc_selectors (acfg);
10731 emit_globals (acfg);
10733 emit_file_info (acfg);
10736 emit_dwarf_info (acfg);
10737 mono_dwarf_writer_close (acfg->dwarf);
10740 emit_mem_end (acfg);
10742 if (acfg->need_pt_gnu_stack) {
10743 /* This is required so the .so doesn't have an executable stack */
10744 /* The bin writer already emits this */
10745 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
10748 if (acfg->aot_opts.data_outfile)
10749 fclose (acfg->data_outfile);
10755 res = emit_llvm_file (acfg);
10763 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
10766 sprintf (llvm_stats_msg, ", LLVM: %d (%d%%)", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
10768 strcpy (llvm_stats_msg, "");
10770 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;
10772 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",
10773 (int)acfg->stats.code_size, (int)(acfg->stats.code_size * 100 / all_sizes),
10774 (int)acfg->stats.info_size, (int)(acfg->stats.info_size * 100 / all_sizes),
10775 (int)acfg->stats.ex_info_size, (int)(acfg->stats.ex_info_size * 100 / all_sizes),
10776 (int)acfg->stats.unwind_info_size, (int)(acfg->stats.unwind_info_size * 100 / all_sizes),
10777 (int)acfg->stats.class_info_size, (int)(acfg->stats.class_info_size * 100 / all_sizes),
10778 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,
10779 (int)acfg->stats.got_info_size, (int)(acfg->stats.got_info_size * 100 / all_sizes),
10780 (int)acfg->stats.offsets_size, (int)(acfg->stats.offsets_size * 100 / all_sizes),
10781 (int)(acfg->got_offset * sizeof (gpointer)));
10782 aot_printf (acfg, "Compiled: %d/%d (%d%%)%s, No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
10783 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
10785 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
10786 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
10787 if (acfg->stats.genericcount)
10788 aot_printf (acfg, "%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
10789 if (acfg->stats.abscount)
10790 aot_printf (acfg, "%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
10791 if (acfg->stats.lmfcount)
10792 aot_printf (acfg, "%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
10793 if (acfg->stats.ocount)
10794 aot_printf (acfg, "%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
10798 res = mono_img_writer_emit_writeout (acfg->w);
10803 res = compile_asm (acfg);
10810 acfg->stats.link_time = TV_ELAPSED (atv, btv);
10812 if (acfg->aot_opts.stats) {
10815 aot_printf (acfg, "GOT slot distribution:\n");
10816 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
10817 if (acfg->stats.got_slot_types [i])
10818 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]);
10819 aot_printf (acfg, "\nMethod stats:\n");
10820 aot_printf (acfg, "\tNormal: %d\n", acfg->stats.method_categories [METHOD_CAT_NORMAL]);
10821 aot_printf (acfg, "\tInstance: %d\n", acfg->stats.method_categories [METHOD_CAT_INST]);
10822 aot_printf (acfg, "\tGSharedvt: %d\n", acfg->stats.method_categories [METHOD_CAT_GSHAREDVT]);
10823 aot_printf (acfg, "\tWrapper: %d\n", acfg->stats.method_categories [METHOD_CAT_WRAPPER]);
10826 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);
10828 if (acfg->aot_opts.dump_json)
10841 mono_aot_readonly_field_override (MonoClassField *field)
10847 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
10853 mono_aot_is_shared_got_offset (int offset)